Imports:
  - Types:
      - WorkflowDocument
      - WorkflowStage
      - WorkflowExtendStage
      - WorkflowMemory
      - WorkflowReflect
      - WorkflowAssistant
      - WorkflowDelegation
      - WorkflowRepeat
      - WorkflowGates
      - WorkflowGateStep
    Usages:
      - parse-workflow
      - memory
      - assistants
      - gates
    From: goga/pipeline/workflow

Usages:
  convention: .goga/usages/conventions.md
  beautiful_yaml: .goga/usages/cooks/beautiful_yaml.md
  afm: .goga/usages/cooks/afm.md

Annotations: |
  The `convention` practice is used for:
  - Working with the codebase
  - Organizing the REPL development cycle
  - Debugging and testing
  - Organizing the test infrastructure
  - Understanding the general principles and rules of development and testing in the project

  This cell is a pure transformer: it reads a pipeline-file written in goga
  DSL (phases-list or stages-map) and writes an equivalent afm flow-file
  (flat YAML with top-level prompt, root_dir, name, description, repeat,
  memory, collaboration, team, and a stages list). It performs
  no I/O beyond the two paths it receives and the optional workflow-file
  instruction source, performs no network or subprocess calls, and performs
  no environment-variable reads — the caller supplies the root_dir value
  explicitly.

  The parsing half honors YAML links: a pipeline-file parses as one stream
  whose anchor registry survives the "---" document boundary (anchors
  declared in the header or in hidden body keys resolve in the body), and
  hidden declaration keys — top-level body keys starting with "." — are
  dropped before stage assembly.

  The cell consumes `WorkflowDocument` (the optional workflow argument of
  `compile_flow`) and `WorkflowStage` (the value type of the workflow stages
  map, referenced in the workflow reconstruction algorithm). The import is
  one-directional —
  this cell consumes the declarative workflow instructions; the workflow cell
  never imports from this cell. The cell does NOT call parse_workflow itself
  — the consumer (the run_pipeline routine in goga/pipeline) parses the
  workflow-file and passes the resulting `WorkflowDocument` to
  `compile_flow` via its optional workflow parameter. When workflow is None,
  no workflow is applied and the output carries no top-level prompt and no
  per-stage overrides.

  Use `beautiful_yaml` for the YAML serialization parameters applied by
  `serialize_flow`; a custom yaml.SafeDumper subclass extends these
  defaults to enforce the canonical key order, the flow-style for agents,
  the block-style for skills and depends_on, and the block-literal style for
  the top-level prompt.

  Use `convention` for code style, dataclass usage, and test layout.

  The input pipeline-file is segmented by a literal three-dash line: the
  segment before is the header (name, description, optional roles), the
  segment after is the body (either a YAML list for phases or a YAML dict
  for stages). The output flow-file is NOT segmented — it is a single flat
  YAML document with optional prompt, name, description, repeat, memory,
  collaboration, team, and stages.

  `BodyFormat` detection is structural: a list body yields PHASES
  (auto-generates depends_on by position), a dict body yields STAGES (passes
  depends_on through as-is, then rewrites after workflow loop-expansion when
  a workflow is applied). Any other body shape is a structural error.

  Stage-body field translation: the afm interactive field is authored as the
  communication key in a stage body (pipeline-file stage AND embedded
  extend-stage) and translated to the output interactive key in its canonical
  position; an authoring interactive key is a structural error "interactive key
  is forbidden in stage body; use communication". Equally, the afm auto_run key
  is authored as the trigger key in a stage body and translated to the output
  auto_run key (trigger: manual ⇒ auto_run: false; trigger: on_success or
  absent ⇒ no auto_run key) — the authoring trigger key is consumed by the
  translation and never leaks into the output as an unknown key. The output
  canonical key order
  keeps interactive (afm contract stable). All other step content fields
  (command, prompt, description, agents, skills, and any extra fields) are passed
  through verbatim — no validation of their contents, no schema enforcement.
  References in depends_on (dangling ids, cycles, duplicates) are afm's
  responsibility, not this cell's.

  Canonical `FlowStage` fields key order: interactive, auto_approve, auto_run,
  command, prompt, description, buttons, agents, supervisor, supervisor_prompt,
  skills, script_before, script, script_after, script_timeout, reflect,
  memory_use, pre_completion, assistants, verify, then alphabetically-sorted
  unknown keys.
  command is populated
  from the agent
  field of `WorkflowStage` (composed as /home/goga/bin/AGENT-as-claude.sh);
  description is populated from the prompt field of `WorkflowStage`. Both
  are independent channels — pipeline-file prompt and workflow-file prompt
  coexist as separate fields in the same stage when both are present.
  supervisor and supervisor_prompt sit between agents and skills so an
  authored supervisor block reads as a continuation of the agents block;
  they appear in their canonical slots ONLY when the source step body
  authors them.

  Default stage-field injection: the input stage-body field for the afm
  agents list is roles (an authoring agents key in a stage body is a
  structural error, raised by `compile_flow`). When a step body has no
  usable roles value (key absent, explicit null, or an empty list), the
  compiler injects
  a SINGLE default into the assembled `FlowStage` fields —
  "agents=[\"auto\"]" — EXCEPT in a body carrying script, where NO
  agents key is assembled at all (afm rejects agents combined with
  script): neither the ["auto"] default NOR a translated roles value
  reaches the output, while the roles elements are still validated.
  auto is a sentinel agent mode: goga emits the
  literal string auto verbatim and does NOT interpret it — the actual
  agent selection is performed on the afm side. supervisor and
  supervisor_prompt are not default-injected; they are valid
  authored fields that pass through to their canonical slots when the
  source step body carries them. An authored non-empty roles value (any
  list with at least one entry) always wins and disables injection
  entirely; its entries are translated to the output agents values via
  `translate_role` (known aliases mapped, all other values passed through
  verbatim).
  The injection lives in `FlowStage` assembly only — the
  `PipelineDocument` body returned to consumers is never affected (it
  stays a faithful mirror of the source pipeline-file). The injection runs
  uniformly on the non-workflow path and on the workflow path (after
  per-stage overrides and loop-expansion).

  The header segment additionally supports an optional roles block
  with three fixed string keys: planner, executor, reviewer. Each
  value is an inline prompt text that fully replaces (not merges with)
  the corresponding default prompt file during pipeline run
  materialization (the planner/executor/reviewer keys map to the
  planning/implementation/review prompt-file stems via `translate_role`).
  summary is NOT an overridable role. An agents key is rejected
  with a structural error by `parse_dsl`. Unknown keys, non-str values,
  and empty mappings are handled by `parse_dsl` per its contract; the
  roles data is carried in `PipelineHeader` (its roles field, of type
  `PipelineRoles`) and never enters the compiled afm flow-file — it is a
  goga-side artifact surfaced to the consumer via `PipelineDocument` (its
  header field) from `compile_flow` return value.

  `compile_flow` returns a tuple of `PipelineDocument` and `FlowDocument`: the
  input representation (`PipelineDocument`, aggregating header+format+body —
  the ORIGINAL parsed body, not the workflow-reconstructed body) and the
  output representation (`FlowDocument`, the afm flow-file model — including
  workflow-applied overrides, loop-expansion, rewritten depends_on, and the
  top-level prompt when a workflow supplied one). The text flow-file is
  written to flow_path as a side effect — the return value is part of the
  signature, not an additional side effect. Consumers access inline
  prompt overrides through `PipelineDocument` header, never through
  `FlowDocument`.

  Workflow application (when `compile_flow` is called with a non-None
  workflow argument): the cell reconstructs the body per the workflow
  instructions BEFORE building the `FlowDocument`. The reconstruction is:
  (1) extend-stages from the workflow's extend map embedded into the body
  and positioned via before/after — BEFORE per-stage overrides,
  loop-expansion, skip-removal, and reference rewriting, so the existing
  machinery applies to extend-stages uniformly. STAGES positions an
  extend-stage by deriving its explicit depends_on from before/after; PHASES
  positions an extend-stage by list insertion (no depends_on field on
  `PhaseStep`).
  (2) STRICT VALIDATION of workflow.extend.<name>.before/.after refs
  against the FULL name set (every step name/id present in the ORIGINAL body,
  plus every extend-stage name in workflow.extend): for each before/after ref,
  an unknown ref (naming no original step and no extend-stage) raises a
  structural error "unknown stage name in workflow.extend.<name>.before: <ref>"
  (or .after). The check runs BEFORE the (1) embed (extend names come from
  workflow.extend keys, so cross-references between extend-stages resolve
  without embedding) and BEFORE any skip removal, so a ref to a stage that
  exists in the original body — even if also marked skip: true — is NOT flagged
  (referencing a skipped stage is not a dangling ref). Existence only is
  checked — cycles, self-references, and duplicate refs remain afm's
  responsibility.
  (3) STRICT VALIDATION of workflow.stages names against the FULL name set
  (every step name/id present in the ORIGINAL body, plus every extend-stage
  name embedded at (1)): for each name in workflow.stages, an unknown name
  (absent from both the original body and the extend-stages) raises a
  structural error "unknown stage name in workflow.stages: <name>". The check
  runs on the FULL set
  BEFORE any skip removal, so a stage that exists in the original body —
  even if also marked skip: true — is NOT flagged as unknown. Extend-stage
  names are valid here (embedded before this check). Strictness over
  extend.<name>.before/.after refs is enforced separately at (2).
  (4) SKIP REMOVAL + transparent depends_on reconnection: stages whose
  workflow.stages[name].skip is True (and which exist) are removed from
  the working body. STAGES: each remaining stage's depends_on is
  transparently reconnected — a reference to a removed stage S is replaced
  with resolve(S), the transitive set of non-skipped predecessors of S
  (chains resolved; no dangling references or duplicates). PHASES: removed
  steps drop from the body list and depends_on re-derives by list position
  in step 5 (automatic collapse). skip wins over agent/prompt/loop/skills
  overrides on the same entry (removal runs before (5)). If the
  reconstructed body becomes empty (every stage skipped), raise a
  structural error "empty body".
  (5) per-stage overrides applied in-place to the body of `PhaseStep` /
  `StageStep`, matching embedded extend-stages by name. A stage
  not found here can only be an intentionally skipped one (removed at (4)),
  so the lookup is SILENT; unknown names are errors at (3). The agent
  override FALLS BACK to an extend-entry's inline agent, and a skills merge
  is applied. An agent instruction (stages-block or extend-entry inline)
  targeting a stage whose body authors script is a structural error
  "agent is forbidden on a script stage in workflow.<name>: <agent>" —
  the stage action is one, the agent exec target or the script, and the
  composed command must never ride the flow-file beside a script;
  (6) loop-expansion producing N copies with ids NAME-1..N and chain-style
  internal depends_on, expanding extend-stages when the effective loop for
  that name is >= 2 (stages-block loop OR the extend-entry's inline loop);
  (7) external depends_on references rewritten via the expanded_ids map,
  rewriting before/after-derived refs as well: both after and before
  → LAST expanded id — any reference to a loop-expanded chain points to its
  completion). Unknown stage names in workflow.stages and dangling refs in
  extend before/after are STRUCTURAL ERRORS (validated on the full
  original∪extend name set before skip removal). The agent instruction is composed into the
  in-container wrapper path directly — the cell does NOT call any host-side
  resolver.

  Inline extend fields and override priority: an extend-entry may carry
  inline agent/loop (extracted by parse_workflow into
  `WorkflowExtendStage`). These inline fields provide DEFAULT override
  values for the extend-stage. An explicit stages-block entry for the
  same name takes precedence PER FIELD — the effective value for a field is
  the stages-block value when that entry provides it (not None), else the
  extend-entry's inline value (when the stage originated from an
  extend-entry carrying it), else None (agent) / 1 (loop). Thus a
  stages-block agent → command composition wins over an inline agent;
  a stages-block loop wins over an inline loop. Realized by treating
  each extend-stage's inline agent/loop as a virtual stages-block
  override merged UNDER the explicit one, so passes 1 and 2 operate on the
  effective override set with no new pass.

  Skills merge: when a stages-block entry for a name carries a non-None
  skills list, the compiler merges it with the step body's existing
  skills (from the pipeline-file) — pipeline skills first, then the
  workflow skills, deduplicated by value (first occurrence keeps its
  position). An empty pipeline-skills side yields the workflow list; an
  empty workflow-skills side leaves the pipeline list unchanged; both empty
  yields no skills key. Extend-entry skills are NOT merged — they pass
  through verbatim as the new stage's skills (a new stage has no pipeline
  skills to merge with).

  approve translation: for a stage whose effective approve is one of
  "auto"/"plan"/"dialog", the compiler reads the trigger fields from that
  stage's body (pipeline-file body for an existing stage; the extend-stage body
  for an extend-stage) and applies up to two INDEPENDENT effects —
  communication: true ⇒ SUPPRESS interactive (no interactive key), and roles
  containing planner ⇒ emit auto_approve: true. Each value drives a subset of
  the two effects: "auto" drives BOTH; "plan" drives ONLY the interactive
  suppression (communication effect); "dialog" drives ONLY the auto_approve
  emission (roles effect). Each effect fires on its own trigger; baseline
  no-op when neither trigger (or neither directive subset) applies; uniform
  across every loop-expanded copy.

  Stage trigger directive: a stage body (pipeline-file stage AND embedded
  extend-stage) may carry the trigger key with the value on_success or manual;
  an absent key equals on_success. Any other value is a structural error
  "trigger must be one of: on_success, manual". An authoring auto_run key in a
  stage body is a structural error "auto_run key is forbidden in stage body;
  use trigger: manual". Translation: trigger manual assembles auto_run: false
  into the FlowStage fields in the canonical slot immediately after
  auto_approve; trigger on_success (explicit or by default) emits NO auto_run
  key — auto_run: true is never emitted. The runtime meaning of auto_run: false
  (the stage pauses until manually launched) belongs to afm — goga only
  compiles the directive.

  Workflow manual instruction: when the workflow stages block carries manual
  for a stage, the compiler applies it in the per-stage override pass: manual
  true forces the manual state over any trigger of the stage body (idempotent
  on an already-manual stage — no error); manual false cancels the RESULTING
  manual state regardless of its source (pipeline-file body or extend-stage
  body); manual false on a stage whose resulting state is not manual is a
  structural error "manual: false on non-manual stage <NAME>". skip removal
  runs before this pass — a skipped stage never reaches the manual application.
  Loop-expanded copies carry the stage's effective trigger, so every copy of a
  manual stage assembles auto_run: false.

  Workflow notes instruction: when the workflow stages block carries notes
  for a stage (a map of note name → prompt text on `WorkflowStage`), the
  compiler assembles the per-stage buttons field of the flow-file in the
  canonical slot immediately after description; the map passes through
  verbatim — keys and values unchanged. An authoring buttons key in a stage
  body (pipeline-file stage OR embedded extend-stage) is a structural error
  "buttons key is forbidden in stage body; use notes in workflow.stages" —
  buttons are authored ONLY through the workflow notes instruction (a single
  authoring source; no collisions). The instruction applies per stage name to
  embedded extend-stages as well; loop-expanded copies carry the same buttons;
  a skipped stage never reaches the application (skip removal runs first).
  Interpretation of the buttons belongs to afm — the compiler only assembles
  and serializes the field. Output-side only — `PipelineDocument` stays the
  faithful mirror of the source pipeline-file.

  Stage script directives: before_script, script, after_script are string or
  string-list stage-body directives translated to script_before, script,
  script_after (the authoring keys are consumed, not passed through). A
  payload is either a string (carried verbatim) or the script's lines — a
  non-empty list of non-empty strings joined with newlines into ONE
  multi-line string (shell-identical to authoring the same text as a block
  scalar; the output field is always a string). Any other value is a
  structural error "before_script|script|after_script must be a string or a
  non-empty list of non-empty strings in stage <name>" — the message names
  the AUTHORED key. A stage body that carries
  script together with prompt and/or skills is a structural error "script is
  mutually exclusive with prompt/skills in stage <name>"; a body carrying
  script together with a verbatim command key (not pipeline vocabulary — it
  rides the unknown-key passthrough) is a structural error "script is
  mutually exclusive with command in stage <name>" — the same exclusivity
  the per-stage override pass enforces for a workflow agent instruction on
  a script body. before_script / after_script are compatible with
  prompt / skills / script and with an agent stage's composed command (no
  error) — they are the invocation's shell bookends, not the action.

  Stage timeout directive: timeout is a string stage-body directive (pipeline-file
  stage AND embedded extend-stage) translated to script_timeout of the assembled
  `FlowStage`. A non-string value is a structural error; timeout without script in
  the same stage body is a structural error naming the stage (before_script /
  after_script do not open the directive — script_timeout scopes to the script
  action). The authoring key is consumed, never passed through; the value passes
  verbatim with no format validation (the duration grammar belongs to afm at
  runtime). The output key occupies the canonical slot immediately after
  script_after and is present only when authored. Direct authoring of
  script_timeout in a stage body is not forbidden. Loop-expanded copies inherit
  the translated value verbatim; PipelineDocument bodies stay untouched
  (output-side only).

  Workflow memory emission: when the supplied workflow carries memory
  participation, the cell assembles the top-level memory block of the
  flow-file and the per-stage memory keys. The block is emitted if and only
  if at least one stage participates in memory — the memory configuration
  alone never turns the block on. A stage participates by carrying a reflect
  instruction under the reflect method, or a true memory instruction under
  the alignment method. The emitted path composes the fixed memory root with
  the authored suffix. The goga-side method selector never reaches the
  output. Apply `afm` for the external contract of the emitted memory keys.
  Apply `memory` for the authoring vocabulary of the consumed workflow
  instructions. The stage-body keys reflect and memory_use are
  authoring-forbidden — the memory stage keys are compiled exclusively from
  the workflow instructions; an authored occurrence in any stage body is a
  structural error. Output-side only — `PipelineDocument` stays the faithful
  mirror of the source pipeline-file.

  Repeat compilation: the pipeline header declares the repeatable capability
  and this cell owns the single compilation rule — a repeatable pipeline
  ALWAYS produces a repeat key. A workflow repeat block compiles the authored
  keys only (this cell materializes no defaults); a missing block, an absent
  workflow document, or a workflow-free compilation compiles the scalar form.
  A workflow repeat block on a non-repeatable pipeline is a structural error
  naming the conflict — the cross-reference check lives here because only
  this cell sees both documents. The compiled repeat is emitted immediately
  after description, before memory. This cell owns no cycle logic — it counts
  no cycles, decides no stop condition, and prunes nothing; the engine owns
  every cycle semantic and the run stays a single engine invocation.

  Collaboration emission: the cell compiles collaboration from both
  authoring surfaces — the workflow document (catalog, delegation, stage
  entries) and the pipeline declarations each stage body carries — into
  the flow-file alongside the pipeline stages. The top-level
  collaboration block is emitted into every compiled flow — mode
  "assistants" — with max_depth carried when the workflow's delegation
  block authors a depth. The team list is emitted from the catalog in
  authored order, then the pipeline-declared members in pipeline body
  stage order (each stage's declarations in authored order;
  loop-expanded copies collapse to their base stage's first occurrence;
  vetoed and stage-skipped declarations never join; a name joins exactly
  once) — omitted entirely when both sources are empty. Stage assistants
  entries are emitted for every effective attachment of every stage
  present in the compiled body — uniform across every loop-expanded
  copy; a skipped stage attaches nothing; within one stage's compiled
  attachment list the pipeline declarations come first (pipeline
  authored order), then the workflow entries (workflow authored order) —
  the same pipeline-first rule as the prompt append and the skills
  expansion. The team list order is deliberately the opposite: catalog
  members before pipeline-declared members.

  Pipeline declaration carriage: the assistants map of a pipeline-file
  stage body is extracted at parse time into the typed assistants field
  of the step models; the verbatim body mirrors every other field. The
  parsed representation carries the declarations unchanged — the
  workflow extension applies at compilation, output-side only;
  PipelineDocument stays the faithful mirror of the source.

  The effective assistant namespace of a compilation spans the workflow
  catalog, every full inline declaration of the stages-block entry maps,
  and the pipeline declarations of the compiled body. A name carried by
  two sources is a structural error naming both authoring sites (a
  tool-delivered contribution colliding through the overlay included).
  An entry naming a pipeline declaration of its own stage is a skip (the
  {skip: true} veto — no attachment, no team member, no profile for that
  name; the stage itself still runs) or an additive extension: when/gate
  override the pipeline values with absence inheriting them (an authored
  gate: false deliberately downgrades a gated helper), agent/env/
  delegate configure delivery, prompt appends to the pipeline text
  (pipeline text first, one blank line, then the workflow text; a
  single-sided text stands alone), and skills expands the pipeline list
  (pipeline entries first, then workflow entries, deduplicated by value
  preserving first occurrence). An entry naming no pipeline declaration
  of that stage keeps the catalog-reference and inline-declaration
  semantics and requires its own when — the when-required check is
  origin-aware and lives here, where both documents meet (a when-less
  entry extending a pipeline declaration of the same stage is legal
  authoring). A pipeline declaration is visible only to its own stage's
  entry: an entry of another stage naming it is an
  unknown-assistant-reference structural error. An attachment from any
  source on a stage whose translated body carries script, or whose
  translated agents value is exactly ["planning"], is a structural error
  naming the stage and the assistant — the check runs over the working
  body with or without a workflow document (a pipeline declaration
  attaches on every run). An attachment on a skipped stage is silent —
  the stage is removed from the compiled body and nothing attaches.

  Every emitted entry materializes its defaults: mode from gate (true →
  required, false → advisory), trigger from when (start → one_shot,
  checkpoints → checkpoints, finish → on_completion, message → on_message —
  always written
  explicitly, the engine's one_shot default is never relied upon), title
  from the authored name, instruction from the
  authored prompt (the empty string when none). A gated finish — gate true
  with when finish — overrides the trigger row to pre_completion: the
  engine's pre-completion review round runs after the stage agent's turn
  and before the stage completes, so the required verdict can block the
  stage from finishing; an ungated finish keeps on_completion, the final
  turn after the result is ready. A reference takes its
  declaration fields from the named namespace entry and its own gate and
  when overrides. The stage entry carries NO skills key — the engine
  strict-parses stages[].assistants and rejects unknown fields ("unknown
  field \"skills\"; use \"profile\"" on afm v2.0.9); skills reach the
  engine ONLY through a team member entry (which accepts them), and the
  team draws from the catalog and the pipeline declarations — so a
  catalog or pipeline declaration's skills are delivered, while a
  workflow inline declaration's authored skills have no engine channel
  and a compile-time WARNING names the stage and the assistant (once per
  name) instead of dropping them silently. Every
  team member and every stage attachment carries
  the generated profile binding goga-<name> — the binding to the profile
  the engine configuration materializes for the ids this flow references.

  Pre-completion correction budget: a stage carrying at least one gate
  assistant (a gated finish — the pre-completion review participant)
  assembles the `FlowPreCompletion` block into the canonical fields slot
  after memory_use — the engine's per-stage pre_completion setting. The
  value is computed, never authored: max_failures materializes as the
  stage's gate-assistant count times the fixed per-assistant limit (10) —
  without the block the engine allows one correction round per attempt,
  capping the gate assistants at one round's worth of findings. Uniform
  across every loop-expanded copy; a skipped stage attaches nothing and
  emits no budget; a stage with no gate assistant emits no key at all, so
  gate-assistant-free workflows compile byte-identically. The budget is
  independent of the verify settings — a stage carrying both emits
  pre_completion.max_failures and verify.max_failures side by side. An
  authored pre_completion key in a stage body (pipeline-file stage or
  embedded extend-stage body) is a structural error naming the compiled
  origin. Output-side only — `PipelineDocument` stays the faithful mirror
  of the source pipeline-file.

  Stage-body assistant declarations: an authored assistants key in a
  pipeline-file stage body (both body formats) is the stage's helper
  declaration surface — a name-keyed map where every entry declares one
  helper of that stage: its content (prompt, skills) and its engagement
  (when — required, one of start/checkpoints/finish/message; gate —
  optional, materializing false). The delivery keys (agent, env,
  delegate) are not part of the stage-body vocabulary — authoring any of
  them is a structural error naming the stage and the assistant;
  delivery is workflow-file territory. Every declaration resolves
  content — prompt or skills authored — a structural error naming the
  stage and the assistant otherwise. An authored assistants key inside
  an embedded extend-stage body is a structural error naming the stage —
  attachments of a new stage are authored in the workflow stages block
  by the new stage's name.

  Top-level key order: prompt, root_dir, name, description, repeat, memory,
  collaboration, team, stages. The stage pre_completion key occupies the
  canonical fields slot after memory_use and is present only when the stage
  carries at least one gate assistant; the stage assistants key follows it
  and is present only when the stage carries at
  least one effective attachment.

  Use `afm` for the emitted engine contracts — the repeat directive (the
  scalar and map forms, the strict block parse), the team-member and
  stage-assistant key sets, the mode and trigger vocabularies, and the
  profile binding.
  Use `assistants` for the authoring vocabulary of the consumed workflow
  instructions.

  Gates compilation: the cell compiles a stage's authored check steps into the
  engine's stage-completion gate — the verify field of the flow-file. The
  translation is one-directional into the engine vocabulary: script → run
  (a list-form script payload arrives from the parser already joined with
  newlines into one multi-line string),
  agent → command (composed agent-aware: the authored agent name claude
  composes the BARE ALIAS claude — the engine withholds the author's
  Claude credentials from any AI verifier whose command is not exactly the
  bare alias, so the wrapper of the claude CLI (an invocation-shape wrapper,
  no format conversion) never authenticates as a verifier; every other
  agent composes the in-container wrapper path
  /home/goga/bin/<agent>-as-claude.sh — composed directly, no host-side
  resolution, no agent-name existence checks), patience →
  review_patience, max_iterations → max_failures, fresh_correction unchanged;
  name, prompt, and an authored timeout pass verbatim. A shell step without an
  authored timeout carries the materialized "1h"; an AI step materializes no
  timeout default — a goga-side product default, not an engine contract. A
  check step carrying both or neither of script/agent, or carrying prompt
  alongside script (the engine accepts prompt on AI steps only), is a
  structural error with the parser's message ("gates step must carry
  exactly one of script/agent in workflow.stages.<NAME>.gates[<i>]" /
  "prompt is forbidden on a script gate step in
  workflow.stages.<NAME>.gates[<i>]" — authored files hit the parser's own
  checks first; a programmatic workflow, which a tool contribution delivers
  through the overlay merge without a parse, reaches this cell unvalidated,
  and the guard fires instead of composing a wrapper path over a None agent
  or emitting a run+prompt step the engine rejects at load). An empty gates
  list equals absence — the parser normalizes authored emptiness to None,
  and the emission guard treats an empty programmatic list the same: no
  verify key, no body check. When
  the workflow-level gates settings block authored any key, every gated
  stage's verify is the container form (the steps plus the authored settings,
  authored keys only — no materialized settings); with no settings block
  authored, a gated stage carries the steps alone (the list form). The
  settings ride only on gated stages: ungated stages and the engine
  configuration layers are never touched, and the settings block without
  per-stage steps is inert. The verify key occupies the canonical fields slot
  after assistants; inside the emitted block: steps, then the settings in the
  fixed order max_failures, review_patience, fresh_correction; inside a step:
  name, then run/command, then timeout, prompt. A step's authored env map
  never reaches the emitted verify — the emission drops it silently; the
  pipeline run coordination's gate wrapper generation consumes it (per the
  stage-env precedent). Use `afm` for the emitted
  verify contract; use `gates` for the authoring vocabulary of the consumed
  instructions.

  Gates cross-reference checks run here, over the working body after skip
  removal: gates on a stage compiling to a script stage (its body carries
  script) and gates on a planning-only stage (translated agents exactly
  ["planning"]) are strict pre-run errors naming the stage — the engine
  rejects both, and this cell surfaces them with its own messages. A check
  step's script/agent exclusivity and prompt binding are re-checked here
  defensively (see Gates compilation). An
  authoring gates key and a raw verify key in a stage body (pipeline-file
  stage or embedded extend-stage body) are strict compile errors directing
  the author to workflow.stages — verify is a compiled-only key, authored
  exclusively through the workflow stages block. An authoring
  pre_completion key in a stage body is the same family of strict compile
  error — the correction budget is computed from the stage's gate
  assistants, never authored. The checks run once on the
  original — every loop-expanded copy carries the same gate without
  revalidation; the gates of a skipped stage drop silently (skip removal runs
  first).

  This cell performs NO engine-interplay validation — no cross-field checks
  of engine constraints (the failure budget vs the patience value, the
  effective ceiling) — and never interprets, counts, or re-implements gate
  execution: sequencing, fail-fast, full-list re-runs, retry budgets, verdict
  parsing, and waiver are engine behavior. The flow-file is the single
  delivery channel — this cell writes no engine configuration for gates. A
  gate-free workflow compiles byte-identically: no verify key anywhere, no
  other key affected; the pipeline-file and the input representation are
  never modified by gates authoring.

---

"BodyFormat()":
  location: body_format.py
  annotations: |
    str-backed Enum declaring the structural format of a pipeline-file body.

    Modeled via the standard library enum module; str-mixin so values
    serialize as plain strings (per `convention`).

  properties:
    "PHASES = \"phases\"": |
      Body is a YAML list (sorted list of steps with a dash-prefixed name
      item). depends_on is auto-generated by position during compilation.
    "STAGES = \"stages\"": |
      Body is a YAML dict (map keyed by step id). User-supplied depends_on
      is passed through as-is during compilation.

"PipelineRoles(planner: str | None = None, executor: str | None = None, reviewer: str | None = None)":
  location: pipeline_roles.py
  annotations: |
    Data model of the header-level roles directive — three optional
    inline prompt overrides, one per fixed role key. Constructed by
    `parse_dsl` when the header segment contains a non-empty roles
    block; carried verbatim inside `PipelineHeader` (its roles field)
    and surfaced to the consumer through `PipelineDocument`.

    `planner`: inline prompt text overriding
               goga/assets/afm/prompts/planning.md, or None when not
               specified
    `executor`: inline prompt text overriding
                goga/assets/afm/prompts/implementation.md, or None
    `reviewer`: inline prompt text overriding
                goga/assets/afm/prompts/review.md, or None

    The planner/executor/reviewer field names map to the planning/
    implementation/review prompt-file stems via `translate_role`. summary
    is NOT an overridable role — its prompt file is always materialized
    from the default.

    Build the data model with the standard library dataclasses module
    (NOT pydantic, per `convention`). Use @dataclass(kw_only=True).

    Requirements:
    - Use @dataclass(kw_only=True) (per `convention`)
    - All three fields default to None; a pipeline-file may omit any of them
    - Field order is fixed: planner, executor, reviewer — matches the
      canonical order of the overridable prompt files in
      goga/assets/afm/prompts/

    Constraints:
    - Do not validate the contents of prompt text — pass it through
      verbatim to the consumer (run_pipeline writes it to the prompt file
      unchanged)
    - Do not merge or concatenate with default prompt text — the consumer
      replaces the file wholesale
    - Do not carry a summary field — summary is never overridable from the
      DSL

  properties:
    "planner -> str | None": |
      Inline prompt text overriding goga/assets/afm/prompts/planning.md
      (stem resolved via `translate_role`), or None when not specified in
      the header.roles block.
    "executor -> str | None": |
      Inline prompt text overriding
      goga/assets/afm/prompts/implementation.md, or None when not
      specified.
    "reviewer -> str | None": |
      Inline prompt text overriding goga/assets/afm/prompts/review.md,
      or None when not specified.

"PipelineDocument(header: PipelineHeader, format: BodyFormat, body: PhasesBody | StagesBody)":
  location: pipeline_document.py
  annotations: |
    Aggregated pipeline-file document — the parsed representation of a
    pipeline-file as a single value, combining the header, body format,
    and body in one dataclass. Built by `compile_flow` from `parse_dsl`'s
    3-tuple output and returned to consumers as the first element of the
    documents tuple. Exists so that consumers (run_pipeline) can obtain
    the parsed representation — including the roles field of `header` — from a single
    return value without re-invoking parse_dsl.

    `header`: parsed `PipelineHeader` (name, description, optional roles)
    `format`: detected `BodyFormat` — PHASES or STAGES
    `body`: parsed body — `PhasesBody` when format is PHASES,
            `StagesBody` when format is STAGES. The body reflects the
            ORIGINAL parsed body; workflow-applied reconstruction lives
            only in `FlowStage` instances inside `FlowDocument`, never in
            this field.

    Build the data model with the standard library dataclasses module
    (NOT pydantic, per `convention`). Use @dataclass(kw_only=True).

    Requirements:
    - Use @dataclass(kw_only=True) (per `convention`)
    - All three fields are required (no defaults) — a PipelineDocument is
      always complete

    Constraints:
    - Do not validate the body format against the body type — the caller
      (`compile_flow`) constructs PipelineDocument from `parse_dsl`'s
      consistent output

  properties:
    "header -> PipelineHeader": |
      Parsed pipeline-file header (name, description, optional roles).
    "format -> BodyFormat": |
      Detected body format — PHASES or STAGES.
    "body -> PhasesBody | StagesBody": |
      Parsed body. Type matches the format property above: PhasesBody
      when PHASES, StagesBody otherwise. The ORIGINAL parsed body —
      workflow-reconstructed stages live only in `FlowDocument`.

"PipelineHeader(name: str, description: str, roles: PipelineRoles | None = None, repeatable: bool = False)":
  location: pipeline_header.py
  annotations: |
    Header of an input pipeline-file — top-level name and description
    appearing before the three-dash separator, plus an optional roles
    field (of type `PipelineRoles`) carrying inline prompt overrides.
    Parsed by `parse_dsl` from the header segment of the pipeline-file
    text. Carried 1:1 into the `PipelineDocument` (its header field) by
    `compile_flow`. The roles field does not enter the compiled
    `FlowDocument` — it is a goga-side
    artifact surfaced to the consumer through `PipelineDocument`.

    `name`: pipeline name (e.g. "Goga feature")
    `description`: short pipeline description (e.g. "Feature implementation")
    `roles`: optional `PipelineRoles` instance parsed from the
              header-level roles block, or None when the block is
              absent or empty
    `repeatable`: the pipeline's repeat capability — a strictly bool flag,
                  False when the key is absent or explicitly false.
                  Declares that the pipeline may run in cycles; never
                  enters the flow-file directly (the compiled repeat key
                  is derived from it)

    Build the data model with the standard library dataclasses module
    (NOT pydantic, per `convention`). Use @dataclass(kw_only=True).

    Requirements:
    - Use @dataclass(kw_only=True) (per `convention`)
    - `name` and `description` are required (no defaults)
    - roles defaults to None; repeatable defaults to False — a pipeline-file
      may omit the flag; field order is fixed: name, description, roles,
      repeatable

  properties:
    "name -> str": |
      Pipeline name.
    "description -> str": |
      Short pipeline description.
    "roles -> PipelineRoles | None": |
      Inline prompt overrides from the header-level roles block, or
      None when the block is absent or empty. Built by `parse_dsl`;
      carried verbatim through `PipelineDocument` to the consumer. Never
      enters the compiled afm flow-file.
    "repeatable -> bool": |
      The pipeline's repeat capability; False when the header omits the
      flag. Never enters the compiled flow-file directly — the repeat
      directive is derived from it.

"PipelineAssistant(name: str, prompt: str | None = None, skills: list[str] | None = None, when: str, gate: bool = False)":
  location: pipeline_assistant.py
  annotations: |
    Data model of one pipeline-file stage-declared helper — the
    declaration a stage body carries under its assistants map.
    Constructed by parse_dsl from one entry of the stage's map; carried
    inside PhaseStep and StageStep (their assistants field); consumed by
    compile_flow to assemble the stage's attachments and team members.

    `name`: the assistant name — the map key; matches [A-Za-z0-9._-];
            "assistant" is rejected; unique within its stage's map
            (uniqueness across the effective namespace is a compilation
            check)
    `prompt`: the helper's instruction text, or None when not authored
    `skills`: the helper's own skill names, or None when not authored —
              an authored empty list is a value
    `when`: the engagement — one of start, checkpoints, finish, message;
            authored on every declaration; no default exists
    `gate`: whether the helper's verdict must pass before the stage may
            finish; materialized false when not authored

    Use `convention` for the data-model rules (dataclasses kw_only=True).

    Requirements:
    - Use @dataclass(kw_only=True) (per `convention`)
    - name is required (no default); prompt and skills default to None;
      when is required (no default — no compiler-side engagement
      default exists); gate defaults to False; field order is fixed:
      name, prompt, skills, when, gate

    Constraints:
    - Do not validate the name grammar, types, or value domains here —
      parse_dsl enforces them during parsing
    - Do not resolve delivery — the declaration carries no delivery
      fields; agent, env, and delegate are workflow-file territory
  properties:
    "name -> str": |
      The assistant name — the map key; unique within its stage's map.
    "prompt -> str | None": |
      The helper's instruction text, or None when not authored.
    "skills -> list[str] | None": |
      The helper's own skill names, or None when not authored; an
      authored empty list is a value.
    "when -> str": |
      The engagement — start, checkpoints, finish, or message; authored
      on every declaration; no default exists.
    "gate -> bool": |
      Whether the helper's verdict holds stage completion; materialized
      false when not authored.

"PhaseStep(name: str, title: str, body: dict[str, Any], assistants: dict[str, PipelineAssistant] | None = None)":
  location: phase_step.py
  annotations: |
    One element of a phases-DSL body — a single dash-prefixed name list item.

    `name`: step id (the value of the name field inside the list item)
    `title`: display label (the value of title inside the item)
    `body`: verbatim copy of every other field in the item (e.g. roles,
            prompt, skills, interactive, and any extra fields),
            excluding name, title, and assistants
    `assistants`: the step's pipeline assistant declarations — a map of
                  PipelineAssistant keyed by assistant name, in authored
                  order, or None when the source body carries no
                  assistants key or an empty map

    Does not carry depends_on — the compiler generates it from list
    position when building `FlowStage`.

    The body field is intentionally typed as dict[str, Any]: the cell
    does not validate or know the schema of step fields. Build the data
    model with the standard library dataclasses module (NOT pydantic,
    per `convention`). Use @dataclass(kw_only=True).

    Requirements:
    - Use @dataclass(kw_only=True) (per `convention`)
    - The body field excludes name, title, and assistants (those are
      separate fields); the assistants key is extracted from the source
      body at parse time

    Constraints:
    - Do not validate the contents of body — pass it through verbatim
    - Do not normalize or rename keys in body

  properties:
    "name -> str": |
      Step id.
    "title -> str": |
      Display label.
    "body -> dict[str, Any]": |
      Verbatim extra fields of the step (excluding name, title, and the
      extracted assistants key).
    "assistants -> dict[str, PipelineAssistant] | None": |
      The step's pipeline assistant declarations keyed by assistant
      name, in authored order. None when the source body carries no
      assistants key or an empty map (an empty map equals absence).

"StageStep(name: str, title: str, depends_on: list[str] | None, body: dict[str, Any], assistants: dict[str, PipelineAssistant] | None = None)":
  location: stage_step.py
  annotations: |
    One entry of a stages-DSL body — a value in the body map, keyed by step id.

    `name`: step id (the map key)
    `title`: display label (the value of title inside the value)
    `depends_on`: list of predecessor step ids, or None when the field
                  is absent from the source value
    `body`: verbatim copy of every other field in the value (excluding
            title, depends_on, and the extracted assistants key)
    `assistants`: the step's pipeline assistant declarations — a map of
                  PipelineAssistant keyed by assistant name, in authored
                  order, or None when the source body carries no
                  assistants key or an empty map

    Carries `depends_on` from the source; the compiler passes it through
    unchanged when building `FlowStage`.

    The body field is intentionally typed as dict[str, Any]: the cell
    does not validate or know the schema of step fields. Build the data
    model with the standard library dataclasses module (NOT pydantic,
    per `convention`). Use @dataclass(kw_only=True).

    Requirements:
    - Use @dataclass(kw_only=True) (per `convention`)
    - The body field excludes title, depends_on, and assistants (those
      are separate fields); name is the map key, also not part of the
      body; the assistants key is extracted from the source body at
      parse time
    - `depends_on` distinguishes None (absent) from an empty list
      (explicit empty)

    Constraints:
    - Do not validate the contents of `body` — pass it through verbatim
    - Do not normalize or rename keys in `body`
    - Do not validate `depends_on` references — afm's responsibility

  properties:
    "name -> str": |
      Step id.
    "title -> str": |
      Display label.
    "depends_on -> list[str] | None": |
      Predecessor step ids, or None when absent.
    "body -> dict[str, Any]": |
      Verbatim extra fields of the step (excluding title, depends_on,
      and the extracted assistants key).
    "assistants -> dict[str, PipelineAssistant] | None": |
      The step's pipeline assistant declarations keyed by assistant
      name, in authored order. None when the source body carries no
      assistants key or an empty map (an empty map equals absence).

"PhasesBody(steps: list[PhaseStep])":
  location: phases_body.py
  annotations: |
    Body of a phases-DSL pipeline-file — an ordered list of `PhaseStep`
    items, in the source order. The order carries semantic meaning: the
    compiler auto-generates depends_on from list position (first step
    gets none, each subsequent step depends on the previous one).

    Build the data model with the standard library dataclasses module
    (NOT pydantic, per `convention`). Use @dataclass(kw_only=True).

    Requirements:
    - Use @dataclass(kw_only=True) (per `convention`)
    - Preserve insertion order of `steps`

  properties:
    "steps -> list[PhaseStep]": |
      Ordered list of phase steps.

"StagesBody(steps: list[StageStep])":
  location: stages_body.py
  annotations: |
    Body of a stages-DSL pipeline-file — an ordered list of `StageStep`
    items, in the iteration order of the source map (Python 3.7+ preserves
    dict insertion order). The order carries no dependency meaning
    (depends_on is user-supplied per step) but determines the order of
    stages in the output flow-file.

    Build the data model with the standard library dataclasses module
    (NOT pydantic, per `convention`). Use @dataclass(kw_only=True).

    Requirements:
    - Use @dataclass(kw_only=True) (per `convention`)
    - Preserve insertion order of `steps`

  properties:
    "steps -> list[StageStep]": |
      Ordered list of stage steps.

"FlowStage(id: str, name: str, depends_on: list[str] | None, fields: dict[str, Any])":
  location: flow_stage.py
  annotations: |
    One stage of an output afm flow-file — a single dash-prefixed id list
    item under the stages key. Both `PhaseStep` and `StageStep` converge
    into this type during compilation.

    `id`: step identifier (output as a dash-prefixed id item)
    `name`: display label (output as the name field)
    `depends_on`: predecessor step ids, or None. None produces no depends_on
                  key in output; an empty list produces depends_on [].
    `fields`: extra step fields in canonical key order (interactive,
              auto_approve, auto_run, command, prompt, description, buttons,
              agents, supervisor, supervisor_prompt, skills, script_before,
              script, script_after, script_timeout, reflect, memory_use,
              pre_completion, assistants, verify, then alphabetically-sorted
              unknown keys).
              buttons (map of str→str) is present only when the workflow
              supplied a non-empty notes instruction for the stage — the map
              passes through verbatim.
              auto_run (bool) is present only when the stage's effective
              trigger is manual — the value is always False; auto_run: true
              is never assembled. script_before/script/script_after (str)
              are present only when the corresponding stage directive was
              authored — a list payload arrives already joined with newlines
              into one multi-line string (the output field is always a
              string); script_timeout (str) is present only when the
              corresponding directive was authored. reflect (map of file +
              mode) is present only when the block is emitted and the
              stage's reflect instruction is effective — the authored file
              verbatim, the materialized mode; uniform across every
              loop-expanded copy. memory_use (bool) is present only when
              the block is emitted under the alignment method — True on a
              participating stage, explicit False on every non-participating
              one. Both occupy the canonical slots after script_timeout. A
              stage of a memory-free workflow carries neither key.
              pre_completion (a `FlowPreCompletion` budget) is present only
              when the stage carries at least one gate assistant (a gated
              finish attachment) — the computed correction budget, uniform
              across every loop-expanded copy; a skipped stage carries none.
              assistants (list) is present only when the stage carries at
              least one effective attachment — uniform across every
              loop-expanded copy; a skipped stage carries none.
              verify (a `FlowVerify` gate) is present only when the stage
              carries authored check steps — uniform across every
              loop-expanded copy; a skipped stage carries none.
              Insertion order of
              this dict IS the output order — the
              serializer iterates it as-is. command is populated from the
              agent field of `WorkflowStage` (composed as the in-container
              wrapper path) when a workflow supplies one; description is
              populated from the prompt field of `WorkflowStage` when a
              workflow supplies one. Both are independent channels —
              pipeline-file prompt and workflow-file prompt may coexist as
              separate fields in the same stage. agents is populated by the
              default-injection rule of `compile_flow` (to the single value
              ["auto"]) when the source step body has no usable agents value
              (missing key, explicit null, or empty list); a body carrying
              script assembles NO agents key at all (afm rejects the
              combination — both the ["auto"] default and a translated
              roles value are suppressed); supervisor and
              supervisor_prompt appear ONLY when the source step body authors
              them.

    The description slot in `fields` is a distinct channel from
    `FlowStage` name: the name field carries the display label sourced
    from the pipeline-file step (the title field of `PhaseStep` or
    `StageStep`), while the description field inside `fields` carries
    the workflow-file per-stage prompt override. Both can coexist in the same
    `FlowStage` instance without collision — they live in different slots
    and serialize as separate YAML keys (name vs description inside the
    stage item).

    The compiler builds `fields` with the canonical key order when
    constructing the `FlowStage` instance; the serializer does not reorder.

    Build the data model with the standard library dataclasses module
    (NOT pydantic, per `convention`). Use @dataclass(kw_only=True).

    Requirements:
    - Use @dataclass(kw_only=True) (per `convention`)
    - `fields` keys must be in canonical order when constructed
    - `depends_on` distinguishes None (absent) from an empty list (explicit empty)

  properties:
    "id -> str": |
      Step identifier.
    "name -> str": |
      Display label.
    "depends_on -> list[str] | None": |
      Predecessor step ids, or None when absent.
    "fields -> dict[str, Any]": |
      Extra fields in canonical key order: interactive, auto_approve,
      auto_run, command, prompt, description, buttons, agents, supervisor,
      supervisor_prompt, skills, script_before, script, script_after,
      script_timeout, reflect, memory_use, pre_completion, assistants,
      verify, then alphabetically-sorted unknown
      keys. buttons
      (map of str→str) is present only when the workflow supplied a
      non-empty notes instruction for the stage. auto_approve
      (bool) is present only when the effective approve directive drives the
      roles effect ("auto"/"dialog") + planner-in-roles fired; auto_run (bool)
      is present only when the stage's effective trigger is manual — the value
      is always False, auto_run: true is never assembled; script_before/script/
      script_after/script_timeout (str) are present only when the corresponding
      stage directive was authored. reflect (map of file + mode) is present
      only when the block is emitted and the stage's reflect instruction is
      effective — the authored file verbatim, the materialized mode; uniform
      across every loop-expanded copy. memory_use (bool) is present only when
      the block is emitted under the alignment method — True on a
      participating stage, explicit False on every non-participating one.
      Both occupy the canonical slots after script_timeout. A stage of a
      memory-free workflow carries neither key. pre_completion (a
      `FlowPreCompletion` budget) is present only when the stage carries at
      least one gate assistant (a gated finish attachment) — the computed
      correction budget, uniform across every loop-expanded copy; a skipped
      stage carries none. assistants (list) is
      present only when the stage carries at least one effective
      attachment — uniform across every loop-expanded copy; a skipped
      stage carries none. verify (a `FlowVerify` gate) is present only
      when the stage carries authored check steps — uniform across every
      loop-expanded copy; a skipped stage carries none. Insertion order
      IS the output order — the
      serializer iterates as-is. command/description from WorkflowStage;
      agents default-injected to ["auto"], absent entirely in a body
      carrying script; supervisor/supervisor_prompt only
      when authored.

"FlowMemory(path: str, mode: str | None = None, memory_use: bool | None = None, max_rules: int, commit: bool)":
  location: flow_memory.py
  annotations: |
    Emitted top-level memory block of the flow-file — the compiled form of
    the workflow-memory configuration. Built by `compile_flow` when memory
    participates; consumed by `serialize_flow`.

    `path`: the composed memory root — the fixed root joined with the
            authored suffix (the bare root when no suffix)
    `mode`: the project-memory access mode — the fixed "r" for the reflect
            method (read-only project memory); the materialized authored
            value ("rw" by default) for the alignment method
    `memory_use`: the global participation default — always False in the
                  emitted block (participation is per-stage opt-in; afm's
                  UseFor(stage) inherits this default for an unset stage key)
    `max_rules`: the maximum number of memory rules (always >= 1)
    `commit`: whether memory changes are committed

    Build the data model with the standard library dataclasses module
    (NOT pydantic, per `convention`). Use @dataclass(kw_only=True).

    Requirements:
    - Use @dataclass(kw_only=True) (per `convention`)
    - Field order is fixed: path, mode, memory_use, max_rules, commit — the
      emission order of the block keys
    - reflect method: mode "r", memory_use False; alignment method: mode the
      materialized authored value ("rw" by default), memory_use False
    - A None field is omitted from the output entirely

    Constraints:
    - Do not decide here whether the block is emitted — `compile_flow`
      decides on participation
    - Do not compose `path` here — the caller composes the root and suffix
    - Do not interpret the block — the runtime behavior belongs to afm (per
      `afm`)
  properties:
    "path -> str": |
      The composed memory root — the fixed root joined with the authored
      suffix.
    "mode -> str | None": |
      The project-memory access mode — "r" for the reflect method, the
      materialized authored value for the alignment method.
    "memory_use -> bool | None": |
      The global participation default; False in every emitted block
      (participation is per-stage opt-in).
    "max_rules -> int": |
      The maximum number of memory rules; always >= 1.
    "commit -> bool": |
      Whether memory changes are committed.

"FlowRepeat(max_cycles: int | None = None, keep_runs: int | None = None)":
  location: flow_repeat.py
  annotations: |
    Emitted top-level repeat directive of the flow-file — the compiled form
    of the workflow run-cycle tuning block. Built by `compile_flow` for a
    repeatable pipeline; consumed by `serialize_flow`.

    `max_cycles`: the authored maximum number of complete run cycles, or
                  None when not authored
    `keep_runs`: the authored number of recent cycle run-directories to
                 retain, or None when not authored

    A directive carrying no authored key IS the scalar form — the
    serialization writes the short form and the engine applies its own
    defaults; this cell materializes no values.

    Build the data model with the standard library dataclasses module
    (NOT pydantic, per `convention`). Use @dataclass(kw_only=True).

    Requirements:
    - Use @dataclass(kw_only=True) (per `convention`)
    - Both fields default to None — an instance carries authored values
      only; an authored zero is a value, not an omission
    - Field order is fixed: max_cycles, keep_runs — the emission order of
      the block keys

    Constraints:
    - Do not decide here whether the directive is emitted — `compile_flow`
      decides on the pipeline capability
    - Do not interpret the bounds — the runtime behavior belongs to the
      engine (per `afm`)
  properties:
    "max_cycles -> int | None": |
      The authored maximum number of complete run cycles, or None when not
      authored.
    "keep_runs -> int | None": |
      The authored number of recent cycle run-directories to retain, or
      None when not authored.

"FlowCollaboration(mode: str = \"assistants\", max_depth: int | None = None)":
  location: flow_collaboration.py
  annotations: |
    Emitted top-level collaboration block of the flow-file. Built by
    `compile_flow` on every compilation; consumed by `serialize_flow`.

    `mode`: the dashboard collaboration mode — always "assistants"
    `max_depth`: the authored delegation depth, or None — None omits the
                 key from the output entirely

    Build the data model with the standard library dataclasses module
    (NOT pydantic, per `convention`). Use @dataclass(kw_only=True).

    Requirements:
    - Use @dataclass(kw_only=True) (per `convention`)
    - mode defaults to "assistants" — the block is emitted into every
      compiled flow
    - Field order is fixed: mode, max_depth — the emission order of the
      block keys; a None max_depth is omitted from the output entirely

    Constraints:
    - Do not decide here whether the block is emitted — `compile_flow`
      always constructs it
    - Do not interpret the block — the runtime behavior belongs to afm
      (per `afm`)
  properties:
    "mode -> str": |
      The dashboard collaboration mode; "assistants" in every emitted
      block.
    "max_depth -> int | None": |
      The authored delegation depth, or None when no depth is authored
      (the key is omitted from the output).

"FlowTeamMember(id: str, title: str, profile: str, instruction: str, skills: list[str])":
  location: flow_team_member.py
  annotations: |
    Emitted team member — one run-level assistant of the flow-file. Built
    by `compile_flow` from one catalog entry of the workflow document, in
    authored order; consumed by `serialize_flow`.

    `id`: the assistant's authored name — the stable identity the engine
          recognizes on resume
    `title`: the display title — the authored name; the dashboard handle
             derives from it
    `profile`: the generated profile binding goga-<name> — the binding to
               the profile the engine configuration materializes for this
               flow
    `instruction`: the assistant's instruction — the authored prompt, the
                   empty string when none is authored
    `skills`: the assistant's own skills — the authored list, an empty
              list when none is authored

    Build the data model with the standard library dataclasses module
    (NOT pydantic, per `convention`). Use @dataclass(kw_only=True).

    Requirements:
    - Use @dataclass(kw_only=True) (per `convention`)
    - Field order is fixed: id, title, profile, instruction, skills — the
      emission order of the member keys
    - instruction and skills are always materialized — defaults included

    Constraints:
    - Do not derive the profile command here — the engine configuration
      write materializes it
    - Do not interpret the member — the runtime behavior belongs to afm
      (per `afm`)
  properties:
    "id -> str": |
      The assistant's authored name; the identity the engine recognizes
      on resume.
    "title -> str": |
      The display title — the authored name.
    "profile -> str": |
      The generated profile binding goga-<name>.
    "instruction -> str": |
      The assistant's instruction; the empty string when none is authored.
    "skills -> list[str]": |
      The assistant's own skills; an empty list when none is authored.

"FlowAssistant(profile: str, title: str, instruction: str, mode: str, trigger: str)":
  location: flow_assistant.py
  annotations: |
    Emitted stage attachment entry — one assistant attached to one stage
    of the flow-file. Built by `compile_flow` from one effective
    attachment; consumed by `serialize_flow`.

    `profile`: the generated profile binding goga-<name>
    `title`: the assistant's name
    `instruction`: the authored prompt, the empty string when none
    `mode`: the gate mapping — "required" when the effective gate is
            true, "advisory" otherwise
    `trigger`: the engagement mapping — "one_shot" from start,
               "checkpoints" from checkpoints, "pre_completion" from a
               gated finish (gate true — the pre-completion review that
               can block the stage from finishing), "on_completion" from
               an ungated finish, "on_message" from message (the resting
               engagement — no initial request; each message is one turn
               and the helper stays attached)

    The entry carries NO skills field: the engine strict-parses
    stages[].assistants entries and rejects any key outside the five
    above (verified against afm v2.0.9 — `unknown field "skills"; use
    "profile"`). Skills reach the engine ONLY through a FlowTeamMember
    entry, which accepts them — and team members are built from the
    catalog alone, so an inline declaration's authored skills have no
    engine channel (a compile-time WARNING names them; the catalog is
    the delivery form).

    Build the data model with the standard library dataclasses module
    (NOT pydantic, per `convention`). Use @dataclass(kw_only=True).

    Requirements:
    - Use @dataclass(kw_only=True) (per `convention`)
    - Field order is fixed: profile, title, instruction, mode, trigger —
      the emission order of the entry keys
    - Every field is always materialized — defaults included; the
      trigger is written explicitly, never inherited from the
      engine default

    Constraints:
    - Do not interpret mode or trigger — the runtime behavior belongs to
      afm (per `afm`)
  properties:
    "profile -> str": |
      The generated profile binding goga-<name>.
    "title -> str": |
      The assistant's name.
    "instruction -> str": |
      The authored prompt; the empty string when none is authored.
    "mode -> str": |
      required when the effective gate is true, advisory otherwise.
    "trigger -> str": |
      one_shot, checkpoints, on_completion, pre_completion (a gated
      finish), or on_message — mapped from the gate/when pair.

"FlowPreCompletion(max_failures: int)":
  location: flow_pre_completion.py
  annotations: |
    Emitted pre-completion correction budget — a stage's pre_completion
    block, the engine setting that bounds how many failed correction
    attempts the stage's pre-completion review rounds may process before
    the stage fails. Built by `compile_flow` from the stage's gate
    assistants (the gated finish attachments, compiled to trigger
    pre_completion); carried in the stage fields; consumed by
    `serialize_flow`.

    `max_failures`: the correction budget — the stage's gate-assistant
                    count times the fixed per-assistant limit. Always
                    computed, never authored; a strictly positive int.

    Requirements:
    - Use @dataclass(kw_only=True) (per `convention`)
    - max_failures is required (no default) — the block is emitted only
      when a stage carries at least one gate assistant, and the value is
      always computed
    - Field order is fixed: max_failures — the emission order of the
      block keys

    Constraints:
    - Do not decide here whether the block is emitted — `compile_flow`
      decides on the stage's gate assistants
    - Do not interpret the budget — the round semantics belong to afm
      (per `afm`)
  properties:
    "max_failures -> int": |
      The correction budget — the gate-assistant count times the fixed
      per-assistant limit; a strictly positive int.

"FlowVerifyStep(name: str, run: str | None = None, command: str | None = None, timeout: str | None = None, prompt: str | None = None)":
  location: flow_verify_step.py
  annotations: |
    Emitted verify step — one check of a stage's completion gate. Built by
    `compile_flow` from one authored check step; consumed by
    `serialize_flow`.

    `name`: the check's dashboard label — the authored name verbatim
    `run`: the shell command of a shell step (from the authored script — a
           list-form payload arrives already joined with newlines into one
           multi-line string), or None
    `command`: the launch command of an AI step — the authored agent name
               composed into the in-container wrapper path
               /home/goga/bin/<agent>-as-claude.sh, or None
    `timeout`: the step timeout — the authored value verbatim, or the
               materialized "1h" on a shell step without an authored
               timeout; None on an AI step without an authored timeout
    `prompt`: the AI step's review instruction, carried verbatim, or None

    Requirements:
    - Use @dataclass(kw_only=True) (per `convention`)
    - Exactly one of `run`/`command` is not None — the step form mirrors
      the authored exclusivity
    - Field order is fixed: name, run, command, timeout, prompt — the
      emission order of the step keys

    Constraints:
    - Do not decide here whether the timeout is materialized —
      `compile_flow` applies the shell-step rule when building
    - Do not interpret the step — execution semantics belong to the
      engine (per `afm`)
  properties:
    "name -> str": |
      The check's dashboard label; the authored name verbatim.
    "run -> str | None": |
      The shell command of a shell step, or None.
    "command -> str | None": |
      The AI step's launch command — the authored agent name composed
      into the in-container wrapper path, or None.
    "timeout -> str | None": |
      The authored timeout verbatim, the materialized "1h" on a shell
      step without one, or None on an AI step without one.
    "prompt -> str | None": |
      The AI step's review instruction, carried verbatim, or None.

"FlowVerify(steps: list[FlowVerifyStep], max_failures: int | None = None, review_patience: int | None = None, fresh_correction: bool | None = None)":
  location: flow_verify.py
  annotations: |
    Emitted stage completion gate — the compiled form of a stage's
    authored check steps and, when the workflow-level settings block
    authored any key, the authored retry settings under the engine
    vocabulary. Built by `compile_flow`; carried in the stage fields;
    consumed by `serialize_flow`.

    `steps`: the compiled check steps in authored order
    `max_failures`: the authored iteration bound (from max_iterations),
                    or None when not authored
    `review_patience`: the authored stalemate tolerance (from patience),
                       or None when not authored
    `fresh_correction`: the authored correction-session mode, or None
                        when not authored

    An instance carrying no authored setting IS the list emission form —
    the serialization writes the steps alone; any authored setting
    switches to the container form. This cell materializes no settings
    defaults.

    Requirements:
    - Use @dataclass(kw_only=True) (per `convention`)
    - `steps` is required (no default); every setting defaults to None —
      an authored zero is a value, not an omission
    - Field order is fixed: steps, max_failures, review_patience,
      fresh_correction — the emission order of the block keys

    Constraints:
    - Do not decide here whether the gate is emitted — `compile_flow`
      decides on the authored check steps
    - Do not interpret the settings or the steps — execution semantics
      belong to the engine (per `afm`)
  properties:
    "steps -> list[FlowVerifyStep]": |
      The compiled check steps in authored order.
    "max_failures -> int | None": |
      The authored iteration bound, or None when not authored.
    "review_patience -> int | None": |
      The authored stalemate tolerance, or None when not authored.
    "fresh_correction -> bool | None": |
      The authored correction-session mode, or None when not authored.

"FlowDocument(prompt: str | None = None, root_dir: str | None = None, name: str, description: str, repeat: FlowRepeat | None = None, memory: FlowMemory | None = None, collaboration: FlowCollaboration | None = None, team: list[FlowTeamMember] | None = None, stages: list[FlowStage])":
  location: flow_document.py
  annotations: |
    Output afm flow-file — a single flat YAML document with up to nine
    top-level keys (prompt (when present), root_dir (when supplied),
    name, description, repeat (when the pipeline is repeatable), memory
    (when memory participates), collaboration (always), team (when the
    workflow carries a catalog), stages). No
    segmentation, no header sub-object:
    the format is flat, and this type mirrors that flatness.

    `prompt`: top-level prompt value emitted as the FIRST top-level key of
              the flow-file when not None. Populated from the prompt field
              of `WorkflowDocument` when a workflow supplies one;
              None otherwise (omitted from output — no top-level prompt
              key in the flow-file).
    `root_dir`: top-level afm root_dir directive value emitted as the
              SECOND top-level key of the flow-file (immediately after
              the prompt key when present, before the name key) when not
              None. Populated by the caller (the run_pipeline routine in
              goga/pipeline) from the in-container project root
              (Path.cwd() resolves to /workspace inside the goga container);
              None when the caller did not supply one (omitted from output
              — no top-level root_dir key in the flow-file). The compiler
              itself performs no environment-variable reads.
    `repeat`: the compiled repeat directive, or None when the pipeline is
              not repeatable. Emitted between description and memory when
              not None; an instance carrying no authored key is the scalar
              form; None omits the key entirely (byte-identical output for
              non-repeatable pipelines)
    `memory`: the compiled memory block, or None when memory does not
              participate. Emitted between description and stages when not
              None; omitted entirely when None — byte-identical output for
              memory-free workflows.
    `collaboration`: the compiled collaboration block — constructed on
                     every compilation (mode "assistants" in every
                     compiled flow); emitted between memory and team
    `team`: the compiled team list — one `FlowTeamMember` per catalog
            entry in authored order; an empty list omits the key from
            the output entirely
    `name`: top-level name value (carried 1:1 from `PipelineHeader` name)
    `description`: top-level description value (carried 1:1 from
                   `PipelineHeader` description)
    `stages`: ordered list of `FlowStage` items, output as the stages list.
              When a workflow supplied loop-expansion or per-stage
              overrides, the list reflects the reconstructed stages; when
              no workflow was applied, the list reflects the original
              parsed body.

    The only object `serialize_flow` accepts as input.

    Build the data model with the standard library dataclasses module
    (NOT pydantic, per `convention`). Use @dataclass(kw_only=True).

    Requirements:
    - Use @dataclass(kw_only=True) (per `convention`)
    - `prompt` defaults to None — the flow-file omits the top-level prompt
      key when no workflow supplies one
    - `root_dir` defaults to None — the flow-file omits the top-level
      root_dir key when the caller did not supply one
    - memory defaults to None; collaboration defaults to None; team
      defaults to None; repeat defaults to None; field order is fixed:
      prompt, root_dir, name, description, repeat, memory, collaboration,
      team, stages — the canonical emission order in `serialize_flow`

  properties:
    "prompt -> str | None": |
      Top-level flow prompt, or None when no workflow supplied one. Emitted
      as the first top-level key when not None.
    "root_dir -> str | None": |
      Top-level afm root_dir directive, or None when the caller did not
      supply one. Emitted as the second top-level key (after prompt when
      present, before name) when not None.
    "name -> str": |
      Top-level flow name.
    "description -> str": |
      Top-level flow description.
    "repeat -> FlowRepeat | None": |
      The compiled repeat directive; an instance carrying no authored key
      is the scalar form. None when the pipeline is not repeatable — the
      key is omitted from the output entirely.
    "memory -> FlowMemory | None": |
      The compiled memory block, or None when memory does not participate.
    "collaboration -> FlowCollaboration | None": |
      The compiled collaboration block; present in every compiled flow.
    "team -> list[FlowTeamMember] | None": |
      The compiled team list in authored order; empty when the workflow
      carries no catalog.
    "stages -> list[FlowStage]": |
      Ordered list of flow stages.

"parse_dsl(text: str) -> header: PipelineHeader, format: BodyFormat, body: PhasesBody | StagesBody":
  location: parse_dsl.py
  annotations: |
    Structurally parse a pipeline-file into a header, a body format, and a
    typed body. No content validation of step fields; no depends_on rule
    application.

    `text`: full pipeline-file text (must contain a three-dash separator line)
    `header`: parsed `PipelineHeader` (name, description from the header
              segment; plus an optional roles field of type
              `PipelineRoles` or None, carrying inline prompt overrides
              from the header-level roles block — None when the block is
              absent or an empty mapping, a `PipelineRoles` instance
              otherwise)
    The format output is the detected `BodyFormat` — PHASES if the body is
    a YAML list, STAGES if the body is a YAML dict.
    The body output is the parsed body — `PhasesBody` when format is PHASES,
    `StagesBody` when format is STAGES.

    Algorithm:
    1. Split `text` into a header segment and a body segment on the
       three-dash separator. If no such separator exists — raise a
       structural error "missing body separator". The split is the
       structural pre-check (separator presence, exactly three dashes);
       the content is not parsed from the segments
    2. Parse the whole `text` as ONE YAML stream whose anchor registry
       survives the document boundary, so YAML links carry across the
       separator: an anchor declared in the header segment (or in a
       hidden body key) resolves in the body segment, and aliases keep
       their sequential order (an alias authored before its anchor
       fails). On a YAML error of any kind — raise a structural error
       "invalid YAML in pipeline-file". The stream must carry exactly
       two documents: a single document means the header segment is
       empty or comment-only, and a leading separator line means the
       same (the stream's first document is body content) — both raise
       "header missing name/description"; a third document (an extra
       separator line inside the body) raises "extra body separator".
       Extract the header from the first document: name and description.
       If either is missing or not a str — raise a structural error
       "header missing name/description". Then extract the optional
       roles block from the header mapping. If the block is absent or
       an empty mapping — set roles to None. If the block is present but
       its value is not a mapping (e.g. a scalar, a string, a list) —
       raise a structural error "non-mapping roles block in header".
       Otherwise validate every key against the fixed set {planner,
       executor, reviewer}: an unknown key (including summary) raises
       a structural error "unknown role in header.roles: <key>; valid
       keys: planner, executor, reviewer"; a non-str value raises a
       structural error "non-str value in header.roles.<key>". Build
       `PipelineRoles` from the validated entries.
       Then extract the optional repeatable flag: when present, its value
       must be strictly bool — otherwise raise a structural error
       "non-bool value in header.repeatable"; an absent key equals False.
       Build `PipelineHeader` with name, description, roles, and
       repeatable.
       ADDITIONALLY, if the header mapping carries the agents
       key — raise a structural error "agents key is forbidden in
       header; use roles".
    3. Take the second stream document as the body and drop every hidden
       declaration key from a mapping body — top-level str keys starting
       with "." are YAML anchor sites, not stage names; their content is
       already merged by YAML resolution
    4. Detect format by the structure of the parsed body:
       - a list → `BodyFormat` PHASES; build a `PhasesBody` of `PhaseStep`
         items (one per list entry). Each list item must carry string name
         and title fields; otherwise raise a structural error
         "phase item missing name/title"
       - a dict → `BodyFormat` STAGES; build a `StagesBody` of `StageStep`
         items (one per map entry). Each map value must carry a string
         title field; otherwise raise a structural error
         "stage value missing title"
       - any other shape — raise a structural error "unsupported body format"
    4a. For each parsed step item (both formats), when the item value
        carries an assistants key: a non-mapping value raises a
        structural error "non-mapping assistants in stage <name>; author
        the map form keyed by assistant name"; an empty map equals
        absence (assistants None); every entry value must be a mapping
        with the key set prompt, skills, when, gate — an unknown key
        raises a structural error naming the stage, the assistant, and
        the valid keys (the delivery keys agent, env, delegate are named
        in the message as workflow-file territory); every entry key
        matches [A-Za-z0-9._-] and is not "assistant"; prompt (when
        present) is a str; skills (when present) is a list[str]; when is
        required and one of start/checkpoints/finish/message; gate (when
        present) is strictly bool; a declaration resolving neither
        prompt nor skills raises a structural error naming the stage and
        the assistant. Build one PipelineAssistant per entry; the map is
        extracted into the step's typed assistants field and excluded
        from the verbatim body
    5. Return (header, format, body)

    Apply `convention` for code style and exception message formatting.

    Requirements:
    - The three-dash separator is matched as a line of exactly three dashes
      (per YAML document separator convention), not as a substring
    - YAML links carry across the separator: the file parses as one stream
      with a shared anchor registry, so an anchor declared in the header
      segment or in a hidden body key resolves in the body segment; aliases
      stay sequential (an alias before its anchor fails) and a duplicate
      anchor name across segments fails
    - A YAML error of any kind (header or body) raises the clean structural
      error "invalid YAML in pipeline-file" — raw YAML internals never leak
    - The stream must carry exactly two documents: fewer (an empty or
      comment-only header segment, or a leading separator line) raises
      "header missing name/description"; more (an extra separator line
      inside the body) raises "extra body separator"
    - Hidden declaration keys — top-level str keys of a mapping body
      starting with "." — are dropped before stage assembly: they are YAML
      anchor sites, never stage names, and their content is already merged
    - An empty body (`PhasesBody` with zero steps or `StagesBody` with zero
      steps) is NOT a structural error here — `compile_flow` checks for
      emptiness
    - `PhaseStep` and `StageStep` carry deep copies of the parsed body
      dicts, so subsequent mutation does not affect the source
    - The stage-body assistants grammar: a name-keyed mapping; an empty
      map equals absence; each entry value carries the key set prompt,
      skills, when, gate; when is required and one of the four values;
      gate is strictly bool; a declaration must resolve prompt or skills;
      the delivery keys agent, env, delegate are rejected with an error
      naming the stage and the assistant
    - The assistants map is extracted into the typed step field and
      excluded from the verbatim body; steps carry deep copies of the
      parsed declarations
    - The fixed role key set is exactly {planner, executor, reviewer} —
      no other keys accepted (summary is not a valid role)
    - An absent roles block and an empty roles mapping are treated
      identically: roles is set to None
    - The agents key in the header is a structural error
    - A non-str value for a known key is a structural error (not silently
      coerced)
    - A non-mapping value for the roles block itself (scalar, string,
      list) is a structural error — the block must be a mapping or absent
    - The repeatable key (when present) must be strictly bool; absent
      equals False; the flag is carried into `PipelineHeader` and never
      enters the compiled flow-file directly

    Constraints:
    - Do not apply depends_on rules — that is `compile_flow`'s job
    - Do not validate the contents of step fields
    - Do not resolve or validate depends_on references — afm's job
    - Do not handle a pipeline-file without a three-dash separator
      (already-afm format) — it is an error by design
    - Do not validate or merge inline prompt text — `parse_dsl` passes
      the roles values through verbatim; the consumer (the run_pipeline
      routine in goga/pipeline)
      decides how to materialize them

"StructuralError(message: str)":
  location: parse_dsl.py
  annotations: |
    Structural error of pipeline-file parsing and compilation — raised, never
    returned. The exception `parse_dsl` raises for grammar violations
    (malformed header, roles, phases/stages bodies) and `compile_flow` raises
    for composition violations (workflow/stage-name correspondence, memory
    instructions). A ValueError subclass, so consumers can catch either the
    concrete type or ValueError — exported through the facade for exactly
    that catch.

    `message`: the human-readable structural error text (no payload, no
               extra state)

    Requirements:
    - Inherits ValueError; constructed with `message` only

    Constraints:
    - Do not carry structured error data — the message is the whole contract

"serialize_flow(doc: FlowDocument) -> text: str":
  location: serialize_flow.py
  annotations: |
    Serialize a `FlowDocument` into a byte-exact string in the canonical afm
    flow-file format. Uses the `beautiful_yaml` parameters plus custom
    rules for canonical key order and flow-style for agents.

    `doc`: the `FlowDocument` to serialize (fields must already be in
           canonical key order — `compile_flow` enforces this when building;
           top-level prompt and root_dir may each be None or a str)
    `text`: the resulting YAML string, byte-equivalent to flow.yml for
            equivalent content

    Algorithm:
    1. Build a top-level representation in fixed order:
       - when `doc` prompt is not None — emit prompt as the FIRST
         top-level key, in block-literal scalar style (multi-line prompt
         text). When `doc` prompt is None — omit the key entirely
         (no top-level prompt key in the output)
       - when `doc` root_dir is not None — emit root_dir as the SECOND
         top-level key (after prompt when present, before name), as a
         plain scalar. When `doc` root_dir is None — omit the key entirely
         (no top-level root_dir key in the output)
       - when `doc` repeat is not None — emit the repeat directive after
         description and before memory: an instance carrying no authored
         key is the scalar form (written repeat: true); otherwise a
         block-style mapping of the authored keys in the fixed order
         max_cycles, keep_runs
         (present keys only, plain scalars). When `doc` repeat is None —
         omit the key entirely
       - when `doc` memory is not None — emit the memory block after
         description and before stages, key order path, mode, memory_use,
         max_rules, commit; every present value a plain scalar; a None
         field omitted entirely (no key in the output). When `doc` memory
         is None — omit the block entirely
       - when `doc` collaboration is not None — emit the collaboration
         block after memory (when present) and before team: a block-style
         mapping, key order mode, max_depth, plain scalars; a None
         max_depth is omitted entirely
       - when `doc` team is non-empty — emit the team list before stages:
         a block-style list; each member a block-style mapping, key order
         id, title, profile, instruction, skills; instruction a plain
         scalar when single-line and a block-literal scalar when
         multi-line (the script-family pattern); skills a block-style
         list, written explicitly when empty
       - name, then description, then stages (per step 2)
    2. For each `FlowStage` in `doc`, build a representation in canonical
       key order: id, name, then the stage fields as-is (already in
       canonical order — interactive, auto_approve, auto_run, command,
       prompt, description, buttons, agents, supervisor, supervisor_prompt,
       skills, script_before, script, script_after, script_timeout, reflect,
       memory_use, pre_completion, assistants, verify, then
       alphabetically-sorted unknown
       keys), then depends_on
       when it is not None. The serializer does NOT reorder — canonical
       order is fixed at `FlowStage` assembly. Stage memory keys: reflect —
       a block-style mapping of plain scalars (file, mode); memory_use — a
       plain bool scalar. Stage pre_completion: a block-style mapping of one
       plain int scalar (max_failures) in the canonical slot after
       memory_use. Stage assistants: a block-style list of mappings
       in the canonical slot after pre_completion; each entry a block-style
       mapping, key order profile, title, instruction, mode, trigger;
       instruction follows the script-family pattern; mode and trigger
       plain scalars; NO skills key on a stage entry — the engine
       strict-parses stages[].assistants and rejects unknown fields
       (skills travel only on a team member entry, and the team draws
       from the catalog alone). Stage verify: when the stage fields carry
       the verify gate — an instance with no authored setting serializes
       as the list form (the steps list is the verify value); an instance
       with any authored setting serializes as the container form: a
       block-style mapping with steps first, then the authored settings
       in the fixed order max_failures, review_patience, fresh_correction
       (present keys only, plain scalars); each step is a block-style
       mapping, key order name, run|command, timeout, prompt;
       run/command/timeout/prompt are plain scalars when single-line and
       block-literal scalars when multi-line (the script-family pattern)
    3. Serialize the representation to YAML per `beautiful_yaml`, with the
       flow-style applied to agents and block-style applied to skills,
       depends_on, and the top-level prompt; auto_approve and auto_run as
       plain bool scalars; script_before / script / script_after as plain
       scalars when single-line and block-literal scalars when multi-line;
       script_timeout as a plain scalar when single-line and a block-literal
       scalar when multi-line (the script-family pattern); buttons values:
       single-line text — a plain scalar (quoted as needed), multi-line text
       — a block-literal scalar; the buttons map itself is emitted as a
       regular block-style mapping
    4. Ensure the result ends with a single trailing newline
    5. Return the string

    Apply `beautiful_yaml` for the YAML serialization parameters.
    Apply `convention` for code style and docstring formatting.

    Requirements:
    - Output is canonical afm flow-file YAML: optional prompt (first,
      when present), optional root_dir (second, when supplied), then
      fixed top-level key order (name, description, repeat (when present),
      memory (when present), collaboration, team, stages), canonical
      per-stage key order (including auto_approve, auto_run, command,
      description, buttons, script_before/script/script_after/script_timeout,
      reflect, memory_use, pre_completion, assistants, and verify),
      flow-style for agents, block-style for skills and depends_on,
      auto_approve and auto_run as plain bool scalars, single trailing newline
    - a non-repeatable flow document serializes without the repeat key —
      byte-identical output
    - the scalar form is written for a repeatable pipeline carrying no
      authored key
    - When `doc` prompt is None — the output omits the prompt key
      entirely (no top-level prompt key in the output)
    - When `doc` root_dir is None — the output omits the root_dir key
      entirely (no top-level root_dir key in the output)
    - root_dir is emitted as a plain scalar (NOT block-literal style like
      the top-level prompt)
    - agents is emitted in flow-style; skills, depends_on, and the
      top-level prompt are emitted in block-style
    - Empty list values (e.g. an explicit empty depends_on) are written
      explicitly, not omitted
    - All other key-value pairs follow `beautiful_yaml` defaults
    - a stage without a manual-effective trigger serializes without the
      auto_run key (byte-identical output for trigger-free pipelines);
      auto_run serializes only as auto_run: false
    - a stage without an authored timeout serializes without the
      script_timeout key
    - buttons values: single-line text as a plain scalar (quoted as needed),
      multi-line text as a block-literal scalar; a stage without a buttons key
      serializes without it (byte-identical output for notes-free pipelines)
    - A flow document without memory serializes without the block and without
      any memory stage key — byte-identical output for memory-free workflows
    - The block occupies the position between description and stages; the stage
      keys occupy their canonical slots
    - A flow document without a team and without stage attachments
      serializes without those keys — byte-identical output except the
      always-present collaboration mode key
    - A stage without a gate serializes without the verify key
      (byte-identical output for gate-free workflows); the container form
      is emitted only when a setting is authored; step scalar style follows
      the script-family pattern

    Constraints:
    - Do not reorder keys — canonical order is fixed at assembly
    - Do not validate `doc` — assume it is well-formed (`compile_flow`
      constructed it)
    - Do not write to disk — return the string; the caller writes it
    - Do not reorder the new keys — the canonical order (collaboration
      between memory and team, team before stages, stage assistants after
      memory_use) is fixed at assembly
    - Do not interpret the gate — the runtime behavior belongs to afm (per
      `afm`)

"compile_flow(pipeline_path: Path, flow_path: Path, workflow: WorkflowDocument | None = None, root_dir: str | None = None, project_name: str | None = None) -> documents: tuple[PipelineDocument, FlowDocument]":
  location: compile_flow.py
  annotations: |
    Entry point of the cell: compile a pipeline-file (goga DSL) into an afm
    flow-file at the given paths. Reads `pipeline_path`, parses and detects
    format via `parse_dsl`, applies per-format depends_on rules and canonical
    key order, builds a `FlowDocument`, serializes it via `serialize_flow`,
    writes to `flow_path`, and returns the documents tuple. When `workflow`
    is supplied (a `WorkflowDocument`), the cell reconstructs the parsed
    body per the workflow instructions BEFORE building the FlowDocument;
    when `workflow` is None, no workflow is applied and the output carries
    no top-level prompt and no per-stage overrides.

    `pipeline_path`: absolute path to the input pipeline-file (DSL format)
    `flow_path`: absolute path to the output flow-file (afm format). The
                 parent directory must already exist — `compile_flow` does
                 not create it
    `workflow`: optional `WorkflowDocument` carrying declarative
                instructions for extending the pipeline (top-level prompt,
                per-stage agent/prompt/loop overrides, AND new stages via
                extend with before/after positioning). When None — no
                workflow is applied, the output carries no top-level prompt
                and no per-stage overrides. Supplied by the consumer
                (the run_pipeline routine in goga/pipeline), parsed from a
                project workflow-file via parse_workflow (per the
                `parse-workflow` practice).
    `root_dir`: optional top-level afm root_dir directive carried into the
                `FlowDocument` and emitted by `serialize_flow` as the
                top-level root_dir key immediately after the prompt key
                (when present) and before the name key. When None — the
                root_dir key is omitted entirely. Supplied by the
                consumer (the run_pipeline routine in goga/pipeline),
                which resolves the value from the in-container project
                root (Path.cwd() == /workspace inside the goga container —
                the single source of truth mirroring the host-side mount
                decision).
    `project_name`: optional project name (basename of the git origin remote URL,
                minus a trailing .git) used as the description prefix in the
                compiled flow-file. When not None — the `FlowDocument` description
                becomes f"[{project_name}] {header.description}"; when None — the
                description is the header description unchanged. OUTPUT-only: the
                `PipelineDocument` description stays the faithful mirror (like
                `root_dir`). Supplied by the consumer (the run_pipeline routine in
                goga/pipeline), which resolves it in-container via
                resolve_project_name; the compiler performs no environment /
                subprocess reads to derive it.
    `documents`: a tuple of `PipelineDocument` and `FlowDocument` — the
                 parsed input representation (carrying header roles when
                 present; the ORIGINAL parsed body, NOT the
                 workflow-reconstructed body) and the output flow-file model
                 (including workflow-applied overrides, loop-expansion,
                 rewritten depends_on, the top-level prompt when a
                 workflow supplied one, and the top-level root_dir when
                 the caller supplied one). The text flow-file is also
                 written to `flow_path` as a side effect.

    Algorithm:
    1. Read `pipeline_path` as text
    2. Call `parse_dsl` to obtain (header, format, body)
    3. If the body has zero steps — raise a structural error "empty body"
    4. When `workflow` is not None — reconstruct the body per the `workflow`
       instructions (BEFORE building FlowStages):
       4.0. Repeat correspondence check (when `workflow` is not None): when
            the workflow document carries a repeat block and the parsed
            header's repeatable flag is False — raise a structural error
            "workflow repeat block requires a repeatable pipeline; author
            repeatable: true in the pipeline header". The workflow parser
            never sees the pipeline; this cell owns the cross-reference
            check
       4.1. Embed extend-stages and position them via before/after — STAGES
            derives their explicit depends_on, PHASES inserts them into the
            body list (only when the workflow's extend map is non-empty):
            1. Build the set of known names: every step name/id present in
               the body, plus every extend-stage name. The set resolves
               cross-references between extend-stages.
            2. For each extend-stage name and its `WorkflowExtendStage` in
               the workflow's extend map (resolve cross-references via the
               known-names set; a second pass or deferred resolution handles
               extend-stages referencing not-yet-embedded extend-stages):
               - STAGES branch (explicit depends_on via the StageStep field):
                 2.1. Construct a `StageStep` whose name is the extend-stage
                      name, whose title comes from the extend-stage body,
                      whose depends_on is initialized from the extend-stage
                      after (None when after is None), and whose body is the
                      extend-stage body minus title.
                 2.2. For each name in the extend-stage before (when present):
                      append the extend-stage name to the depends_on of the
                      existing body step whose name/id equals that name
                      (initialize to an empty list when it had no depends_on).
               - PHASES branch (positional insertion — `PhaseStep` carries
                 NO depends_on field; depends_on is derived by list position
                 in step 5):
                 2.1. Construct a `PhaseStep` whose name is the extend-stage
                      name and whose title and body come from the extend-stage
                      body.
                 2.2. Compute the insertion index from the positioning fields:
                      immediately AFTER the step whose name/id equals the LAST
                      resolvable after name, and/or immediately BEFORE the
                      step whose name/id equals the FIRST resolvable before
                      name. When both after and before are present, the index
                      must satisfy both (after-targets precede
                      before-targets); when inconsistent, fall back to the
                      after-based index and emit a WARNING.
                 2.3. Insert the `PhaseStep` at the computed index; subsequent
                    steps shift down. Step 5's positional derivation then
                    yields the correct depends_on: the extend-stage depends
                    on its positional predecessor (the after-target, or the
                    after-target's last loop-expanded copy once 4.6 runs),
                    and each before-target gains the extend-stage as its
                    positional predecessor. Multi-target before/after in
                    PHASES reduces to a single positional predecessor per
                    step, but the transitive execution order still respects
                    every target (an extend-stage after [A, B] is placed
                    after the last of A and B, so it runs after both via the
                    positional chain).
               - Dangling reference (a before/after name absent from the
                 known-names set) — cannot occur at this step: step 4.2
                 strict-validates every before/after ref BEFORE the embed and
                 raises a structural error "unknown stage name in
                 workflow.extend.<name>.before/.after: <ref>". The embed thus
                 runs as a pure transform that may assume every ref resolves.
            3. Place the constructed extend-steps into the body sequence:
               - STAGES: add the `StageStep`s to the body map, keyed by
                 name (their explicit depends_on encodes before/after).
               - PHASES: the `PhaseStep`s are already inserted at their
                 computed positions; depends_on is derived purely by list
                 position in step 5 (no explicit depends_on is carried).

       4.2. Strict-validation of workflow.extend.<name>.before/.after refs:
                build the valid-name set = { every step name/id in the
                ORIGINAL body } ∪ { every extend-stage name in workflow.extend }.
                For each before/after ref: if the ref is NOT in the valid-name
                set — raise a structural error "unknown stage name in
                workflow.extend.<name>.before/.after: <ref>". Runs BEFORE the 4.1
                embed (extend names come from workflow.extend keys, so cross-
                references between extend-stages resolve without embedding) and
                BEFORE any skip removal, so a really-existing skipped stage is
                NOT flagged (referencing a skipped stage is not a dangling ref).
                Existence only — cycles, self-references, and duplicate refs
                remain afm's responsibility.
       4.3. Strict-validation of workflow.stages names: build the valid-name
             set = { every step name/id in the ORIGINAL body } ∪ { every
             extend-stage name embedded at 4.1 }. For each name in
             workflow.stages: if the name is NOT in the valid-name set — raise
             a structural error "unknown stage name in workflow.stages: <name>".
             The check runs on the FULL set BEFORE any skip removal, so a
             really-existing skipped stage is NOT flagged as unknown. Extend-
             stage names are valid here (embedded before this check). Strictness
             over extend.<name>.before/.after refs is enforced at 4.2
             (above); a workflow must not carry a dangling extend ref.
       4.4. Skip removal + transparent depends_on reconnection: determine the
             skipped-name set = { name : workflow.stages[name].skip is True
             AND name exists in the working body }. Then:
             - STAGES branch (explicit depends_on reconnection):
               1. For each remaining `StageStep` D with a non-None depends_on,
                  rebuild depends_on as: for each ref in D.depends_on, if ref
                  is a skipped name S — replace with resolve(S); else keep
                  {ref}. resolve(S) = union of resolve(P) for P in
                  S.depends_on (a skipped P recurses; a non-skipped P
                  contributes {P}); a skipped S whose depends_on is None or
                  resolves to nothing contributes {}. resolve is evaluated
                  with a visited set so a depends_on cycle among skipped
                  stages terminates (cycles remain afm's concern — the
                  compiler does not validate them, but must not crash).
                  Deduplicate the rebuilt list preserving first-occurrence
                  order; a resulting empty list is written as depends_on []
                  (explicit empty). References to non-skipped names are
                  unchanged.
               2. Remove every `StageStep` whose name is a skipped name from
                  the body map.
             - PHASES branch (position-derived depends_on): remove every
               `PhaseStep` whose name is a skipped name from the body list.
               The position-derived depends_on in step 5 then chains the
               remaining steps correctly (a removed step is simply absent
               from the positional chain — automatic collapse, no explicit
               reconnection).
             skip wins over agent/prompt/loop/skills overrides on the same
             entry — removal runs BEFORE 4.5, so the skipped stage's overrides
             are never applied (they target a stage already gone).
             Guard: after removal, if the reconstructed body has zero steps —
             raise a structural error "empty body" (consistent with the
             existing empty-body guard on the ORIGINAL body at step 3). This
             covers the edge-case where skip removes every stage of the
             pipeline.

       4.5. Apply per-stage overrides (in-place mutation of the body's step
           bodies) — matches embedded extend-stages by
           name; the agent override falls back to an extend-entry's
           inline agent; a skills merge is applied. A name not found in the
           body is SILENTLY skipped (it can only be an intentionally skipped
           stage removed at 4.4; unknown names already errored at 4.3).
           Compute the EFFECTIVE
           override for each stage name by merging, per field, the explicit
           stages entry (when present and providing the field) OVER the
           extend-entry's inline agent/loop/approve (treated as defaults):
          - For each stage name that has EITHER an explicit stages-block
            entry OR (originated from an extend-entry carrying inline agent,
            loop, or approve), determine the effective values:
            * Find the step in the body whose name/id equals the stage name
            * If not found — silent (it can only be an intentionally skipped
              stage removed at 4.4; unknown names already errored at 4.3)
            * If found:
              - effective agent = the stages-block agent when the entry
                provides it (not None), else the extend-entry's inline
                agent when this step originated from an extend-entry
                carrying one, else leave the step's existing command
                unchanged. When the effective agent is not None and the
                step body authors script — raise the structural error
                "agent is forbidden on a script stage in workflow.<name>:
                <agent>" (the stage action is one, the agent exec target
                or the script; a composed command never rides the
                flow-file beside a script). Otherwise assign the
                wrapper path /home/goga/bin/<agent>-as-claude.sh to the
                command slot of the step body (the wrapper path is composed
                directly — do NOT call any host-side wrapper resolver)
              - when the stages-block prompt for this name is not None —
                assign that prompt text to the description slot of the step
                body (prompt has no inline extend equivalent — an
                extend-entry's prompt already lives in its body)
              - when the stages-block skills for this name is not None —
                merge skills: set the step body's skills to
                dedup(pipeline_skills ++ workflow_skills), where
                pipeline_skills is the step body's existing skills (or []),
                workflow_skills is the stages-block skills list, ++
                concatenates (pipeline first), and dedup drops later
                duplicates by value preserving first-occurrence position.
                Pipeline-only or workflow-only sides are harmless; both
                empty yields no skills key
              - effective approve = the stages-block approve when the entry
                provides it (not None), else the extend-entry's inline
                approve when this step originated from an extend-entry
                carrying one, else None. Thread the effective approve into
                the per-stage body for step 5 (it drives the interactive-
                suppress / auto_approve effects there)
              - effective manual = the stages-block entry's manual for this
                name (None when the entry provides no manual key or the name
                has no entry). Application on the WORKING body copy:
                * None — the stage body's trigger stands unchanged
                * True — set the working body's trigger to manual (forcing;
                  setting it on an already-manual stage is an idempotent
                  no-op)
                * False — when the stage body (pipeline-file body OR
                  extend-stage body) carries trigger manual, set the working
                  body's trigger to on_success (cancellation: the assembled
                  stage carries no auto_run key); otherwise raise a structural
                  error "manual: false on non-manual stage <NAME>"
                The rewrite targets the working body copy only — the original
                parsed body and PipelineDocument stay untouched
              - effective notes = the stages-block notes for this name (None
                when the entry provides no notes key or the name has no
                entry). The extend-seeded branch carries notes=None — notes
                has no inline extend equivalent (notes in an extend-entry is
                rejected by the workflow parser). An overlay merge passes the
                notes field explicitly — an overlay that omitted it would
                silently drop the instruction
       4.6. Build a new ordered list of steps with loop-expansion applied —
           expands an extend-stage when the effective
           loop for that name is >= 2 (producing NAME-1..N):
          - Maintain an expanded-ids map from each base-name to the list
            of ids produced for it
          - For each step in the body (in source order):
            * Determine loop_count: effective loop for the step's name =
              the stages-block loop when the entry provides it (not
              None), else the extend-entry's inline loop when this step
              originated from an extend-entry carrying one, else 1
            * When loop_count == 1 — append the step unchanged (id stays
              as-is); record the base-name mapped to a single-element list
              containing only the base-name
            * When loop_count >= 2 — append N copies with id
              NAME-1, NAME-2, ..., NAME-N. The FIRST copy inherits the
              original step's external depends_on (rewritten in step 4.7);
              each subsequent copy gets an internal depends_on pointing to
              the previous copy (chain). Record the base-name mapped to
              the list [NAME-1, ..., NAME-N]
          - For PHASES format (position-derived depends_on): each expanded
            copy becomes its own PhaseStep in the list; the position in the
            new list determines depends_on automatically during step 5
            (the original step's position is inherited by the first copy;
            subsequent copies depend on their predecessor copy by list
            position; the next ORIGINAL step after the expanded one
            naturally depends on the LAST copy via list position)
       4.7. Rewrite external depends_on references — including
           before/after-derived refs (symmetric — both
           point to the chain's completion). STAGES only — PHASES format is
           handled by position in step 5:
          - For each StageStep in the new sequence with non-None
            depends_on: for each ref in depends_on:
            * When ref matches a base-name whose loop_count >= 2 — replace
              with the LAST id from that base-name's expanded-ids list
            * When ref matches a base-name whose loop_count == 1 — keep
              the ref as-is; it points to the single unexpanded copy whose
              id equals the base-name (see step 4.6)
            * Otherwise (ref does not match any base-name in the body) —
              keep ref as-is and let afm surface a dangling-reference
              error if applicable
          - The same LAST-expanded-id rewrite applies to
            before/after-derived refs: a ref equal to an after name whose
            loop_count >= 2, and a before-target's ref to the new
            extend-stage whose loop_count >= 2, both resolve to the LAST
            expanded id (depends_on means "runs after", so any reference
            to a loop-expanded chain points to its LAST copy). PHASES
            extend-stages were positionally inserted at 4.1; loop-expansion
            at 4.6 chains their copies in place, so each extend-stage's
            positional predecessor is the after-target's last expanded
            copy — no explicit rewrite needed for PHASES.
       4.8. Replace the body's step list with the new (embedded + expanded +
           rewritten) sequence.
       4.9. Compute memory participation from the workflow (when `workflow`
           is not None). The effective memory configuration is the
           `WorkflowMemory` value of the workflow document when it carries
           one, else a default-constructed `WorkflowMemory` (its field
           defaults ARE the materialized authoring defaults: path None,
           max_rules 25, commit False, mode None — the default method is
           "reflect"). The method is the materialized method of the
           effective configuration; under the reflect method — a stage
           participates when its `WorkflowReflect` instruction is not None;
           under the alignment method — a stage participates when its memory
           instruction is True. Participation is computed over the stages
           present in the working body after skip removal and loop expansion
           (embedded extend-stages included; a stage removed by skip —
           a workflow-file skip directive OR a CLI skip directive — never
           counts, so a run whose every participating stage was skipped
           emits no block)
       4.10. Resolve the assistant attachments of the working body (after
             skip removal and loop expansion) over the effective assistant
             namespace — the `WorkflowAssistant` catalog of the workflow
             document, the full inline declarations found in the
             stages-block entry maps, and the pipeline declarations carried
             by the working body's steps:
             - namespace uniqueness: a name carried by two sources
               (catalog, inline, pipeline declarations — a tool-delivered
               contribution included through the overlay) raises a
               structural error naming both authoring sites
             - the content check: EVERY workflow declaration of the
               effective namespace (the catalog plus every full inline
               declaration, override-style entries included) must resolve
               content — its effective prompt or its effective skills is
               not None; a declaration resolving neither raises a
               structural error naming the assistant and its authoring site.
               The check addresses workflow declarations only — a pipeline
               declaration resolves content at parse time, and a reference
               or extension carries no content of its own
             For each stage of the working body, assemble the effective
             attachment list — the stage's pipeline declarations first
             (authored order), then the stage's workflow entries (authored
             order):
             - a workflow entry naming a pipeline declaration of THIS
               stage: a {skip: true} entry vetoes that declaration — no
               attachment, no team member, no profile for the name; the
               stage still runs. Any other entry is an additive extension:
               effective when = the entry's authored when, else the
               declaration's; effective gate = the entry's authored gate,
               else the declaration's; effective prompt = the declaration's
               prompt joined to the entry's prompt with exactly one blank
               line when both are authored (pipeline text first; a
               single-sided text stands alone); effective skills = the
               declaration's list expanded with the entry's (declaration
               entries first, then entry entries, deduplicated by value
               preserving first occurrence); the entry's agent/env/delegate
               configure delivery (consumed by the engine configuration
               write)
             - a workflow entry naming no pipeline declaration of this
               stage: an entry naming no namespace member raises a
               structural error "unknown assistant reference in
               workflow.stages.NAME: <assistant>" — including a name
               pipeline-declared by ANOTHER stage (a pipeline declaration
               is visible only to its own stage's entry). A reference or
               full inline declaration carrying when None raises the
               structural error "when is required in
               workflow.stages.NAME.assistants.ASSISTANT" (the origin-aware
               when-required check: a when-less entry is legal only as an
               extension of a pipeline declaration of the same stage). A
               {skip: true} entry naming no pipeline declaration of this
               stage raises a structural error "skip targets a
               pipeline-declared assistant in
               workflow.stages.NAME.assistants.ASSISTANT" — the veto is
               exclusively the veto over what the pipeline ships; the name
               may be a namespace member (a catalog entry or an inline
               declaration), and not authoring the attachment is how those
               are governed. The
               same name twice in one stage's effective attachment list of
               a programmatic contribution raises a structural error naming
               the stage and the assistant
             - every assembled attachment from any source on a stage whose
               translated body carries script, or whose translated agents
               value is exactly ["planning"], raises a structural error
               naming the stage and the assistant — the check runs over the
               working body with or without a workflow document
             An emitted attachment whose resolved source is a workflow
             inline declaration authoring skills logs a WARNING naming the
             stage and the assistant — once per name (no engine channel;
             only catalog and pipeline declarations become team members);
             the warning replaces a silent drop and never adds an
             output-side key
       4.11. Gates cross-reference checks (over the working body after skip
           removal and loop expansion):
           - authoring-key prohibitions (the same pass as the existing
             authoring-key checks, pipeline-file stage OR embedded
             extend-stage body): a `gates` key in a stage body raises a
             structural error "gates key is forbidden in stage body; use
             gates in workflow.stages"; a raw verify key in a stage body
             raises a structural error "verify key is forbidden in stage
             body; use gates in workflow.stages"
           - for each stage of the working body whose effective gates list
             is not None: a stage whose translated body carries script
             raises a strict error naming the stage; a stage whose
             translated agents value is exactly ["planning"] raises a
             strict error naming the stage
           - the checks run once per stage name on the original —
             loop-expanded copies inherit the gate without revalidation;
             the gates of a removed stage never reach the checks
    5. Build FlowStages from the (possibly reconstructed) body:
       - PHASES: for each `PhaseStep`, build a `FlowStage` with depends_on
         derived from list position (first step has none; each subsequent
         step depends on the previous one — including expanded copies,
         which chain naturally via list position)
       - STAGES: for each `StageStep`, build a `FlowStage` with depends_on
         passed through from the (possibly rewritten) source step
       - Body source: pipeline-file step body for an existing stage; the
         extend-stage body (the body field of `WorkflowExtendStage`) for an
         extend-stage
       - In both branches, BEFORE assembling fields, check script exclusivity:
         if the (effective) body carries script together with prompt and/or
         skills — raise a structural error "script is mutually exclusive with
         prompt/skills in stage <name>" (every stage, incl. loop-expanded
         copies; same pass as the agents/interactive-forbidden checks).
         if the (effective) body carries script together with command (a key
         authored verbatim in a stage body or an extend-stage body — it is
         not pipeline vocabulary but rides the unknown-key passthrough) —
         raise a structural error "script is mutually exclusive with command
         in stage <name>" (the workflow agent-instruction path already
         errored at 4.5 with its own message).
         before_script/after_script do NOT trigger the error
       - In both branches, BEFORE assembling fields, check the
         authoring-buttons prohibition: an authoring buttons key in a stage
         body (pipeline-file stage OR embedded extend-stage) raises a
         structural error "buttons key is forbidden in stage body; use notes
         in workflow.stages" (same pass as the agents/interactive-forbidden
         checks)
       - Stage-body validation (in the existing stage-body checking pass):
         a reflect or memory_use key in a stage body (pipeline-file stage OR
         embedded extend-stage body) raises a structural error "reflect key
         is forbidden in stage body; use reflect in workflow.stages" /
         "memory_use key is forbidden in stage body; use memory in
         workflow.stages"
       - In both branches, BEFORE canonical ordering, inject default stage
         fields when the source step body has no usable roles value
         (missing key, explicit null, or empty list): set agents to
         ["auto"] — EXCEPT in a body carrying script, where NO agents key
         is assembled at all (afm rejects agents combined with script):
         neither the ["auto"] default NOR the translated roles value
         reaches the output, while the roles elements are still validated
         (a non-str element raises the same structural error). The input
         stage-body field for the afm agents list is
         roles; an authored non-empty roles value is translated entry-
         by-entry via `translate_role` (known aliases mapped, all other
         values passed through verbatim) into the output agents value.
         An authoring agents key in a stage body — pipeline-file stage OR
         embedded extend-stage — is a structural error "agents key is
         forbidden in stage body; use roles". auto is a sentinel agent
         mode emitted verbatim — goga does not interpret it (afm resolves
         it). supervisor and supervisor_prompt are NOT default-injected
         (they appear only when the source step body authors them). An
         authored non-empty roles value always wins and disables
         injection. The ORIGINAL parsed body is never mutated by this
         injection — defaults live in FlowStage assembly only
       - Stage script directives: translate present body keys
         before_script → script_before, script → script, after_script →
         script_after (the authoring keys are consumed, not passed through
         to output). Validate each translated value in the same pass: a
         string passes verbatim; a non-empty list of non-empty strings
         joins with newlines into ONE multi-line string (the script's
         lines); anything else raises a structural error "before_script|
         script|after_script must be a string or a non-empty list of
         non-empty strings in stage <name>" naming the AUTHORED key — the
         check runs AFTER the script exclusivity check and BEFORE the
         timeout directive of the same pass
       - Stage timeout directives: validate and translate the timeout key of the
         (effective) body of every stage (pipeline-file stages, embedded
         extend-stages, and every loop-expanded copy) in the same pass as the
         script exclusivity check:
         * a present timeout whose value is not a string → structural error
           naming the stage
         * a present timeout without a script key in the same body → structural
           error naming the stage
         * translate timeout → script_timeout (the authoring key is consumed),
           placing the value verbatim into the canonical slot immediately after
           script_after; the key is emitted only when timeout is authored, and
           when both timeout and a direct script_timeout are authored, the
           translated timeout value wins
       - approve effects: for a stage whose EFFECTIVE approve is "auto"
         (threaded in at step 4.5), read the trigger fields from THAT STAGE'S
         body and apply two INDEPENDENT effects:
         * interactive translation: communication → interactive, EXCEPT
           when the effective approve directive drives the communication
           effect ("auto"/"plan") AND the body has communication: true —
           SUPPRESS (emit no interactive key). communication: false ⇒
           interactive: false as usual. The "interactive key is
           forbidden in stage body; use communication" error applies to an
           authoring interactive key
         * auto_approve: the effective approve directive drives the roles
           effect ("auto"/"dialog") AND the body roles (the raw list,
           before `translate_role`) contains literal "planner" — emit
           auto_approve: true (canonical slot next to interactive).
           Otherwise absent
         The two effects are independent — each fires on its own trigger
         AND its own directive subset; baseline no-op when the effective
         approve is None or neither trigger applies; uniform across every
         loop-expanded copy
       - validate the trigger field of the (effective) body of every stage
         (pipeline-file stages, embedded extend-stages, and every
         loop-expanded copy): when present, its value must be exactly
         on_success or manual; otherwise raise a structural error "trigger
         must be one of: on_success, manual". An authoring auto_run key in
         the body (pipeline-file stage OR embedded extend-stage) raises a
         structural error "auto_run key is forbidden in stage body; use
         trigger: manual"
       - Stage trigger translation: a body whose (effective) trigger is
         manual assembles auto_run: false into fields in the canonical slot
         immediately after auto_approve; a body with trigger on_success or
         without a trigger assembles NO auto_run key. auto_run: true is never
         emitted. The authoring trigger key is consumed by the translation —
         it never reaches the output as an unknown key. Uniform across every
         loop-expanded copy
       - Workflow notes translation: when the effective notes for the stage is
         not None — assemble buttons (the map verbatim, keys and values
         unchanged) into the fields canonical slot immediately after
         description; uniform across every loop-expanded copy. A stage without
         an effective notes assembles NO buttons key. Output-side only — the
         source bodies and PipelineDocument stay untouched
       - Stage memory keys assembly (uniform across every loop-expanded copy;
         a skipped stage never reaches here): when the block is emitted and
         the method is reflect — a stage carrying a `WorkflowReflect`
         instruction assembles the reflect field (the authored file verbatim,
         the materialized mode) into the canonical slot after script_timeout;
         when the block is emitted and the method is alignment — every stage
         assembles memory_use into the canonical slot after reflect: True on
         a participating stage, explicit False on every non-participating one;
         when the block is not emitted — no stage carries any memory key
       - Stage pre-completion budget assembly: count the stage's gate
         assistants (the effective attachment entries whose trigger is
         pre_completion — exactly the gated finish attachments); when the
         count is positive, assemble a `FlowPreCompletion` with
         max_failures = count × the fixed per-assistant limit (10) into
         the canonical slot after memory_use; uniform across every
         loop-expanded copy; a stage with no gate assistant assembles no
         pre_completion key (the engine's own default applies). An
         authored pre_completion key in a stage body (pipeline-file stage
         or embedded extend-stage body) raises a structural error
         "pre_completion key is forbidden in stage body; it is compiled
         from the stage's gate assistants" (same pass as the other
         authoring-key prohibitions — the budget is computed, never
         authored)
       - Stage assistants assembly: assemble the assistants key from the
         stage's effective attachment list — one `FlowAssistant` per entry
         with every field materialized — into the canonical slot after
         pre_completion; uniform across every loop-expanded copy; a stage
         without attachments assembles no assistants key. An authored
         assistants key in an embedded extend-stage body raises a
         structural error "assistants key is forbidden in stage body; use
         assistants in workflow.stages" (same pass as the other
         authoring-key prohibitions — a defensive re-check: the workflow
         parser rejects it at parse time, a programmatic contribution
         reaches this cell unparsed)
       - Stage gates assembly: when a stage's effective gates list is not
         None — build a `FlowVerify`:
         * one `FlowVerifyStep` per authored `WorkflowGateStep` of the
           stage's effective gates list, in authored order: script →
           run with the timeout materialized to "1h" when not authored;
           agent → command composed as
           /home/goga/bin/<agent>-as-claude.sh (composed directly — no
           host-side resolution, no agent-name existence check); name,
           prompt, and an authored timeout carried verbatim; an AI
           step materializes no timeout default
         * the settings: when the `WorkflowGates` block of the workflow
           document authored any key, carry the authored keys only,
           translated (patience → review_patience, max_iterations →
           max_failures, fresh_correction unchanged); with no settings
           block authored, every setting stays None (the list form)
         * assemble into the `FlowStage` fields canonical slot after
           `assistants`; uniform across every loop-expanded copy;
           output-side only — the source bodies and `PipelineDocument`
           stay untouched
       - In both branches, assemble the fields of each `FlowStage` in the
         EXTENDED canonical key order (interactive, auto_approve, auto_run,
         command, prompt, description, buttons, agents, supervisor,
         supervisor_prompt, skills, script_before, script, script_after,
         script_timeout, reflect, memory_use, pre_completion, assistants,
         verify, then alphabetically-sorted unknown keys), copying
         from the (defaults-injected) step body.
         auto_approve (bool) is present only when the effective approve
         directive drives the roles effect ("auto"/"dialog") + planner-in-roles
         fired; script_before / script / script_after / script_timeout (str)
         are present only when the corresponding stage directive was authored
         (a list-form script payload is already joined into one multi-line
         string — the output field is always a string).
         Stage-body field translation: the input communication key
         maps to the output interactive key in its canonical slot; an input
         interactive key (pipeline-file stage OR embedded extend-stage) is a
         structural error "interactive key is forbidden in stage body; use
         communication". The output canonical key order keeps interactive
    6. Build `FlowDocument`:
       - prompt = `workflow` prompt when `workflow` is not None, else None
       - root_dir = the `root_dir` parameter passed by the caller (forwarded
         verbatim — None when the caller did not supply one; the compiler
         performs no environment-variable reads to derive it)
       - description = f"[{project_name}] {header.description}" when
         `project_name` is not None, else the header description unchanged
         (OUTPUT-only — PipelineDocument.description stays the faithful mirror,
         like root_dir)
       - memory = the built memory block (only when participation exists),
         sourcing every value from the effective memory configuration of
         step 4.9 (the `WorkflowMemory` value of the workflow document when
         it carries one, else a default-constructed `WorkflowMemory` — its
         field defaults ARE the materialized authoring defaults): path = the
         fixed root ".goga/memory" joined with the authored suffix (the bare
         root when the suffix is None); reflect method — mode "r",
         memory_use False; alignment method — mode the materialized authored
         value ("rw" by default), memory_use False; max_rules and commit
         carried from the effective
         configuration (25 / False when no block was authored); place the
         block between description and stages of the `FlowDocument`. When
         participation does not exist — memory is None (no block, no stage
         keys)
       - repeat = None when the header's repeatable flag is False;
         otherwise ALWAYS a `FlowRepeat`: built from the authored keys of
         the workflow's `WorkflowRepeat` block when `workflow` carries one
         (authored keys only — no materialized defaults), else a
         `FlowRepeat` carrying no key (the scalar form; an absent workflow
         document and a workflow-free compilation both land here). Place
         the directive between description and memory
       - collaboration = a `FlowCollaboration` with mode "assistants" and
         max_depth = the depth of the workflow's `WorkflowDelegation` when
         it carries one, else None; team = one `FlowTeamMember` per catalog
         entry in authored order, then one `FlowTeamMember` per attached
         pipeline declaration in pipeline body stage order (each stage's
         declarations in authored order; loop-expanded copies collapse to
         their base stage's first occurrence; vetoed and stage-skipped
         declarations never join; a name joins exactly once) — id =
         title = the name, profile = goga-<name>, instruction = the
         effective prompt (the extended text) or the empty string,
         skills = the effective list or an empty list; place
         collaboration between memory and team, team between
         collaboration and stages
       - name from the header; stages from the assembled FlowStages
    7. Build `PipelineDocument` from (header, format, ORIGINAL body) — the
       parsed representation carried alongside the FlowDocument for the
       consumer. The body field reflects the ORIGINAL parsed body, NOT the
       workflow-reconstructed one — PipelineDocument is a faithful mirror
       of the input pipeline-file
    8. Call `serialize_flow` on the FlowDocument
    9. Write the resulting text to `flow_path`
    10. Return (PipelineDocument, FlowDocument) as the documents tuple

    Apply `convention` for code style, docstring formatting, and warning
    emission for unknown-stage-name warnings.
    Apply `parse-workflow` for the contract of the
    `WorkflowDocument` value supplied by the consumer.

    Requirements:
    - `pipeline_path` and `flow_path` must be absolute paths
    - `flow_path` parent must already exist (caller's guarantee)
    - Structural errors raise with a readable message; OSError (file
      missing, permission denied) propagates unchanged
    - Idempotent: repeated calls with the same inputs overwrite `flow_path`
    - Output is the canonical afm flow-file format as produced by
      `serialize_flow`
    - When `workflow` is None — no workflow is applied (the reconstruction
      step is skipped entirely, no top-level prompt is emitted, no per-stage
      overrides are injected)
    - Return value is a 2-tuple of `PipelineDocument` then `FlowDocument` —
      input representation first, output representation second
    - `PipelineDocument` body reflects the ORIGINAL parsed body —
      workflow-reconstructed stages live only in `FlowDocument` stages
    - The agent instruction of a `WorkflowStage` is composed into the
      in-container wrapper path /home/goga/bin/AGENT-as-claude.sh inline
      — the cell does NOT call any host-side wrapper resolver
    - `FlowStage` fields are assembled directly from the step body dict
      at step 5 — workflow overrides (command, description) are
      injected INTO the body at step 4.5 before this assembly, so a single
      body dict is the sole source for fields. Pipeline-file fields
      and workflow-injected fields coexist in the same dict without
      merging or collision. The ONE exception is buttons: assembled from
      the effective notes only, never threaded into the body (the
      authoring-buttons prohibition closes that channel)
    - Unknown stage names in workflow.stages (names absent from both the
      original body and the extend-stages) raise a structural error
      "unknown stage name in workflow.stages: <name>";
      a really-existing skipped stage is NOT flagged (validation runs on the
      full original∪extend set before removal)
    - Dangling refs in workflow.extend.<name>.before/.after (refs naming no
      original step and no extend-stage) raise a structural error "unknown
      stage name in workflow.extend.<name>.before/.after: <ref>" (not a verbatim
      pass-through); a ref to a really-existing skipped
      stage is NOT flagged (validation runs before skip removal); cross-references
      between extend-stages resolve (extend names are valid targets)
    - stages.<name>.skip: true for an existing stage → the stage is removed
      from the compiled flow-file; dependents' depends_on are transparently
      reconnected (STAGES via resolve, PHASES positional collapse); chains
      resolved transitively; no dangling references or duplicates
    - skip wins over agent/prompt/loop/skills overrides on the same entry
      (removal runs before the override pass)
    - If the reconstructed body is empty after skip removal (every stage
      skipped), raise a structural error "empty body"
    - An extend-stage name referenced by a stages override is valid (extend
      embedded before validation)
    - Loop-expansion for STAGES format rewrites external depends_on
      references to the LAST expanded id (e.g. a stage that depended on
      "review" gets rewritten to depend on "review-2" when review has
      loop=2)
    - Loop-expansion for PHASES format relies on list position to chain
      expanded copies and to make the next original step depend on the last
      copy — no explicit external rewrite pass is needed
    - When the workflow's extend map is non-empty — extend-stages are
      embedded into the body BEFORE per-stage overrides and loop-expansion;
      their depends_on is derived from before/after (after → the new stage's
      depends_on; before → the new stage is added to the depends_on of each
      named existing stage), without losing the prior dependencies of those
      stages
    - Dangling refs in before/after (names in neither the body nor the
      extend-stages) raise a structural error "unknown stage name in
      workflow.extend.<name>.before/.after: <ref>" — strict validation at
      4.2 (a workflow must not carry a dangling extend ref; symmetric
      with workflow.stages strictness)
    - Cross-references between extend-stages (one extend-stage's
      before/after names another extend-stage) are resolved
    - After loop-expansion, before/after-derived references are rewritten
      with the existing expanded_ids map: both after and before → LAST
      expanded id (any reference to a loop-expanded chain points to its
      completion, since depends_on means "runs after")
    - In PHASES format, extend-stages carry NO explicit depends_on (PhaseStep
      has no such field); instead they are POSITIONALLY inserted into the
      body list (after their after-targets, before their before-targets),
      and depends_on is derived purely by list position in step 5.
      Multi-target before/after reduces to a single positional predecessor
      per step; transitive execution order still respects every target
    - extend-stages compile into ordinary `FlowStage` instances —
      `FlowDocument`, `FlowStage`, and `serialize_flow` are used as-is
    - When `workflow` is None, step 4.1 is skipped entirely (as is the whole
      reconstruction)
    - Consumers must NOT re-invoke `parse_dsl` to obtain the roles — they
      read header roles from `PipelineDocument` returned by this routine
    - Default stage-field injection: a step body with no usable roles
      value (missing key, explicit null, or empty list) yields a
      `FlowStage` carrying a single injected default — agents=["auto"] —
      while a body carrying script assembles NO agents key (afm rejects
      agents combined with script; both the default and a translated
      roles value are suppressed, roles elements still validated).
      supervisor and supervisor_prompt are NOT default-injected (authored
      values pass through). auto is emitted verbatim; goga does not
      resolve it.
      An authored non-empty roles value always wins and disables
      injection. The injection runs uniformly on the non-workflow path
      and on the workflow path (after per-stage overrides and
      loop-expansion)
    - The input stage-body field for the afm agents list is roles; the
      agents key in a stage body (pipeline-file stage or embedded
      extend-stage) is a structural error raised by `compile_flow`. The afm
      interactive field is authored as the communication key in a stage body
      and translated to the output interactive key; an authoring interactive key
      is a structural error raised by `compile_flow`
    - Authored roles values are translated to the output agents values
      via `translate_role`; known aliases (planner/executor/reviewer) map
      to planning/implementation/review, every other value passes through
      verbatim (goga does not validate the open afm agent namespace)
    - The output field name agents, the default ["auto"] injection, the
      canonical key order, and the flow-style serialization are as specified
      (afm contract stable)
    - Override priority (inline extend vs stages block): for a stage that
      originated from an extend-entry, the extend-entry's inline agent /
      loop are DEFAULT override values; an explicit stages-block entry
      for the same name wins PER FIELD (effective value = stages value when
      provided, else inline value, else None/1)
    - Skills merge: when a stages-block entry carries non-None skills,
      the compiler merges them with the step's pipeline-file skills
      (pipeline first, then workflow, deduplicated by value). Extend-entry
      skills are NOT merged (verbatim — a new stage has no pipeline side)
    - Inline agent / loop of an extend-entry do NOT appear in the
      compiled flow-file as stage fields — they are extracted into the
      model by parse_workflow and consumed only as override defaults
    - Default injection is local to `FlowStage` fields assembly — the
      `PipelineDocument` body carried alongside the `FlowDocument` is
      never affected (it stays a faithful mirror of the source
      pipeline-file, with whatever roles value — or absence — the
      source authored)
    - The optional `root_dir` parameter is carried verbatim into the
      `FlowDocument` — the compiler performs no environment-variable
      reads (no Path.cwd(), no AFM_DIR inspection) to derive it. The
      caller (the run_pipeline routine in goga/pipeline) computes the
      value from the in-container project root (Path.cwd() inside the
      goga container resolves to /workspace, mirroring the host-side
      mount decision). When the caller does not supply `root_dir`, the
      compiled flow-file carries no top-level root_dir key.
    - The optional `project_name` parameter prefixes the compiled flow-file
      description: when not None, the `FlowDocument` description becomes
      f"[{project_name}] {header.description}"; when None, the description is
      the header description unchanged. OUTPUT-only — the `PipelineDocument`
      description stays the faithful mirror (like `root_dir`). The compiler
      performs no environment / subprocess reads to derive it; the caller
      (the run_pipeline routine in goga/pipeline) resolves it in-container via
      resolve_project_name.
    - approve effects read triggers from the stage's own body and the
      directive from the workflow (effective approve, one of
      auto/plan/dialog); each value drives a subset of the two effects —
      suppress = omission (not interactive:false) for a communication-effect
      directive (auto/plan) + communication:true; auto_approve only for a
      roles-effect directive (auto/dialog) + planner-in-roles; baseline no-op
      when effective approve is None or neither trigger applies; uniform
      across loop copies
    - script together with prompt and/or skills is a structural error
      "script is mutually exclusive with prompt/skills in stage <name>";
      script together with command is a structural error "script is mutually
      exclusive with command in stage <name>" (and a workflow agent
      instruction on a script body errors at the override pass);
      before_script/after_script are compatible with everything (no error)
    - auto_approve, buttons, script_before, script, and script_after appear
      only when their source directive is present; flow-files without those
      directives carry none of these keys
    - trigger (when present in a stage body or extend body) must be exactly
      on_success or manual; any other value (including on_failure) is a
      structural error "trigger must be one of: on_success, manual"
    - An authoring auto_run key in a stage body (incl. an extend body) is a
      structural error raised by `compile_flow` — use trigger: manual
    - Workflow manual true forces the manual state idempotently; manual false
      cancels the resulting manual state from either source (pipeline-file
      body or extend body) and is a structural error "manual: false on
      non-manual stage <NAME>" on a non-manual stage
    - skip: true on an entry carrying any trigger/manual combination removes
      the stage entirely — the manual instruction never applies to a removed
      stage
    - Loop-expanded copies of a manual stage each assemble auto_run: false
    - auto_run appears in the canonical fields order immediately after
      auto_approve, as a plain bool scalar, ONLY for a manual-effective stage;
      a pipeline without trigger/manual compiles byte-identically
      (no auto_run key anywhere)
    - auto_run and the trigger rewrite are output-side only — PipelineDocument
      body stays the faithful mirror of the source pipeline-file
    - timeout (when present in a stage body or extend body) must be a string and
      requires script in the same body — violations are structural errors naming
      the stage
    - script_timeout is emitted only when timeout (or a direct script_timeout)
      is authored; the value is carried verbatim with no format validation
    - script_timeout occupies the canonical fields slot immediately after
      script_after — a pipeline without timeout compiles byte-identically
      (no script_timeout key anywhere)
    - buttons is authored ONLY via the workflow stages-block notes instruction;
      an authoring buttons key in a stage body (pipeline-file stage or
      extend-stage body) is a structural error raised by `compile_flow`
    - a non-None effective notes assembles the stage's buttons field (the map
      verbatim) in the canonical slot immediately after description; every
      loop-expanded copy carries the same buttons
    - a stage without an effective notes assembles no buttons key — a pipeline
      without notes compiles byte-identically (no buttons key anywhere)
    - notes on an extend-stage name applies (embedded before validation); a
      name absent from both the original body and the extend-stages raises the
      existing structural error "unknown stage name in workflow.stages: <name>"
    - buttons is output-side only — `PipelineDocument` and the source bodies
      are never affected
    - The block is emitted if and only if at least one stage participates — a
      memory configuration without participation is a silent no-op (no block,
      no stage keys, not even an opting-out stage key)
    - All six emission cases hold: no block + no instructions → no block; no
      block + reflect instructions → block; block without instructions → no
      block; alignment + a true memory instruction → block; alignment without
      a true memory instruction → no block; reflect + a reflect instruction →
      block
    - The emitted path is the fixed memory root joined with the authored suffix
    - Participation is counted over the working body, not over the
      workflow.stages map — a skipped stage's instructions do not count
    - Every loop-expanded copy carries the same memory keys as its original
    - The method selector never appears in the output
    - A workflow without memory participation compiles byte-identically —
      no memory block, no stage keys
    - The collaboration checks run as specified at 4.10: an unknown
      assistant reference, the same assistant name twice in one stage's
      list, an attachment on a stage whose translated body carries script,
      and an attachment on a stage whose translated agents value is
      exactly ["planning"] are structural errors naming the stage and the
      assistant; the checks run over the working body after skip removal
      and loop expansion — the attachments of a removed stage never count
    - Every assistant declaration of the effective document resolves
      prompt or skills — the content requirement moved here from the
      parser; override-style entries are legal authoring that must be
      covered by a delivered base
    - A workflow without same-name assistant collisions compiles exactly
      as the same workflow carrying no override entries — the content
      check is the only additional compilation rule
    - The content-check error names the assistant AND its authoring
      site through the existing structural-error channel
    - Every emitted collaboration entry materializes its defaults: mode
      from gate, trigger from the gate/when pair (a gated finish maps to
      pre_completion; always written explicitly — the effective when is
      authored or inherited, never defaulted; the engine's one_shot
      default is never relied upon), title from the authored name,
      instruction from the effective prompt (the empty string when none),
      skills from the effective list (an empty list when none — team
      members only; a stage entry carries NO skills key); every team
      member and every stage attachment carries the generated profile
      binding goga-<name>
    - An emitted inline declaration authoring skills logs a WARNING
      (once per assistant name) naming the stage and the assistant —
      its skills have no engine channel (only catalog and pipeline
      declarations become team members); never a structural error and
      never an output key
    - The top-level collaboration block is constructed on every
      compilation; max_depth rides only when the workflow's delegation
      block authors a depth; the team list is emitted from the catalog in
      authored order, then the pipeline-declared members in pipeline body
      stage order (loop-expanded copies collapse to their base stage's
      first occurrence), and is omitted entirely when both sources are
      empty
    - An authored assistants key in an embedded extend-stage body is a
      structural error raised by `compile_flow` (defensive re-check
      against programmatic contributions; the pipeline-file stage body
      side is replaced by the authoring surface of `parse_dsl`)
    - A stage carrying at least one gate assistant (a gated finish
      attachment) emits the `FlowPreCompletion` budget — max_failures =
      gate-assistant count times the fixed per-assistant limit (10) — in
      the canonical slot after memory_use, uniform across every
      loop-expanded copy; only the pre-completion participants count
      (advisory, checkpoints, message, and ungated-finish attachments
      never do); a stage with no gate assistant emits no key and a
      gate-assistant-free workflow compiles byte-identically; the budget
      is computed-only — an authored pre_completion key in a stage body
      is a structural error naming the compiled origin
    - A collaboration-free workflow compiles byte-identically except the
      always-emitted collaboration mode key
    - Collaboration emission is output-side only — `PipelineDocument` and
      the source bodies stay untouched
    - Pipeline declarations attach with or without a workflow document
      (including workflow-free runs) and on every loop-expanded copy
    - A stage-level skip (workflow or CLI) removes the stage and its
      pipeline declarations together
    - Within one stage's compiled attachment list the pipeline
      declarations come first; the team list orders catalog members
      before pipeline-declared members (loop-expanded copies collapse to
      their base stage's first occurrence)
    - The extension prompt join uses exactly one blank line; the skills
      expansion deduplicates by value preserving first occurrence
    - A compilation without stage-declared assistants and without
      workflow attachments is byte-identical to the same compilation
      without this authoring surface
    - A repeatable pipeline always compiles a repeat key — a workflow
      block emits the authored keys only; no block, no workflow document,
      or a workflow-free compilation emits the scalar form
    - A workflow repeat block on a non-repeatable pipeline is a
      structural error naming the conflict — the cross-reference check
      lives in this cell, not in the workflow parser
    - The compiled repeat occupies the top-level position immediately
      after description and before memory
    - A non-repeatable pipeline compiles byte-identically — no repeat key
      anywhere
    - Gates on a stage compiling to a script stage and on a planning-only
      stage are strict pre-run errors naming the stage; the checks run over
      the working body after skip removal, once on the original
    - An authoring `gates` key and a raw verify key in a stage body
      (pipeline-file stage or embedded extend-stage body) are strict compile
      errors — verify is a compiled-only key; the accidental raw
      passthrough is closed
    - A shell step without an authored timeout materializes "1h"; an AI step
      materializes no timeout default — a goga-side product default, not an
      engine contract
    - The settings ride only on gated stages and only when the top-level
      block authored any key — authored keys only, no materialized settings;
      the settings block without per-stage steps is inert (no verify key
      anywhere, no error)
    - Every loop-expanded copy carries the same gate; the gates of a skipped
      stage drop silently
    - The effective-override merge (step 4.5) passes the stages-block gates
      explicitly — gates is a stages-block-only field (an extend-entry carries
      none, and the extend-seeded virtual override carries None); a merge that
      omitted it would silently drop the gate of a stage carrying BOTH an
      extend-entry and a stages-block entry
    - A gate-free workflow compiles byte-identically — no verify key
      anywhere, no other key affected; the pipeline-file and
      `PipelineDocument` stay untouched
    - An AI step's command composition mirrors the per-stage agent override
      composition — direct, no host-side resolution, no agent-name existence
      checks
    - A malformed timeout value and the name text pass verbatim
      (engine-owned grammar)
    - No cross-field validation of engine interplay constraints; no
      interpretation of gate execution

    Constraints:
    - Do not read AFM_DIR or any environment variable — `flow_path` is
      the only source of the output location
    - Do not create `flow_path` parent — caller's responsibility
    - Do not validate depends_on references (dangling, cycles,
      duplicates) — afm's job
    - Do not validate step content beyond structural presence of
      name/title (already enforced by `parse_dsl`)
    - Do not bypass exceptions from `parse_dsl`, `serialize_flow`, or
      the file read/write calls
    - Do not mutate the (header, format, body) tuple returned by `parse_dsl`
      BEFORE building `PipelineDocument` — `PipelineDocument` must reflect
      the original parsed body. Mutations during workflow reconstruction
      operate on a separate copy or a separately constructed sequence
    - Do not include inline prompt overrides in the `FlowDocument` — they
      are goga-side artifacts, not part of the afm flow-file
    - Do not call any host-side wrapper path resolver — the
      `WorkflowStage` agent value is composed into the wrapper path directly
    - Do not validate the `WorkflowStage` agent value against a known agent set —
      absence of the wrapper file is surfaced by afm at invocation time
    - Do not silently skip unknown workflow.stages names — strict validation
      raises a structural error (a workflow does not silently cover multiple
      pipelines); dangling extend.<name>.before/.after refs are likewise a
      structural error at 4.2 (symmetric strictness, no silent WARNING+skip)
    - Do not validate before/after refs for cycles, self-references, or
      duplicates — existence only is checked at 4.2; ordering/cycle concerns
      remain afm's responsibility
    - Do not leave dangling depends_on after a skip — dependents are
      transparently reconnected to the skipped stage's predecessors
    - Do not leak skip-removed stages into `PipelineDocument` body — it stays
      the original parsed body; reconstruction operates on a copy/sequence
    - Do not leak injected defaults into `PipelineDocument` body — the
      default agents=["auto"] value is an output-side
      artifact of `FlowStage` assembly, never a property of the parsed
      representation. The injection helper must operate on a copy of the
      step body so the original body stays clean
    - Do not let an extend-entry's inline agent / loop reach the
      flow-file as stage fields — they are model fields consumed as override
      defaults, not body keys
    - Do not let an inline extend agent / loop override an explicit
      stages-block value for the same name — the stages block wins per
      field (inline fields are defaults only)
    - Do not merge extend-entry skills with pipeline skills — extend
      skills are verbatim (a new stage has no pipeline side)
    - Do not inject defaults when the source step body carries a non-empty
      roles value — authored roles always wins; the compiler must not
      second-guess the user's choice of roles
    - Do not embed extend-stages after loop-expansion — the order
      4.1 → 4.5 → 4.6 → 4.7 is mandatory (correctness of the symmetric
      before/after → LAST expanded-id rewriting in STAGES, and of PHASES
      positional insertion preceding loop-expansion, depends on it)
    - Do not add a depends_on field to PhaseStep or carry explicit depends_on
      for PHASES extend-stages — PHASES positioning is achieved by list
      insertion only (positional derivation in step 5)
    - Do not validate before/after refs for cycles, self-references, or
      duplicates after the existence check — existence IS validated at 4.2
      (a dangling ref is a structural error); only cycles, self-references, and
      duplicates remain afm's responsibility (as for ordinary depends_on)
    - Do not change the stages block contract — overrides/loop/silent-skip
      of unknown names are unchanged
    - Do not leak embedded extend-stages into `PipelineDocument` body — it
      stays a faithful mirror of the original parsed body (as for the current
      workflow-reconstructed stages)
    - Do not perform any approve action for a stage without a workflow entry
      (effective approve is None) — approve is workflow-driven, never inferred
      from the body
    - Do not emit interactive: true for a communication-effect directive
      (auto/plan) + communication:true — suppress means omission, not
      interactive:false
    - Do not emit auto_approve unless a roles-effect directive (auto/dialog)
      AND planner-in-roles
    - Do not let authoring script keys (before_script / script / after_script)
      pass through to output as unknown keys — they are consumed and
      translated to script_before / script / script_after
    - Do not let the authoring timeout key pass through to output as an unknown
      key — it is consumed by the translation
    - Do not validate the timeout string grammar (Go duration) — the format
      error belongs to afm at runtime
    - Do not leak script_timeout into `PipelineDocument` — output-side
      `FlowStage` field only
    - Canonical key order is fixed at `FlowStage` assembly — the full
      order (interactive, auto_approve, auto_run, command, prompt,
      description, buttons, agents, supervisor, supervisor_prompt, skills,
      script_before, script, script_after, script_timeout, reflect,
      memory_use, pre_completion, assistants, verify, then
      alphabetically-sorted unknown keys)
    - Do not leak auto_approve or script_* into `PipelineDocument` — they
      are output-side `FlowStage` fields only
    - Do not emit auto_run: true — the afm contract treats the key's absence
      as the norm; only a manual-effective trigger assembles auto_run: false
    - Do not let the authoring trigger key pass through to output as an
      unknown key — it is consumed by the translation (as communication is)
    - Do not apply the workflow manual instruction to a skipped stage — skip
      removal runs before the override pass
    - Do not mutate the original parsed body when applying manual — the
      rewrite lives on the working copy; PipelineDocument carries the source
      bodies
    - Do not interpret the buttons — the runtime meaning belongs to afm; the
      compiler only assembles and serializes the field
    - Do not let an authoring buttons key pass through to output as an unknown
      key — it is rejected as a structural error
    - Do not apply notes to a skipped stage — skip removal runs before the
      override pass
    - Do not thread the effective notes into the (working) stage body — unlike
      the command/description overrides, buttons are assembled into `FlowStage`
      fields directly from the effective-notes value; the body channel is closed
      by the authoring-buttons prohibition (an injected key would trip the
      step-5 check)
    - Do not re-validate the authoring vocabulary — the workflow parser already
      rejected non-conforming authoring (per `memory`)
    - Do not interpret the memory keys — the runtime behavior belongs to afm
      (per `afm`)
    - Do not emit memory stage keys when the block is absent
    - Do not leak the memory block or the stage keys into `PipelineDocument` —
      output-side only
    - Do not apply memory instructions to a skipped stage — skip removal runs
      before the assembly
    - Do not author engagement defaults — when is authored on every
      pipeline declaration; the compiled trigger is always written
    - Do not let the workflow extension mutate the parsed pipeline
      document — the merge is output-side only
    - Do not re-validate the workflow authoring vocabulary — the
      workflow parser owns it
    - Do not add a skills key to a stage attachment entry — the engine
      rejects it
    - Do not resolve agent names or compose commands for assistants here —
      the engine configuration write owns that
    - Do not interpret gate or when beyond the mapping — the runtime
      behavior belongs to afm
    - Do not re-validate the authoring vocabulary — the workflow parser
      rejected it before compilation
    - Do not let collaboration reach `PipelineDocument` — the
      collaboration block, the team list, and the stage attachments are
      output-side only
    - Do not enforce content presence at parse time or on references —
      the check runs here, over declarations of the effective document
    - Do not materialize repeat defaults — the engine owns the cycle
      defaults; this cell emits authored values only, plus the scalar form
      when nothing is authored
    - Do not count cycles, decide stop conditions, or prune run
      directories — engine semantics; the run stays a single engine
      invocation
    - Do not validate the timeout duration grammar or the name text — the
      engine reports value-format errors at load/preflight
    - Do not cross-check engine constraints (the failure budget vs the
      patience value, the effective ceiling) — the engine owns these
    - Do not interpret, count, or re-implement gate execution — sequencing,
      fail-fast, re-runs, retry budgets, verdict parsing, and waiver are
      engine behavior
    - Do not write any engine configuration for gates — the flow-file is the
      single delivery channel
    - Do not re-validate the gates authoring vocabulary — the workflow
      parser rejected non-conforming authoring before compilation (per
      `gates`)
    - Do not leak the verify gate into `PipelineDocument` — output-side only

"translate_role(role: str) -> name: str":
  location: compile_flow.py
  annotations: |
    Translate a single role alias from the input DSL vocabulary into the
    canonical afm agent name, which is identical to the corresponding
    default prompt-file stem. This is the single source of truth for the
    role <-> {agent-name, prompt-file-stem} bijection — used by the
    stage-list translation in `compile_flow` (role values -> output
    agents values) and imported by the prompt-materialization consumer
    in goga/pipeline (role override fields -> <stem>.md files).

    `role`: a role value/field-name from the input DSL (planner, executor,
            reviewer, or any other string)
    `name`: the canonical afm agent name == prompt-file stem

    Algorithm:
    1. Map the known aliases: planner -> planning, executor -> implementation,
       reviewer -> review
    2. For every other value (including summary, auto, and any other afm
       agent name) — return the input unchanged (verbatim); goga does not
       interpret the open afm agent namespace

    Requirements:
    - The mapping is exactly {planner: planning, executor: implementation,
      reviewer: review}; no other alias is translated
    - Non-alias values pass through verbatim without validation

    Constraints:
    - Do not validate role values against a known set — the afm agent
      namespace is open (summary, auto, and arbitrary agent names pass
      through)
    - Do not inject auto — auto is a compiler-side default for stages
      with no usable roles value, never a role value authored in the DSL

---

Author: Goga
CreatedAt: 15/07/26
Description: |
  Pure transformer cell that compiles goga DSL pipeline-files
  (phases-list or stages-map) into afm flow-files (flat YAML with
  optional prompt, root_dir, name, description, repeat, memory,
  collaboration, team, and stages). Optionally applies declarative
  workflow instructions to reconstruct the parsed body before
  serialization, and compiles the stage quality gates into the engine
  verify field.
