Przejdź do treści
Biblioteka skilli
Nauka i badania · Planowanie

neqsim-task-workflow

/neqsim-task-workflow

Prowadzi przez pełny proces zadania inżynierskiego w NeqSim: zakres, analizę, notebooki z walidacją, kontrolę jakości i raport.

Repozytorium
neqsim ↗
Licencja
Apache-2.0
Ostatnia zmiana repozytorium
27.10.2026

Ocena i bezpieczeństwo

91/ 100Klasa: dobry
Format25 / 25
Frontmatter z nazwą i opisem, poprawna nazwa, opis do 1024 znaków, nazwa zgodna z folderem.
Odkrywalność25 / 25
Opis mówi, kiedy użyć skilla, ma sensowną długość i jest w 3. osobie.
Treść26 / 35
Co najmniej 150 słów i do 500 linii, nagłówki, listy kroków, przykłady albo kod.
Higiena15 / 15
Bez zaślepek typu TODO, bez ścieżek Windows, z licencją.
Ryzykobrak sygnałów w skanie
Pliki w paczce
1
Skrypty
0
Komentarze HTML
0
Adresy URL w SKILL.md
0
Przestarzałość

Brak sygnałów. Repozytorium zmienione 27.10.2026, bez odwołań do wycofanych modeli i API.

Licencja

Apache-2.0, otwarta: można używać i zmieniać, z zachowaniem licencji i informacji o zmianach.

Co robi i kiedy

Prowadzi przez pełny proces zadania inżynierskiego w NeqSim: zakres, analizę, notebooki z walidacją, kontrolę jakości i raport.

Oryginalny opis (EN)

The full NeqSim engineering task workflow that @solve-task orchestrates. USE WHEN: executing any Standard or Comprehensive task end to end - setup and scale classification, scope and research, deep analysis, notebooks with benchmark validation and uncertainty/risk, quality gates, report and work record, knowledge capture, task-type guidance, delegation, NeqSim Improvement Proposals and lessons learned. Load one phase section at a time.

Jak działa

  1. 0.5 ── ALWAYS-ON OBLIGATIONS (moved from the agent)
  2. 0.6 ── OPERATING ENVIRONMENTS (what each step needs)
  3. 1 ── OVERVIEW
  4. 1.5 ── CONTEXT WINDOW RESILIENCE (checkpoint & resume)
  5. 2 ── WORKFLOW (follow this exactly)
  6. 3 ── TASK TYPE SPECIFIC GUIDANCE
  7. 4 ── NOTEBOOK SETUP PATTERN
  8. 5 ── DELEGATE TO SPECIALIST AGENTS
  9. 6 ── NEQSIM IMPROVEMENT PROPOSALS (when material gaps are found)
  10. 7 ── ENGINEERING INTERPRETATION IN REPORTS
Sekcje z nagłówków SKILL.md, w oryginale · 2 559 linii, 19 491 słów
Podgląd SKILL.md
---
name: neqsim-task-workflow
description: "The full NeqSim engineering task workflow that @solve-task orchestrates. USE WHEN: executing any Standard or Comprehensive task end to end - setup and scale classification, scope and research, deep analysis, notebooks with benchmark validation and uncertainty/risk, quality gates, report and work record, knowledge capture, task-type guidance, delegation, NeqSim Improvement Proposals and lessons learned. Load one phase section at a time."
last_verified: "2026-09-18"
---

# NeqSim Task Workflow

This is the detailed procedure behind `@solve-task`. The agent file holds the
mandatory first action, the purpose, and the operating principles (section 0);
sections 1-10 below are loaded on demand for Standard and Comprehensive work.
Section numbers are kept so cross-references from the agent and from
`docs/development/TASK_SOLVING_GUIDE.md` stay valid.

---

## 0.5 ── ALWAYS-ON OBLIGATIONS (moved from the agent)

### Keep `user_input.md` up to date through the whole conversation

`user_input.md` is the **reproducibility log** — anyone re-running this task
should be able to recover the exact starting input from it.

**Whenever the user provides new information during the task, append it to
`user_input.md` immediately and verbatim:**

- Answers to your clarifying questions → append to **section 2 (Q&A)**
- Mid-task corrections, scope changes, or new constraints → append to **section 3 (Follow-up)**
- Any value you assume because the user did not specify it → record it in **section 4 (Inferred Assumptions)** with justification

Do NOT paraphrase, summarise, or "clean up" the user's wording. Paste it as
given. Never delete previous entries — only append.

### All downloaded documents go INSIDE the task folder

**All documents retrieved during a task — STID drawings, PI historian exports,
vendor datasheets, P&IDs, literature PDFs, downloaded standards — MUST be saved
to `step1_scope_and_research/references/` within the task folder.**

NEVER download or save task-related files to workspace-level directories like
`output/`, `figures/`, or any path outside `task_solve/YYYY-MM-DD_slug/`.

**For STID/document retrieval scripts:** Always pass the task's `references/`
path as the output directory:
```python
# CORRECT — saves inside the task folder:
out_dir = os.path.join(TASK_DIR, "step1_scope_and_research", "references")

# WRONG — saves outside the task folder:
out_dir = os.path.join(os.path.dirname(__file__), "..", "figures", "stid_docs")  # NEVER DO THIS
```

**For PDF-to-PNG conversion:** Output converted images to the task's `figures/`:
```bash
<python-executable> devtools/pdf_to_figures.py task_solve/YYYY-MM-DD_slug/step1_scope_and_research/references/ \
    --outdir task_solve/YYYY-MM-DD_slug/figures/
```

This ensures every task is self-contained and portable — zip the task folder
and everything needed is inside it.

### Extract every downloaded or supplied document before solving

The `references/` folder is not passive storage. Before any document-derived
value, topology, limit, requirement, or recommendation enters Step 2, route
**every file** through `technical-document-intelligence-agent` using
`neqsim-document-intelligence-extraction`, then through the applicable
document-type/domain reader.

For each file:

1. Preserve the original and record its hash, actual format, revision/date, and
  extraction-tool versions.
2. Run native text and structured-table extraction first. For spreadsheets,
  retain sheets, formulas, merged ranges, hidden rows/columns, headers, and units.
3. Render and assess every page that contains visual or spatial information.
  Use OCR for scans and multimodal vision for drawings, P&IDs, charts, maps,
  photographs, annotations, symbols, topology, and table layout. OCR alone is
  not sufficient for visual engineering content.
4. Extract comprehensively: body text, tables, title blocks, notes, legends,
  appendices, footnotes, figures, plots, revision clouds, and unexpected
  engineering constraints. Do not stop after finding the fields anticipated by
  the initial task description.
5. Package facts with original text/value/unit, page/cell/bounding-box locator,
  method, confidence, normalized value/unit, and review status. Reconcile
  native/OCR/vision outputs without silently resolving conflicts.
6. Record unsupported content, missing expected fields, conflicts, ambiguous
  facts, and safety-critical or confidence-below-0.85 facts as explicit gaps or
  `needs_review` items.

Write `step1_scope_and_research/document_evidence_manifest.json` with one entry
for every file under `references/`, its extraction operations and status, links
to its evidence package(s), and counts of facts/conflicts/gaps/review items.
Summarize the evidence in `notes.md` and preserve fact identifiers in downstream
inputs/results. The number of manifest source entries MUST equal the recursive
file inventory count, excluding generated evidence packages and the manifest
itself. Do not begin Step 2 while any source is `not_started` or silently
unprocessed; record a blocked/manual-review status when extraction cannot run.

---

## 0.6 ── OPERATING ENVIRONMENTS (what each step needs)

The workflow below was written in the NeqSim source checkout. It also runs from
the pip-installed toolkit (`neqsim-dev-setup`, installed automatically by the
core agent plugin's SessionStart hook) and, degraded, from chat with only the
MCP server. Detect the environment first (agent Step 0) and apply this table.

| Step / tool | Workspace (checkout) | Toolkit (pip, no checkout) | Chat-only (MCP) |
|---|---|---|---|
| `neqsim new-task`, `user_input.md`, `study_config.yaml` | yes | yes | create folder by hand from the template layout |
| `neqsim_dev_setup.neqsim_init()` | `target/classes` (latest Java) | packaged JAR from `pip install neqsim` (`ns.JAR_MODE`, `ns.MISSING_CLASSES`) | not available - use MCP `runFlash`/`runProcess`/`runPVT` |
| `recompile=True`, `mvnw`, Java classes + JUnit (NIP implementation) | yes | **no** - write the NIP, do not attempt | no |
| NeqSim Runner (`AgentBridge`, `neqsim_runner`) | yes | yes | no - run scripts directly or use MCP |
| `validate_task_results`, `consistency_checker`, `TaskResultValidator` | yes | yes (Python validators; the Java `TaskResultValidator` needs the JAR, available) | Python validators not installed - state results.json was not gate-checked |
| `neqsim report` / `generate_report.py`, `WORK_RECORD.md` | yes | yes (Word template optional) | no - deliver the summary in chat |
| `skill_search` / `agent_search`, `capability_assessment.md` | yes | yes | by reasoning over the skill catalogue only |
| Enterprise data readers (STID, SAP, PDM, OTS, Seeq, PEPR) | with credentials | with credentials (enterprise plugin installs the packages) | no |
| Task log / PR back to NeqSim | yes | NIP + issue only | NIP in the answer |

When a row says **no**, the deliverable matrix in the agent's section 0 still
applies: do the step by the strongest available means and record what was
skipped in `results.json` `data_gaps` (or in the chat answer) so the reader knows
the evidence level.

---

## 1 ── OVERVIEW

You follow the **3-step AI-Supported Task Solving While Developing** workflow.
"While Developing" is key — solving the task and improving NeqSim happen in
the same session. The workflow is aligned with the IPA Front-End Loading (FEL)
framework and Stage-Gate methodology:

```
 STEP 1 → Scope & Research    (FEL-1: Identify)    Define standards, methods, deliverables + gather background
 STEP 2 → Analysis & Eval     (FEL-2: Evaluate)     Build simulation, run, validate, iterate until accepted
 STEP 3 → Report              (FEL-3: Define)       Generate Word + HTML deliverables
```

Each step transition is a **gate** (per Stage-Gate, Cooper 1990) — the quality
gates in Section 2 define the go/no-go criteria before advancing.

The framework also draws on:
- **AACE 18R-97** — Cost estimate classification (Class 5→1 maturity)
- **ISO 15288** — Systems engineering life cycle (needs → requirements → architecture → verification)
- **VDI 2221** — Systematic engineering design (clarify → concept → embody → detail)
- **NORSOK Z-013** — Risk and emergency preparedness (risk matrix, ALARP)
- **DNV-RP-A203** — Technology qualification (TRL assessment for novel solutions)

Your deliverable is a populated task folder under `task_solve/`.

### Post-Folder Preflight (mandatory before Step 1 work)

After the task folder exists and `user_input.md` contains the prompt, do these
checks before writing Step 1 content:

1. **Route check.** If the task spans multiple disciplines (e.g. process +
   economics + safety), invoke `@router` first to confirm which specialist
   agents to compose. For single-discipline tasks, skip.
2. **Agent & skill review (ALWAYS — thorough).** Before writing any analysis,
   do a deliberate review of the available **agents and skills** to find what
   can help solve this task instead of solving from scratch:
  - Run `<python-executable> devtools/skill_search.py "<task title>" --top 5` and load the
     top-3 SKILL.md files with `read_file`.
   - Scan the agent list (community + enterprise, e.g. `.github/agents/`,
     `neqsim-community-agents/`, `neqsim-enterprise-agents/`) for discipline
     specialists whose description matches the engineering question.
   - Record the shortlist in `step1_scope_and_research/notes.md`: which
     agents/skills you will use and why, and note explicitly where **no**
     suitable agent/skill exists (that gap is a candidate improvement in the
     Continuous Improvement Rule).
3. **NeqSim codebase review (ALWAYS).** Before writing custom code, review the
   NeqSim codebase to find existing functionality that solves the task:
   - Consult `neqsim-capability-map` and `CHANGELOG_AGENT_NOTES.md`, then use
     `semantic_search` / `grep_search` / `file_search` over
     `src/main/java/neqsim/` for the relevant classes (equipment, EOS,
     standards, mechanical design).
   - Prefer an existing NeqSim class over a simplified Python correlation.
   - Record in `notes.md` which NeqSim classes/methods will be used, and note
     any missing capability as a gap to be closed (NIP + Java implementation
     per Section 0 principle 2 and the Continuous Improvement Rule).
3b. **Data-acquisition screening (ALWAYS — before assuming stand-in data).**
   List the input data the task needs (equipment curves, geometry, fluid
   composition, operating point, etc.) and, for **each** input, screen for a
   retrieval tool/agent that can obtain the *real* value before falling back to
   a representative assumption. Do NOT proceed with stand-in data for an input
   that an available data-source agent could supply. Map each need to its
   source using this table (community names shown; use the `enterprise-` twin
   when on an enterprise task):

   | Data need | Retrieve with | Notes |
   |-----------|---------------|-------|
   | Compressor/pump curves, vendor performance maps, datasheets, P&IDs, mechanical drawings, line lists, material certs | `@stid.reader` / `stid-reader-agent` + `neqsim-stid-retriever` (STID doc download → PDF/OCR → `neqsim-technical-document-reading`) | Vendor "map"/curve docs live in STID; download then extract the map digitally |
   | Piping class, pipe internal diameter, wall thickness, valve (VDS/MDS) data, flange rating | `@tr2000` / `tr2000-agent` + `enterprise-tr2000-api` | Resolve line tag → PCS → internal Ø |
   | Live instrument data / operating point (P, T, flow, speed, valve %, current recycle) | `@plant-data` / `plant-data-agent` + `neqsim-plant-data` (tagreader PI/IP.21) or `@seeq.connect` / `enterprise-seeq-connect` | Resolve historian tag from STID tag; prefer `/PRIM` channel; check units |
   | Measured production volumes (well/field) | `rigga-production-agent` + `enterprise-rigga-production` | Measured production as feed / validation basis |
   | Equipment / maintenance / failure history | `@maintenance` / `maintenance-agent` + `enterprise-maintenance-api` | Read-only work orders, notifications |
   | Picture of real equipment: location, layout, access, a vessel with its valves and instruments, a proposed modification against the As-Built model | `enterprise-stid-agent` (tags, valves, instruments, nozzle schedule, GA drawing) **together with** `enterprise-echo-3d-agent` + `enterprise-echo-3d` (Equinor Echo digital twin, via `prd-ai-skills` echo-toolkit) | Write `step1_scope_and_research/echo_plan.json`, run `echo-3d task --task <task>`; the user names the Echo 3D project(s); "not modelled" is not "not installed"; indicative, not a measurement |
   | Fluid composition / gas-sample molweight | STID/lab report via `@stid.reader`; else record as an explicit gap | A wrong MW mis-places compressor maps — always try to obtain it |
   | Public literature / standards | `@literature-scout` | See step 6 |

   Record in `notes.md`, for every required input: the source agent/skill you
   will use, or an explicit statement that the value is a documented **stand-in
   assumption** because no retrieval path is available (and why). "The data is a
   field unknown" is only acceptable **after** the relevant retrieval agent has
   been screened (and, where feasible, attempted). For governed enterprise
   sources (STID, TR2000, tagreader, Seeq, Rigga, Maintenance, PEPR), prefer the
   corresponding coordinator agent so authentication and read-only governance
   are handled correctly.
4. **Repo memory scan.** List `/memories/repo/*.md` via the `memory` tool.
   Read any whose filename contains a keyword from the task title — this
   surfaces prior solved tasks and known gotchas before you reinvent them.
5. **Capability assessment + agent/workflow and code discovery.** For
  Standard/Comprehensive tasks, invoke `@capability-scout` and write the result
  to `step1_scope_and_research/capability_assessment.md`. As part of this step
  you MUST run BOTH discovery tools and inspect the actual NeqSim implementation
  before selecting a method. Never rely only on the static routing table,
  capability-map prose, or mirrored task sources:

   ```bash
  <python-executable> devtools/skill_search.py "<task title>" --top 5
  <python-executable> devtools/agent_search.py "<task title>" --top 8 \
       --json --out step1_scope_and_research/agent_plan.json
   ```

     Then search `CHANGELOG_AGENT_NOTES.md`, `src/main/java/neqsim/`, neighboring
     JUnit tests, and the locally resolved NeqSim dependency/JAR for the required
     equipment, thermodynamics, standards, safety, mechanical-design, and utility
     functionality. Verify constructors, method signatures, units, limitations,
     and existing tests from source before writing analysis code. When local
     source may be stale, also check current upstream `equinor/neqsim`; do not
     classify a capability as missing from a skill description or mirrored tree
     alone.

   Then, in `capability_assessment.md`:
   - fill **§4 Skills to Load** from `skill_search.py`,
   - fill **§4b Agents to Delegate To** from `agent_search.py` (agent, repo, the
     skills it loads, and why it was picked),
   - fill **§4c Workflow Plan** — choose single-agent, a `router.agent.md`
     composition pattern, or a declarative workflow (MCP `composeWorkflow` /
     `composeMultiServerWorkflow`, or an `engineering-harness` study) when the
     task spans ≥3 disciplines. Prefer delegating to a specialist agent over
     re-loading its skills manually, so its governance and internal workflow are
     reused (this is how "all functionality gets utilized").
   - add a **NeqSim Code Functionality Reviewed** table containing each required
     capability, exact class and method signatures, source/test/JAR evidence,
     availability (`Available`/`Partial`/`Missing`), units/constraints, and how
     the task will use it.

   Persist the plan so it survives context loss and feeds the report:
   - keep `step1_scope_and_research/agent_plan.json` (raw ranking, audit trail),
   - checkpoint it via `progress.store_context("agent_workflow_plan", {...})`,
   - add an `agent_workflow_plan` object to `results.json` (see schema) with an
     `invocation` (`subagent` | `pattern` + `reason` | `skill-only`) per agent,
     and mention the agents/workflow used in the `approach` / `method_summary`
     text so the generated report documents *how* the task was solved. Then
     actually invoke the lead agent for the task family (§5 table) — a plan
     that lists agents as "(pattern)" without a reason is a finding, not a plan.

   For Quick tasks, write a short manual capability + agent note in `notes.md`
   unless a capability gap is suspected.
6. **Literature scout** (Standard/Comprehensive only). Invoke
   `@literature-scout` to populate `step1_scope_and_research/references/`
   and the `## Literature & Reference Documents` section of `notes.md`.

### Autonomous investigation (when the symptom / cause is NOT given)

For root-cause, deviation, under-performance, trip, or "why is this happening?"
tasks where the user has **not** told you what to look for, do not ask them.
Run the investigation loop from `neqsim-autonomous-investigation` BEFORE fixing a
scope, and use **all** available data and tools, not just the one tag/unit named:

1. **Gather all data** — pull the full historian tag map (`@plant-data` /
   `neqsim-plant-data` / `@seeq.connect`), plus alarms/events, maintenance
   history, and STID design limits when available. Save snapshots to the task
   folder.
2. **Observe** — hand the whole tag map (no symptom) to
   `RootCauseAnalyzer.analyzeAutonomous(tagToEquipment)` (or MCP
   `runRootCauseAnalysis` with `symptom` omitted / `"AUTO"`). It auto-detects
   abnormal tags (`AnomalyScanner`), discovers lead-lag relationships
   (`RelationshipGraph`), and classifies them against the flowsheet topology
   (`CausalTopologyModel`).
3. **Hypothesize / test / discriminate** — form ≥3 competing hypotheses
   (including "data/instrument artifact"), verify with the NeqSim simulation, and
   report the **discovered relationships and the discriminating test**, not just a
   single conclusion. Treat any supplied classification as a hint to challenge.

For operational plant tasks involving P&ID symbols, valve actions, live plant
data, active train state, isolation, evacuation, or dynamic response, load
`neqsim-pid-process-operations` together with `neqsim-technical-document-reading`,
`neqsim-process-extraction`, `neqsim-plant-data`, `neqsim-controllability-operability`,
and `neqsim-dynamic-simulation`. Keep public outputs plant-agnostic; use private
prompt files or private skills for site-specific document sources, historian
source names, tag maps, operator procedures, and company requirements.
Use `neqsim.process.operations` for Java deliverables and MCP `runOperationalStudy`
for tool-based tag-map validation, field-data application, valve scenarios, and
controller-response metrics.
For fast liquid-hammer cases, route the extracted STID geometry, tagreader event
window, and valve closure schedule through `neqsim-water-hammer` and MCP
`runWaterHammer` before deciding whether a detailed surge study is required.

---

## 1.5 ── CONTEXT WINDOW RESILIENCE (checkpoint & resume)

Long-running tasks (Standard and Comprehensive) routinely exhaust the context
window. When this happens, the agent starts a new conversation with no memory
of previous work. The **progress checkpoint** system solves this.

### How it works

A `progress.json` file in the task folder records every completed milestone,
key decisions, derived context, and the next action. The file is updated after
each significant step. When a fresh agent picks up the task, it reads
`progress.json` first and knows exactly where to resume.

### MANDATORY: Checkpoint after every milestone

After completing each numbered step in the workflow below, write a checkpoint:

```python
import sys; sys.path.insert(0, "devtools")
from neqsim_runner.progress import TaskProgress

progress = TaskProgress("task_solve/YYYY-MM-DD_task_slug")

# After Phase 0 (classification)
progress.complete_milestone("phase0_classified",
    summary="Type B (Process), Standard scale. 3-stage compression, SRK EOS.",
    decisions={"type": "B", "scale": "Standard", "eos": "SRK",
               "task_title": "3-stage compression from 5 to 150 bara"})
progress.set_next_action("Write task_spec.md with standards and acceptance criteria")

# After Step 1 (research)
progress.complete_milestone("step1_research_done",
    summary="Research complete. Using API 617 for compressor design, "
            "NORSOK P-001 for process. Feed: rich gas, 85% methane.",
    outputs=["step1_scope_and_research/task_spec.md",
             "step1_scope_and_research/notes.md"],
    decisions={"standards": ["API 617", "NORSOK P-001"],
               "feed_composition": {"methane": 0.85, "ethane": 0.07,
                                    "propane": 0.05, "nC4": 0.03}})
progress.set_next_action("Create main notebook: 01_compression_analysis.ipynb")

# Store expensive-to-derive context
progress.store_context("api_methods", {
    "compressor_class": "neqsim.process.equipment.compressor.Compressor",
    "power_method": "getPower('kW')",
    "polytropicEff_method": "getPolytropicEfficiency()",
})
```

### MANDATORY: Check for resume on every session start

When the user asks to resume a task, check that task's `progress.json` before
doing any new work. If it exists, you are **resuming** — do NOT repeat
completed steps:

```python
import sys, os; sys.path.insert(0, "devtools")
from neqsim_runner.progress import TaskProgress

# Find the most recent task folder
import glob
tasks = sorted(glob.glob("task_solve/20*"))
if tasks:
    progress = TaskProgress(tasks[-1])
    if progress.is_resuming():
        print(progress.resume_summary())
        # READ THIS OUTPUT. It tells you:
        # - What has been done
        # - What decisions were made
        # - What to do next
        # DO NOT REDO completed milestones.
```

### What to store in checkpoints

| Milestone | What to save in `decisions` | What to save in `context` |
|-----------|---------------------------|--------------------------|
| phase0_classified | type, scale, eos, task_title | — |
| step1_spec_written | standards, acceptance_criteria | — |
| step1_research_done | feed_composition, operating_envelope | api_methods, neqsim_classes_used |
| step2_notebook_created | notebook_path, simulation_approach | cell_structure, import_patterns |
| step2_notebook_executed | key_results (T, P, power, etc.) | job_ids, output_paths |
| step2_validation_done | validation_method, max_deviation | benchmark_data_source |
| step2_results_saved | results_json_path | figure_list, table_data |
| step3_report_generated | report_paths | manual_sections_content |

### Resume rules

1. **Read progress.json FIRST for resume requests.** Before searching files or planning work.
2. **Trust completed milestones.** Don't re-validate or re-run them unless outputs are missing.
3. **Re-read decisions.** These were derived with full context — use them, don't re-derive.
4. **Check context store.** If API method names or class paths were saved, use those directly.
5. **Check for runner jobs.** If job_ids exist, check their status via the AgentBridge.
6. **Resume from next_action.** This is the exact instruction the previous agent left for you.
7. **If outputs are missing** despite milestone being marked done, re-do that milestone.

### Break large tasks into sub-conversations

For Comprehensive tasks (multi-notebook, multi-day), proactively break the work
into conversation-sized chunks. After Phase 0 + Step 1, checkpoint and tell the
user: "Step 1 is complete. Please start a new conversation and say
`@solve-task resume task_solve/YYYY-MM-DD_slug` to continue with Step 2."

### MANDATORY: Read `study_config.yaml` before planning notebooks

Every new task folder contains `study_config.yaml`. It is the explicit input
contract for task inputs, document sources, task depth, notebook plan, report
detail, and quality gates.

After creating the task folder and before writing `task_spec.md` or creating
notebooks:

1. Read `task_solve/YYYY-MM-DD_slug/study_config.yaml`.
2. Apply the intake gate before continuing:
   - If `intake.pause_after_folder_creation` is `always`, pause and ask the
     user to add or confirm missing task inputs before Step 1 work.
   - If it is `auto`, pause for Standard/Comprehensive tasks when method-critical
     values, required documents, or a fully authored config are missing.
   - If it is `never`, continue with explicit assumptions unless a missing input
     would make the calculation method invalid.
   - When pausing, tell the user the task folder path, the `study_config.yaml`
     path, and the `step1_scope_and_research/references/` drop folder. Explicitly
     say that document input is possible, including PDFs, Word files, Excel
     stream tables, P&IDs, vendor data sheets, standards, and lab reports. Do
     not create notebooks until the user confirms to continue or the required
     files are present.
3. If `study.scale`, `report.depth`, `notebooks.plan`, `inputs.documents`, or
   `quality_gates` are set to anything other than `auto`, treat those values as
   higher priority than scale inferred from the prompt.
4. If `inputs.documents_required` is true or `inputs.documents` lists source
  files, verify the files are under `step1_scope_and_research/references/`,
  classify them, extract relevant engineering data, normalize units/component
  names, validate the values, and record the extraction in Step 1 notes or
  structured JSON before building notebooks.
5. For Comprehensive / Development tasks, do not invent a notebook plan until
  `notebooks.plan` has been read. Create or execute the configured notebooks in
  order, and checkpoint after each notebook.
6. If a required configured notebook, report section, benchmark, uncertainty
  analysis, risk register, figure discussion, or consistency check cannot be
  produced, record the reason in `progress.json`, `results.json` limitations,
  and the final report.
7. Before Step 3, run `<python-executable> step3_report/generate_report.py`; the report
  generator reads `study_config.yaml` and warns about missing configured
  deliverables. Fix warnings marked as required before finalizing unless the
  user explicitly accepts the limitation.

---

## 2 ── WORKFLOW (follow this exactly)

### Phase 0: Setup — Create, Classify, and Scale

1. **Create or identify the task folder first.**

   - For a new task, the mandatory first action above has already created the
     folder using `neqsim new-task ... --prompt ...`. If not, create it now.
   - For a resume request, use the existing folder named by the user or the
     latest task folder confirmed by `progress.json`.
   - Read `README.md`, `user_input.md`, and `study_config.yaml` before writing
     Step 1 content.

2. **Confirm the task type** into one of these categories:
   - **A** — Property (density, viscosity, JT coefficient, phase envelope, etc.)
   - **B** — Process (separation, compression, dehydration, distillation, etc.)
   - **C** — PVT (CME, CVD, swelling test, saturation pressure, etc.)
   - **D** — Standards (ISO 6976, AGA, hydrocarbon dew point, etc.)
   - **E** — Feature (add new NeqSim method/equipment/model)
   - **F** — Design (wall thickness, mechanical sizing, PSV, etc.)
   - **G** — Workflow (field development, design basis, technology screening — multi-discipline)

3. **Determine the task scale** — this controls how deep you go:

| Scale | AACE Class | FEL | Indicators | Task Spec | Notebooks | Report |
|-------|-----------|-----|-----------|-----------|-----------|--------|
| **Quick** | 5 | — | Simple question, single property, one condition | Minimal (just method + acceptance) | 0-1 notebook or runner script | Brief summary only |
| **Standard** | 3–4 | FEL-1/2 | Process simulation, PVT study, single-discipline design | Full task_spec.md | 1 complete notebook | Word + HTML |
| **Comprehensive** | 1–2 | FEL-2/3 | Multiple standards cited, multi-discipline, "Class A/B study", "design basis", field development | Detailed task_spec with all sections, many standards | Multiple numbered notebooks per discipline | Full Word + HTML with navigation |

   **Scale auto-detection rules:**
   - User mentions specific standards (NORSOK, DNV, ISO) → at least Standard
   - User asks for multiple deliverables → at least Standard
   - User says "field development", "design basis", "concept selection", "Class A/B" → Comprehensive
   - User asks a single question with no standards → Quick
   - When in doubt, ask the user: "This looks like a [scale] task — should I go deeper or keep it light?"

  **Follow-up questions (ask only when method-critical data is missing):**

    Ask these scoping questions only when missing inputs would materially change
    the calculation method, acceptance criteria, or decision recommendation.
    Otherwise proceed with explicit assumptions and continue without blocking.

   1. **Fluid / resource**: What is the reservoir fluid composition? If unavailable,
      what type (lean gas, rich gas, oil, condensate)? What is the estimated
      resource volume (GIP/STOIIP) and its uncertainty range?
   2. **Operating envelope**: What are the design pressure, temperature, and flow
      rate ranges? Any constraints (backpressure limit, arrival temperature)?
   3. **Standards & jurisdiction**: Which design codes apply (NORSOK, DNV, API,
      ASME)? Which fiscal/tax regime (Norwegian NCS, UK, generic)?
   4. **Economics**: What gas/oil price range and currency? What discount rate?
      Are cost estimates needed (CAPEX breakdown, OPEX)? Is a formal Equinor STEA
      evaluation required (tax, uplift, owner shares, approved price deck)? If yes and
      the enterprise plugin is installed, delegate the formal step to
      `enterprise-stea-automation-agent` (it can build and run a local STEA project in
      the desktop client), keep the NeqSim result as the labelled screening case and
      record `economics_engine` in `notes.md`; otherwise use NeqSim economics only.
   5. **Uncertainty scope**: Which parameters are most uncertain? Should Monte
      Carlo use full NeqSim process simulations (slower, more accurate) or
      simplified correlations (faster)?
   6. **Deliverables**: What output format — quick answer, notebook only, or full
      Word + HTML report? Are benchmarks against published data required?
   7. **Risk categories**: Which risk categories matter most (market, technical,
      HSE, regulatory, schedule)?

   For Quick-scale tasks, skip questions and proceed directly.

4. **If the folder still does not exist, create it now — non-negotiable:**

    ```
    Run in terminal: neqsim new-task "TASK TITLE" --type X --author "Agent" --prompt "<verbatim user request>"
    ```

    For long requests, save the prompt to a file and use `--prompt-file`.

    Use explicit depth inputs when the user requests a deep study, for example:

    ```
    neqsim new-task "TASK TITLE" --type G --author "Agent" --prompt "<verbatim user request>" --scale comprehensive --report-depth detailed --notebooks 5 --intake-pause always
    ```

    Or pass a fully authored configuration:

    ```
    neqsim new-task "TASK TITLE" --type G --author "Agent" --prompt "<verbatim user request>" --config-file path/to/study_config.yaml
    ```
   This creates `task_solve/YYYY-MM-DD_task_slug/` with all subfolders.
   **ALL subsequent files MUST go inside this folder. Do NOT proceed without it.**
   Read the generated README and verify `user_input.md` captured the prompt
   before continuing.

5. **Run the intake gate before Step 1 work:**
   - Read `study_config.yaml`.
   - Tell the user the task folder exists.
   - Ask for missing method-critical values or invite them to add documents to
     `step1_scope_and_research/references/` and edit `study_config.yaml`.
   - Explicitly say that document input is possible for the task.
   - Continue only after confirmation when `--intake-pause always` was used or
     required inputs are missing.

6. **Run the post-folder preflight** described in Section 1, then checkpoint.

   **CHECKPOINT (Phase 0):** After creating the task folder and classifying:
   ```python
   import sys; sys.path.insert(0, "devtools")
   from neqsim_runner.progress import TaskProgress
   progress = TaskProgress("task_solve/YYYY-MM-DD_task_slug")
   progress.complete_milestone("phase0_classified",
       summary="[1 sentence: type, scale, method]",
       decisions={"type": "X", "scale": "Standard", "eos": "SRK",
                  "task_title": "..."})
   progress.set_next_action("Write task_spec.md")
   ```

### Phase 1: Scope & Research (Step 1)

5. **Fill in the task specification** (`step1_scope_and_research/task_spec.md`).
   Adapt depth to the task scale:

   **Quick scale:** Fill only the essential fields — method/EOS, one-line acceptance
   criterion, and the specific condition to calculate. Leave other sections empty.

   **Standard scale:** Fill all sections — standards, methods, deliverables,
   acceptance criteria, operating envelope, input data.

   **Comprehensive scale:** Fill every section in detail. List ALL applicable
   standards with specific clause numbers. Define a complete work breakdown of
   deliverables. Set quantitative acceptance criteria for every output. Define
   the full operating envelope with min/design/max values.

   The task spec sections:

   **Design Basis Header** (Design/Development mode — per NORSOK P-001 practice):
   - **Document ID**: Auto-generated from task folder name
   - **Revision**: Rev 0 (initial), increment on significant parameter changes
   - **Status**: Draft → Issued for Review → Approved
   - **Design life**: e.g., 25 years (or N/A for property lookups)
   - **Design code**: Primary governing standard (e.g., ASME VIII Div.1, DNV-ST-F101)
   - **Design conditions**: Summary table of design P, T, flow rate with units

   **Core sections (all modes):**
   - **Applicable standards** (MANDATORY — see below): Which codes, standards, and
     company TRs govern this task (NORSOK, ISO, DNV, API, ASME, company TR documents).
     Load the `neqsim-standards-lookup` skill for equipment-to-standards mapping.
   - **Calculation methods/models**: Which EOS, correlations, pipe flow models to use
   - **Required deliverables**: What the final output must include
   - **Acceptance criteria**: Mass balance tolerance, design factors, safety margins
   - **Operating envelope**: Range of conditions to cover (P, T, flow, composition)
   - **Input data**: Reference fluid compositions, operating conditions, equipment data

   **Standards identification (MANDATORY — proportional to scale):**

   | Scale | Standards Requirement |
   |-------|---------------------|
   | Quick | 1-line note: "Per [STANDARD]" or "N/A — property lookup" |
   | Standard | Table listing each applicable standard with scope |
   | Comprehensive | Full table with clause numbers, design values, limits, compliance evidence |

   Use the equipment-to-standards mapping from `neqsim-standards-lookup` skill to
   automatically identify standards based on the equipment types in the simulation.
   Query `designdata/standards/standards_index.csv` for the mapping.

   **Scope limitations** (Design/Development mode):
   - **In scope**: What this analysis covers
   - **Out of scope**: What is explicitly excluded (e.g., "detailed fatigue analysis",
     "site-specific seismic loads", "control system design")
   - **Validity envelope**: Conditions under which results are valid (T range, P range,
     composition range, flow regime). Results outside this envelope require re-analysis.
   - **Model limitations**: Known EOS/correlation limitations at the operating conditions
     (e.g., "SRK accuracy degrades near critical point", "Beggs & Brill not validated
     above 90° inclination")

   If the user specifies standards or methods in their request (e.g., "per NORSOK P-001"),
   incorporate these directly into the task spec. If not specified, select appropriate
   standards based on the task type and engineering domain.

6. **Auto-search for similar past solutions (MANDATORY):**
   Before writing any new code, search for related prior work:
   - **Search earlier tasks in the configured task root** (not only `task_solve/`;
     the root may be elsewhere, e.g. OneDrive): run
     `neqsim tasks search <equipment fluid standard tag keywords> --exclude <this task>`
     (`--json` for scripts). Open the top hits' `results.json`, `analysis.md`,
     `WORK_RECORD.md` and `SOURCES.md`; reuse their documents, models and
     conclusions instead of re-deriving them, and list the tasks reviewed in `notes.md`.
     Also use `neqsim tasks index` output (`INDEX.md`/`tasks.json`) when present.
   - **Keyword search** `docs/development/TASK_LOG.md` for task type, equipment, fluid, standards
   - **Search** `docs/development/CODE_PATTERNS.md` for relevant patterns
   - **Search** `src/test/java/neqsim/` for existing tests covering similar equipment/fluids
   - **Search** `examples/notebooks/` for related notebooks
   - If a similar task was solved before, **start from that solution** — adapt rather than rebuild
   - Document what prior work was found (or not found) in `notes.md`

6b. **Gather background knowledge** for the task:
   - Search the NeqSim codebase for existing classes/methods relevant to the task
   - Check `CHANGELOG_AGENT_NOTES.md` for any recent API changes affecting this task
   - Use web search if available for engineering reference data
   - **Retrieve vendor documents** if the task references specific equipment tags.
     Load the `neqsim-stid-retriever` skill for document retrieval patterns:
     relevance filtering, retrieval manifests, and backend configuration.
     If a retrieval backend is configured (via gitignored `devtools/doc_retrieval_config.yaml`),
     auto-fetch performance curves, mechanical drawings, and data sheets.
     Otherwise, expect documents in `step1_scope_and_research/references/`.
     Users can always **add documents manually** to `references/` alongside
     auto-retrieved ones — both sources coexist and are tracked in the manifest.
      Ask the user for additional documents only when the task is Standard or
      Comprehensive and the missing documents would materially change the method,
      constraints, or recommendation. For Quick tasks, proceed with documented
      assumptions unless the calculation is invalid without the document.
      For trapped-liquid fire rupture studies, load `neqsim-trapped-liquid-fire-rupture`
      and retrieve the full evidence pack before calculation: P&ID/STID isolation
      boundaries, line lists, piping specs, material certificates, flange/bolt/gasket
      data, fire-zone/PFP documents, relief/thermal relief basis, and acceptance
      criteria. Missing evidence must be written to `results.json` as assumptions/gaps.
   - **Extract figures from reference PDFs** placed in `step1_scope_and_research/references/`:
     ```bash
    <python-executable> devtools/pdf_to_figures.py step1_scope_and_research/references/ --outdir figures/
     ```
     Then use `view_image` on extracted PNGs to read engineering drawings, P&IDs,
     charts, data tables, and compressor maps. This makes PDF content available
     for AI analysis (diagram digitization, data extraction, layout understanding).

   - **Structured image analysis workflow** (for vendor drawings, P&IDs, datasheets):
     When reference documents contain engineering drawings or visual data, use the
     `neqsim-technical-document-reading` skill Section 3.7 patterns:

     1. **P&IDs** → Extract equipment tags, valve tags, instrument tags, piping
        sizes/classes, line numbers, and connection topology using the
        `PID_EXTRACTION` format. This provides the flowsheet topology that
        informs the NeqSim `ProcessSystem` model.

     2. **Vendor API datasheets** (e.g., API 692 seal datasheets, API 617
        compressor datasheets) → Extract operating conditions, design data,
        performance parameters, and material specs using the
        `VENDOR_DATASHEET_EXTRACTION` format. These values become simulation
        inputs and validation targets.

     3. **Mechanical arrangement drawings** → Extract dimensions, nozzle
        schedules, standpipe geometry (lengths, bore sizes, volumes), piping
        run lengths using `MECHANICAL_ARRANGEMENT_EXTRACTION` format. Physical
        dimensions feed into volume calculations, heat transfer models, and
        residence time estimates.

     4. **Performance maps / phase envelopes** → Digitize key points (rated
        point, surge line, cricondentherm, operating envelope boundaries)
        using `PERFORMANCE_MAP_EXTRACTION` or `PHASE_ENVELOPE_EXTRACTION`
        format. These validate simulation results against vendor/design data.

     5. **Generate figure discussions** — for each image analyzed that informs
        the engineering analysis, produce a figure discussion block (observation,
        mechanism, implication, recommendation) and include it in
        `results.json["figure_discussion"]` for the report.

7. **Write comprehensive research notes** to `step1_scope_and_research/notes.md`.
   These notes must be **substantive** — not a skeleton template.
   The depth should be proportional to the task mode.

   **Screening mode:** A condensed version covering: sources consulted, key
   data / sanity-check values, NeqSim classes used, and assumptions made.

   **Design / Development mode (full sections):**
   - **Sources** (table): Every source consulted — NeqSim classes, papers, standards,
     web references, textbooks. Minimum 5 entries for Standard tasks, 10+ for Comprehensive.
   - **Literature & Reference Documents**: For each key reference, write a structured
     summary with: file location, relevance, key equations cited, key data extracted,
     limitations, and how it applies to this specific task.
   - **Background — Engineering Context**: Explain the real-world engineering problem
     in 2-3 paragraphs. Why does this matter? What goes wrong in practice? What are
     the consequences of getting it wrong? Include industry context.
   - **Background — Physical Mechanisms**: Describe the underlying physics. What
     thermodynamic, chemical, or transport phenomena are involved? Include governing
     equations with variable definitions.
   - **Key Data / Correlations**: Reference values, design rules of thumb, typical
     operating ranges. These are the "sanity check" values used during validation.
   - **Industry Experience / Case Studies**: Known field cases, operational incidents,
     lessons learned. This grounds the analysis in reality.
   - **Relevant Standards — Detailed Requirements**: For each standard in task_spec,
     extract the specific clauses, equations, tables, and design factors that apply.
     Don't just list the standard — quote the requirement.
   - **NeqSim API Coverage — Detailed Inventory**: For each capability needed, check
     if NeqSim has it. Search the Java source code. List class names, key methods,
     and any limitations found. This feeds directly into Phase 1.5.
   - **Open Questions**: Uncertainties, missing data, things to clarify with the user

### Phase 1.5: Deep Analysis & Solution Design (required for high-consequence work)

Before writing simulation code for design, workflow, safety-critical, or
high-value economics tasks, produce a **thorough engineering analysis document**
that gives deep insight and a clear solution path. For smaller tasks, use a
condensed analysis section in notes and proceed.

7b. **Write a detailed problem analysis** to `step1_scope_and_research/analysis.md`.
    Include the following sections (depth proportional to task consequence):

    #### 7b.1 — Physics & Theory Deep-Dive
    Explain the fundamental physics/engineering behind the problem at a level
    suitable for a senior engineer review:
    - **Governing equations** with derivations or references (use LaTeX notation)
    - **Physical mechanisms** — what causes the phenomenon, why it matters
    - **Thermodynamic basis** — which EOS is appropriate and why, phase behavior
    - **Transport phenomena** — heat/mass transfer, fluid mechanics if relevant
    - **Key assumptions** — what simplifications are being made and their impact
    - **Dimensional analysis** — key dimensionless groups if applicable
    - **Order-of-magnitude estimates** — quick hand calculations to set expectations
      (e.g., "JT coefficient ~0.5 K/bar → expect ~25°C drop across 50 bar valve")

    #### 7b.2 — Alternative Solution Approaches
    List at least 2-3 different ways to solve this problem, with pros/cons:

    | Approach | Description | Pros | Cons | Recommended? |
    |----------|-------------|------|------|--------------|
    | A | ... | ... | ... | ✓ / ✗ |
    | B | ... | ... | ... | ✓ / ✗ |
    | C | ... | ... | ... | ✓ / ✗ |

    Justify the chosen approach with engineering reasoning.

    #### 7b.3 — NeqSim Capability Assessment

    **Option A (recommended for Standard/Comprehensive):** Invoke the capability
    scout agent to perform a systematic assessment:
    ```
    @capability-scout [paste the task description here]
    ```
    The scout returns a structured Capability Assessment Report covering:
    - Full capability requirements matrix with NeqSim coverage status
    - NIPs for every ❌ Missing or ⚠️ Partial gap
    - Recommended skills to load
    - Recommended agent pipeline for the task
    - Implementation priority order

    **Option B (for Quick/simple tasks):** Manually assess by checking the
    `neqsim-capability-map` skill and searching the codebase:

    | Capability Needed | NeqSim Class/Method | Status | Gap Description |
    |-------------------|---------------------|--------|------------------|
    | JT flash | ThrottlingValve | ✅ Available | — |
    | S8 solid flash | TPSolidflash | ✅ Available | — |
    | Nucleation model | — | ❌ Missing | Need CNT-based nucleation rate |
    | Corrosion rate | DeWaardMilliamsCorrosion | ⚠️ Partial | Missing S8 direct corrosion path |

    **For every ❌ Missing or ⚠️ Partial gap, write a NeqSim Improvement Proposal**
    (see Section 6 below). This is how the development flywheel turns: tasks
    surface gaps → gaps become proposals → proposals become implementations.

    #### 7b.4 — Solution Architecture
    Describe the simulation/calculation architecture:
    - **Flowsheet diagram** (text-based or markdown table showing equipment order)
    - **Data flow** — what feeds into what, what outputs are needed
    - **Iteration strategy** — recycles, adjusters, convergence approach
    - **Parametric studies** — what sensitivity sweeps to run and why
    - **Expected results** — what ranges you expect before running (from hand calcs)

    #### 7b.5 — Risk & Failure Mode Analysis
    Before building the simulation, anticipate what could go wrong:
    - **Numerical risks** — convergence failure, phase identification issues
    - **Physical risks** — conditions outside EOS validity, near-critical behavior
    - **Data risks** — missing BIPs, uncertain component properties
    - **Mitigation** — fallback approaches for each risk

    #### 7b.6 — Engineering Insight Questions
    List 5-10 engineering questions the analysis should answer. These go beyond
    "what is the answer" to "what does it mean and what should we do":
    - Example: "At what H2S level does sulfur deposition become operationally significant?"
    - Example: "Is pre-heating more cost-effective than chemical inhibition?"
    - Example: "How sensitive is the NPV to gas price vs. CAPEX uncertainty?"
    These questions drive the analysis and ensure the report provides actionable insight.

**CHECKPOINT (Phase 1 complete):** This is a natural break point. Checkpoint
before the context-heavy notebook creation and execution:
```python
progress.complete_milestone("step1_research_done",
    summary="Research complete. [key method, standards, feed comp]",
    outputs=["step1_scope_and_research/task_spec.md",
             "step1_scope_and_research/notes.md",
             "step1_scope_and_research/analysis.md"],
    decisions={"standards": [...], "feed_composition": {...},
               "simulation_approach": "...", "acceptance_criteria": {...}})
progress.store_context("neqsim_classes", {
    "main_class": "full.java.ClassName",
    "key_methods": ["method1(args)", "method2(args)"],
})
progress.set_next_action("Create analysis artifact: 01_XXXX.ipynb or run_XXXX.py with [approach]")
```
   For Comprehensive tasks, consider telling the user: "Step 1 is complete.
   Start a new conversation with `@solve-task resume task_solve/YYYY-MM-DD_slug`."

### Phase 2: Analysis & Evaluation (Step 2)

8. **Determine the right approach** (refined from Phase 1.5):
- Use the solution architecture from the analysis document
- Implement the recommended approach from the alternatives assessment
- Address each engineering insight question in the executable analysis artifact
- For every NeqSim gap: implement the proposed improvement or use a workaround
- Choose reasonable engineering defaults for missing input data (document assumptions)
- **Check for data gaps** — if analysis requires documents not yet retrieved
     (e.g., mechanical drawings, instrument datasheets, P&IDs, parallel train data):
     1. Log the gap in the notebook with what's missing and why
     2. If a retrieval backend is configured, auto-fetch the specific doc types needed
     3. If not, ask the user to drop the file in `references/` or provide the values
     4. Update the retrieval manifest with `iterative_retrievals` entries
     5. Re-extract PNGs for any new PDFs and continue analysis
     See `neqsim-stid-retriever` skill § "Iterative Retrieval During Analysis"

9. **Create the executable analysis artifact** in `step2_analysis/`:
   - For Quick tasks, a short runner script is acceptable when it gives a clearer,
     faster answer than a notebook. The script must use `neqsim_dev_setup.py`,
     write or merge `results.json`, and be executed by `neqsim_runner` or a
     direct verified command.
   - For Standard and Comprehensive tasks, create notebooks with VS Code notebook
     tools, `nbformat`, or valid `.ipynb`
     JSON. Raw JSON notebooks must be nbformat v4, keep cells in the top-level
     `cells` array, and include `metadata.language` for every cell. When editing
     existing notebooks, preserve existing `metadata.id` values.
   - Use the devtools setup pattern from `neqsim-notebook-patterns`: import
     `neqsim_dev_setup`, call `neqsim_init(project_root=PROJECT_ROOT, ...)`,
     then use classes through `ns.*` or `ns.JClass(...)`
   - Do not use `from neqsim import jneqsim` in task notebooks or runner jobs;
     that can use the installed Python package instead of workspace Java classes
   - The first setup cell must set `NEQSIM_MODE = "devtools"` and fail if the
     project root cannot be found
   - Follow the notebook structure from the `@solve-process` agent when creating
     notebooks.
   - Include clear markdown cells explaining each step in notebooks; for runner
     scripts, include concise printed output and comments only where they clarify
     non-obvious engineering logic.
   - Avoid interactive prompts, hidden kernel state, and shell-specific commands;
     every code cell must run from a fresh kernel in order
   - Load existing task-level `results.json` before adding artifact-specific
     results so multi-artifact runner merge preserves prior outputs
   - **Results & Figures (proportional requirement):**
     - Quick: at least one clear results table and at least one informative figure when visualization adds value
     - Standard/Comprehensive: detailed results tables and typically 2-3+ informative figures
     - Development/design deliverables should include enough figures to support recommendations
     - A **results section** that extracts key numerical outputs into
       a formatted table (pandas DataFrame or formatted print) with units
     - Typically **2-3+ matplotlib figures** for Standard/Comprehensive tasks showing the most important relationships
       (e.g., production profile vs time, pressure vs distance, temperature vs stage,
       cost breakdown bar chart, sensitivity tornado chart)
     - All figures saved to `figures/` as PNG with descriptive filenames
     - Figure captions added to `results.json` under `figure_captions`
     - A **summary comparison table** when comparing cases or validating against
       reference data
   - **Figure Discussion Cells** — add discussion cells for all decision-critical
     figures (and for all major figures in Design/Development mode). This is the
     critical link between calculations and conclusions. Each discussion cell should
     follow this pattern:

     ```markdown
     ### Discussion: [Figure Title]

     **Observation:** [What does the figure show? State the key finding with numbers.]

     **Physical Mechanism:** [Why does this happen? Explain the underlying physics,
     chemistry, or engineering reason.]

     **Engineering Implication:** [What does this mean for the design or operation?
     Compare against design limits, typical values, or industry experience.]

     **Recommendation:** [What action should be taken based on this result?
     Be specific: material selection, operating limits, equipment sizing, etc.]

     > *Links to: [reference specific key_results entries], answers insight question Q[N]*
     ```

     **Example figure discussion cell:**
     ```markdown
     ### Discussion: Temperature Profile Along Pipeline

     **Observation:** The gas temperature drops from 45°C at the inlet to -12°C at
     the outlet (Figure 2). The temperature crosses the sulfur deposition onset
     temperature (0°C) at approximately 12 km from the inlet.

     **Physical Mechanism:** The temperature drop is driven by Joule-Thomson cooling
     across the letdown valve (ΔT = -35°C for this gas composition at 120→45 bara)
     combined with heat loss to the 4°C seabed. The JT coefficient of 0.45°C/bar
     is typical for lean gas with 85% methane.

     **Engineering Implication:** Solid S₈ will precipitate in the pipeline between
     12 km and the outlet. The deposition rate peaks at approximately 25 km where
     the gas reaches maximum supersaturation. This represents a flow assurance risk
     requiring mitigation.

     **Recommendation:** Install direct electrical heating (DEH) between 10-30 km
     to maintain gas temperature above 5°C (with 5°C safety margin above deposition
     onset). Alternatively, pre-heat gas to minimum 60°C upstream of the valve to
     keep the entire pipeline above 0°C.

     > *Links to: outlet_temperature_C = -12°C, sulfur_deposition_onset_C = 0°C.
     > Answers insight question Q3: "At what distance does deposition begin?"*
     ```

   - **Traceability Chain** (Design/Development mode, recommended for all):
     1. **Calculation** → produces numerical results
     2. **Figure** → visualizes the results
     3. **Discussion cell** → interprets the figure (observation, mechanism, implication)
     4. **Recommendation** → specific action based on the discussion
     5. **results.json** → captures the chain in `figure_discussion` entries

     For Design/Development deliverables, every conclusion should trace back to
     specific figures and discussion cells. For Screening tasks, a brief
     interpretation paragraph after key figures is sufficient.

   - For **Type G (Workflow)** tasks: create multiple notebooks, numbered sequentially
     (e.g., `01_reservoir_fluid.ipynb`, `02_pipeline_sizing.ipynb`, etc.)

10. **Execute notebooks and runner scripts with supervised runner by default.** Fix errors immediately.

10a. **Notebook execution method — default rule (MANDATORY):**

    The default execution engine for task notebooks and scripts is `neqsim_runner`, as
    configured by `notebooks.execution_engine: neqsim_runner` in
    `study_config.yaml`. This runs notebooks in isolated subprocesses with
    their own JVMs, retry handling, persisted job state, and no manual kernel
    restart loop.

    **Use `neqsim_runner` (headless/supervised) unless `study_config.yaml`
    explicitly sets `notebooks.execution_engine: interactive`.** This is
    mandatory when ANY of these are true:
    - Standard or Comprehensive scale
    - More than one notebook
    - Parametric sweep or Monte Carlo
    - Any notebook expected to run > 5 minutes
    - Benchmark validation, uncertainty, or risk notebooks are required
    - Prior JVM crash, kernel death, hanging cell, or `RuntimeError: JVM cannot be restarted`

    **Use `run_notebook_cell` (interactive) only for quick debugging** when ALL
    of these are true:
    - `study_config.yaml` sets `notebooks.execution_engine: interactive`, or the
      user explicitly asks for interactive notebook debugging
    - Quick or Screening scale
    - Single notebook, no sweep, no Monte Carlo
    - Expected runtime < 5 minutes
    - No prior JVM/kernel crash or hanging cell in this session

    **Escalation rule:** If interactive execution hits a JVM crash, kernel death,
    hanging cell, or `RuntimeError: JVM cannot be restarted`, immediately switch
    to `neqsim_runner` for all remaining notebooks. Do not keep restarting the
    VS Code kernel and retrying interactively.

    **Runner usage:**

    ```python
    # In a standalone script or notebook orchestration cell:
    import sys; sys.path.insert(0, str(TASK_DIR.parent.parent / "devtools"))
    from neqsim_runner.agent_bridge import AgentBridge

    bridge = AgentBridge(task_dir=str(TASK_DIR))
    planned_notebooks = [
        "step2_analysis/01_analysis.ipynb",
        "step2_analysis/02_benchmark_validation.ipynb",
    ]

    # Default mode="execute" produces an executed .ipynb with all cell outputs.
    # Each run happens in an isolated subprocess with its own JVM.
    job_ids = [
        bridge.submit_notebook(notebook_path, mode="execute",
                               max_retries=3, timeout_seconds=3600)
        for notebook_path in planned_notebooks
    ]

    # Run all jobs (supervisor handles retry/recovery automatically).
    # Keep max_parallel=1 unless the task owner explicitly accepts parallel JVM load.
    bridge.run_all(max_parallel=1)

    summary = bridge.summary()
    print(summary)
    if summary["failed"] or summary["pending"]:
        raise RuntimeError("NeqSim Runner jobs did not all complete successfully")

    # Merge multi-notebook outputs instead of overwriting earlier results.
    bridge.merge_results_to_task(job_ids)

    # Get the executed notebook (only for mode="execute")
    executed_nb = bridge.get_executed_notebook(job_ids[0])
    ```

    For script-only workloads, use `bridge.submit_script()` or
    `bridge.submit_parametric_sweep()` instead of `submit_notebook()`. For
    lighter notebook jobs that do not need executed `.ipynb` outputs, set
    `mode="script"`, but keep the same success check and merge step.

    **When to use the runner vs interactive notebook:**

    | Signal | → Runner | → Interactive |
    |--------|----------|---------------|
    | Task scale | Standard / Comprehensive | Quick / Screening |
    | Notebooks in task | > 1 | 1 |
    | Monte Carlo iterations | N > 50 | N ≤ 50 or none |
    | Parametric sweep cases | > 3 | ≤ 3 or none |
    | Expected wall time | > 5 min | < 5 min |
    | Previous JVM crash this session | Always switch | N/A |
    | Need interactive debugging | No | Yes |
    | Need executed .ipynb with outputs | Yes (mode="execute") | Yes |

    The runner writes outputs to `task_dir/runner_output/` and job stat

[…] pełny plik w paczce .zip

Wersje

W bazie nie ma innych skilli o nazwie neqsim-task-workflow.

Migawka bazy z 28.10.2026 · wersja paczki 0dd1dfdefffc (skrót SHA-256 całej paczki)

Zgłoś problem z tym skillem: szkodliwa treść, błędny opis albo prośba autora o usunięcie.

Podobne skille

  • 93neqsim-setup
    Konfiguruje i sprawdza środowisko NeqSim: katalog zadań, szablon raportu Word oraz działanie Javy i serwera MCP.
  • 95neqsim-notebook-patterns
    Pokazuje wzorce notebooków Jupyter z NeqSim: konfigurację środowiska, strukturę, wizualizację i schemat wyników.

Uwagi i zgłoszenia

Wiadomość trafi do Bartosza Sokolińskiego. Adres e-mail jest potrzebny tylko do odpowiedzi. Szczegóły w polityce prywatności.