Usages:
  convention: .goga/usages/conventions.md
  jinja2: .goga/usages/cooks/jinja2.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 parser of project-level workflow-files. It loads a
  workflow-file (the reading step lives in `load_workflow`; `parse_workflow`
  accepts the rendered text), validates its structure (known top-level keys
  prompt / stages / extend /
  memory / profile / build / assistants / delegation / repeat / gates /
  agent / env, field types,
  loop counts, extend-entry positioning, and the inline agent/loop/approve fields of
  an extend-entry), and returns a
  `WorkflowDocument` carrying declarative instructions for the compiler. It performs no I/O beyond the path it receives, performs
  no network or subprocess calls, and has no Imports — it depends only on
  the Python standard library and PyYAML.

  YAML links (anchors, aliases, and "<<" merge keys) resolve through the
  standard YAML loading; hidden declaration keys — top-level str keys
  starting with "." — are anchor sites skipped by the top-level validation
  (their content is already merged at parse time, and they never count as
  workflow content).

  This cell is intentionally DECLARATIVE: it does NOT know about the compiler
  or any compiler-level concept (flow documents, flow stages, the compile
  routine, body embedding, depends_on derivation, command composition,
  loop-expansion, skills merging, stage REMOVAL or depends_on RECONNECTION).
  It returns instructions (per-stage overrides for stages — agent, prompt,
  loop, skills, AND a skip flag that instructs the compiler to DELETE the
  stage; NEW stages for extend — carrying the extracted inline agent/loop);
  the consumer
  (compiler) consumes them. This keeps the import graph one-directional: the
  compiler imports `WorkflowDocument` (and `WorkflowExtendStage`) from this
  cell, never the reverse. The cell extracts inline agent/loop from an
  extend-entry into the model (as it extracts before/after) but does
  not resolve agent names to wrapper paths, does not embed extend-stages,
  does not derive depends_on, does not apply loop-expansion, does not merge
  skills, does not DELETE stages, and does not rewrite depends_on — all of
  that is the compiler's responsibility.

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

  approve is a declarative auto-approval instruction (one of the values
  "auto"/"plan"/"dialog", validated structurally). This cell extracts it into
  `WorkflowStage` / `WorkflowExtendStage`; the compiler
  consumes it to suppress a stage's interactive flag
  and/or emit auto_approve: true (each value drives a subset of these two
  effects). This cell performs NO approval logic — the import graph stays
  one-directional.

  manual is a declarative manual-launch instruction (strictly bool, validated
  structurally, stages-block only). This cell extracts it into `WorkflowStage`;
  the compiler consumes it to force or cancel the manual launch mode of a
  stage. This cell performs NO manual-launch logic — the import graph stays
  one-directional.

  notes is a declarative note-buttons instruction (a map of note name → prompt
  text, str→str, validated structurally, stages-block only). This cell extracts
  it into `WorkflowStage`; the compiler consumes it to emit the per-stage
  buttons field of the flow-file. Interpretation of the buttons belongs to
  afm — this cell performs NO note-button logic, and the import graph stays
  one-directional.

  trigger is a full stage-body field, not a workflow key. In the stages block
  it is an unknown key; in an extend-entry body it passes through verbatim
  inside the extend-stage body and its value (on_success | manual) is
  validated at compilation. manual is forbidden in an extend-entry: the
  launch mode of a new stage is authored in its body via trigger, not via
  workflow instructions.

  memory is a declarative workflow-memory configuration — an optional top-level
  block plus two per-stage participation instructions. This cell validates the
  block and the instructions structurally: key sets, types, value domains, path
  shapes, and the correspondence between the block method and the stage
  instruction. Materialized defaults live in the document model. This cell
  performs NO memory logic — it composes no paths, decides no block emission,
  and resolves no stage participation; the consumer consumes the extracted
  values. The import graph stays one-directional.

  repeat is a declarative run-cycle tuning block — an optional top-level map
  carrying the optional integer keys max_cycles and keep_runs in the engine's
  vocabulary, verbatim. This cell validates the block structurally: the value
  must be a mapping (a scalar value, including a boolean, is a structural
  error), every key must be max_cycles or keep_runs, every value must be an
  integer (a boolean is not an integer) and not negative. The block carries
  authored values only — this cell materializes no defaults; an empty block
  equals absence. A workflow consisting of the block alone is valid. This cell
  performs NO cycle logic — it counts nothing, decides no stop condition, and
  prunes nothing; the consumer compiles the block and the engine owns every
  cycle semantic. The import graph stays one-directional.

  assistants is a declarative collaboration instruction set — a top-level
  assistants catalog, a top-level delegation block, and a per-stage
  assistants attachment map. Both assistants surfaces are name-keyed maps:
  the catalog is keyed by assistant name and every stage attachment is
  keyed by assistant name. This cell validates the authoring surfaces
  structurally — the name-keyed entry maps, field types, the
  assistant-name grammar, the skip-entry form, the value domain of every
  authored when, unknown keys — and extracts them into the document model
  with ABSENCE-PRESERVING attachment fields (an omitted when/gate is
  carried as not-authored; an authored gate: false is a value) and a
  skip-veto carriage. This cell performs NO collaboration logic — it
  resolves no attachment references, classifies no entry origin (which
  entry is a skip veto over a pipeline-declared assistant, which is an
  extension of one, and which is a reference or an inline declaration is
  knowable only where both documents meet, at compilation), derives no
  profile ids, maps no gate or engagement values, and emits no team or
  stage-assistant entries; the consumers consume the extracted values.
  The import graph stays one-directional.

  One entry model serves every authoring form: a catalog entry (the
  declaration fields under the assistant's name), a full inline
  declaration on a stage (the catalog field set plus gate/when), a
  reference (a value carrying only gate/when), an extension (any entry
  addressing a name declared by the pipeline-file stage — it may omit
  when and author delivery/content fields), and a skip veto ({skip:
  true} alone). Every entry carries exactly one meaningful instruction:
  the veto alone, or at least one extension, reference, or declaration
  field. Whether a when is required is decided by the name's origin at
  compilation, not here. Assistant names match [A-Za-z0-9._-]; the name
  "assistant" is rejected. Uniqueness of a name across the effective
  namespace (the catalog, every inline declaration, and the pipeline
  declarations of the compiled pipeline-file) is a compilation check;
  this cell enforces the grammar and the per-map key uniqueness only.

  A full declaration — catalog or inline — MAY carry no prompt and no
  skills: an override-style entry that configures delivery fields
  (agent, env, delegate) and inherits its content from a tool-delivered
  entry of the same name at the overlay merge; the effective-content
  requirement (prompt or skills) is enforced at COMPILATION, not here.

  Assistant names are globally unique across the workflow-file: the
  catalog and every inline declaration form one namespace, and a repeated
  declaration name is a structural error. Every authored name matches
  [A-Za-z0-9._-]; the name "assistant" is rejected — its dashboard handle
  is reserved by the engine.

  The model preserves field presence for the override fields: an
  explicitly authored empty skills list or env map is carried as an
  explicit empty value (an override that clears), never normalized to
  absence; delegate carries None when not authored and the authored
  boolean otherwise. Per-stage env of WorkflowStage keeps its own
  empty-equals-absence rule — the presence discipline applies to the
  assistant fields only.

  This cell additionally owns the contributor-profile zone of the workflow
  path: profile resolution (project-then-home lookup, project wins on the
  same name), strict profile-name validation, activation precedence
  resolution, and whole-file Jinja rendering of workflow-files before
  parsing. The zone stays pure: no environment reads, no subprocess, no
  network; file I/O is limited to the paths received as parameters.
  Rendering is a step before parsing — the rendered text passes the
  standard structural validation unchanged; rendering never bypasses
  validation. The template context is the entire content of the single
  active profile; with no activation the context is empty.

  The zone renders two surfaces with one fixed environment per `jinja2`:
  whole workflow-files before parsing, and the strings of committed
  workflow contributions — the field-level render the pipeline amendment
  applies to a tool's document at its commit. The field-level render
  touches strings only: structure, field presence, and non-string values
  are preserved unchanged.

  Use `jinja2` for the rendering engine contract: the fixed environment
  flags, the missing-key semantics, and the strict syntax-error surfacing
  with location.

  gates is a declarative quality-gate instruction set — an optional top-level
  settings block (patience, max_iterations, fresh_correction) plus an optional
  per-stage check-step list in the stages block. This cell validates both
  surfaces structurally (key sets, types, value bounds, step forms, the
  script/agent exclusivity, the required step name, the prompt-to-AI-step
  binding, the script list-of-lines form, the step env string-map form) and
  extracts them into the
  document model. The top-level block carries authored values only — an empty
  block equals absence, and a workflow consisting of the block alone is valid.
  A per-stage value is a list of check steps — an empty list equals absence;
  every step carries a required name and exactly one of script (a shell check)
  and agent (an AI review), and prompt belongs to an AI review step only. A
  script payload is a non-empty string or a non-empty list of non-empty
  strings — a list is the script's lines, joined with newlines into ONE
  multi-line string on the model (shell-identical to authoring the same text
  as a block scalar; the model field stays str). An agent alias is a single
  string — the list form is a structural error. A
  step may additionally carry env — a str→str map valid on BOTH step kinds
  (an empty map equals absence); the pipeline run coordination's gate wrapper
  generation consumes it (the stage-env delivery precedent), NOT the compiler.
  A gates key in an extend-entry is a structural
  error — the checks of a new stage are authored in the stages block by the
  new stage's name. Value grammar is not validated here: timeout durations,
  name text, and env key shapes pass verbatim, and their format errors are
  surfaced downstream.
  This cell performs NO gate logic — it composes no commands, materializes no
  settings defaults, and decides no emission form; the consumers consume the
  extracted values. The import graph stays one-directional.

  agent and env are declarative workflow-global run settings — the two
  top-level keys every consumer resolves as the global layer ahead of the
  project configuration's own globals: agent (a single string naming the
  run's global agent) and env (a str→str map of the run's global
  environment layer). This cell validates both keys structurally and
  extracts them into the document model; it resolves no wrappers, merges
  no layers, and launches nothing — the consumers own every resolution
  law. agent follows the empty-to-absence normalization of a scalar: a
  non-str value is a structural error, an empty or whitespace-only value
  normalizes to absence. env follows the string-map law: a non-mapping
  value, a non-str key, or a non-str value is a structural error; an
  empty map equals absence — the assistant explicit-clear discipline does
  not apply to this key. Both keys count as content for the empty-workflow
  rule: a workflow consisting of agent alone (or env alone) is valid;
  profile never counts. Both keys ride the whole-file contributor-profile
  rendering like the rest of the document, and the profile peek reads the
  raw text — a value materializing only through rendering activates
  nothing.

---

"WorkflowStage(agent: str | None = None, env: dict[str, str] | None = None, prompt: str | None = None, loop: int | None = None, skills: list[str] | None = None, skip: bool = False, approve: str | None = None, manual: bool | None = None, notes: dict[str, str] | None = None, reflect: WorkflowReflect | None = None, memory: bool | None = None, assistants: dict[str, WorkflowAssistant] | None = None, gates: list[WorkflowGateStep] | None = None)":
  location: workflow_stage.py
  annotations: |
    Data model of a single per-stage override instruction in a workflow-file —
    which agent, which environment, which prompt, how many loop iterations,
    which skills to merge,
    whether to SKIP (delete) the stage, an optional auto-approval directive,
    an optional manual-launch instruction, an optional note-buttons
    instruction, and optional memory-participation instructions. Constructed
    by `parse_workflow`
    from one entry of the workflow-file stages map; carried verbatim inside
    `WorkflowDocument`.

    `agent`: agent name consumed by the compiler to compose the per-stage
             command wrapper path, or None when not specified
    `env`: per-stage environment instruction (string map, literal and/or
           rendered). Validated by `parse_workflow` (dict of str→str; an
           empty map equals absence — None). Declarative — extracted here,
           consumed by the pipeline run coordination's wrapper generation,
           NOT the compiler. None when not specified
    `prompt`: per-stage prompt text consumed by the compiler as the stage
              description field, or None when not specified
    `loop`: positive integer (>= 1) instructing the compiler to expand the
            stage into N copies, or None when not specified
    `skills`: list of skill names the compiler merges with the stage's
              pipeline-file skills, or None when not specified
    `skip`: bool flag instructing the compiler to DELETE the stage. False by
            default (key absent / skip: false). True (skip: true) removes the
            stage and transparently reconnects dependents' depends_on
    `approve`: optional auto-approval directive consumed by the compiler.
               Accepted values are "auto", "plan", and "dialog" (validated by
               `parse_workflow`; any other value is a structural error). The
               compiler applies two INDEPENDENT effects, and each value drives
               a subset of them: "auto" drives BOTH (suppress the stage's
               interactive flag when the stage body has communication: true, AND
               emit auto_approve: true when the stage body's roles contain
               planner); "plan" drives ONLY the interactive-suppression effect;
               "dialog" drives ONLY the auto_approve effect. This cell does NOT
               act on `approve` — it is declarative; the compiler applies it.
               None when not specified.
    `manual`: optional manual-launch instruction consumed by the compiler.
              None means the instruction is not given — the stage's own body
              decides the launch mode; True forces the manual launch mode;
              False explicitly cancels the resulting manual state of the stage
              regardless of which side authored it. Accepted file values are
              strictly bool (validated by `parse_workflow`; any other value is
              a structural error). This cell does NOT act on `manual` — the
              compiler applies the force / cancel logic. None when not
              specified.
    `notes`: optional map of note name → prompt text consumed by the compiler
             to emit the per-stage buttons field of the flow-file. None when
             not specified; an empty map equals absence — `parse_workflow`
             normalizes it to None, so the model carries either None or a
             non-empty map. This cell does NOT act on `notes` — it is
             declarative; the compiler emits the buttons.
    `reflect`: optional memory-reflection instruction. Declarative — extracted
             here, consumed by the compiler to emit the stage's reflect field.
             None when not specified.
    `memory`: optional memory-participation instruction. Declarative —
             extracted here, consumed by the compiler to emit the stage's
             memory participation. None when not specified; an explicit false
             equals absence (normalized to None by `parse_workflow` — no
             separate semantics for false).
    `assistants`: the stage's assistant entries — a map of
                  WorkflowAssistant keyed by assistant name, in authored
                  order. None when not specified (an empty map equals
                  absence). Each entry is a reference, a full inline
                  declaration, an extension of a name declared by the
                  pipeline-file stage, or a skip veto; the origin decides
                  at compilation. Declarative — extracted here, consumed
                  by the compiler to emit the stage's assistants entries
    `gates`: the stage's check steps — a list of `WorkflowGateStep` in
             authored order, or None when not specified (an empty list
             equals absence — normalized by `parse_workflow`). Declarative —
             extracted here, consumed by the compiler to emit the stage's
             completion gate

    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 agent/env/prompt/loop/skills/approve/manual/notes/reflect/memory
      default to None; assistants defaults to None; gates defaults to None;
      an empty list equals absence — normalized by `parse_workflow`; `skip`
      defaults to False (NOT None); `manual` defaults
      to None (NOT False) — an absent key and an explicit manual: false are
      DIFFERENT instructions and must stay distinguishable to the compiler
    - Field order is fixed: agent, env, prompt, loop, skills, skip, approve,
      manual, notes, reflect, memory, assistants, gates — matches the
      canonical order of the per-stage keys in the workflow-file
    - An explicit memory: false is normalized to None at parse time
    - `approve` accepts ONLY "auto"/"plan"/"dialog"; `manual` accepts ONLY
      True/False — any other value is rejected by `parse_workflow` as a
      structural error before this dataclass is built

    Constraints:
    - Do not validate loop >= 1 / skills list[str] / skip bool / manual bool /
      notes dict[str, str] / env dict[str, str] here — `parse_workflow`
      enforces these during parsing
    - Do not resolve agent to a wrapper path, merge skills, DELETE the stage,
      or RECONNECT dependents here — all the compiler's job
    - Do not act on `env` here — env never reaches the serialized flow-file
      as a stage field and the compiler does not act on it; the pipeline run
      coordination's wrapper generation consumes it
    - Do not act on `approve` or `manual` here — they are declarative; the
      compiler performs the approval and manual-launch logic when applying
      the workflow
    - Do not act on `notes` here — it is declarative; the compiler emits the
      buttons when applying the workflow
    - Do not act on `reflect` or `memory` here — they are declarative; the
      compiler performs the emission when applying the workflow
    - Do not act on `gates` here — it is declarative; the compiler emits the
      completion gate when applying the workflow
  properties:
    "agent -> str | None": |
      Agent name consumed by the compiler to compose the wrapper path, or None.
    "env -> dict[str, str] | None": |
      Per-stage environment instruction (string map, literal and/or rendered).
      Declarative — extracted here, consumed by the pipeline run
      coordination's wrapper generation, NOT the compiler. None when not
      specified (an empty map equals absence).
    "prompt -> str | None": |
      Per-stage prompt text consumed by the compiler as the stage description.
    "loop -> int | None": |
      Positive iteration count (>= 1) for loop-expansion, or None.
    "skills -> list[str] | None": |
      Skill names merged with the stage's pipeline-file skills, or None.
    "skip -> bool": |
      Flag instructing the compiler to delete the stage and reconnect dependents.
    "approve -> str | None": |
      Optional auto-approval directive (one of "auto"/"plan"/"dialog").
      Declarative — extracted here, consumed by the compiler to suppress
      interactive / emit auto_approve (each value drives a subset of the two
      effects). None when not specified.
    "manual -> bool | None": |
      Optional manual-launch instruction (None = not given, True = force,
      False = cancel). Declarative — extracted here, consumed by the compiler
      to force or cancel the stage's manual launch mode. None when not
      specified.
    "notes -> dict[str, str] | None": |
      Optional note-buttons instruction (map of note name → prompt text).
      Declarative — extracted here, consumed by the compiler to emit the stage's
      buttons field. None when not specified (an empty map equals absence).
    "reflect -> WorkflowReflect | None": |
      Optional memory-reflection instruction (file + access mode). Declarative
      — extracted here, consumed by the compiler to emit the stage's reflect
      field. None when not specified.
    "memory -> bool | None": |
      Optional memory-participation instruction. Declarative — extracted
      here, consumed by the compiler to emit the stage's memory participation.
      None when not specified; an explicit false equals absence.
    "assistants -> dict[str, WorkflowAssistant] | None": |
      The stage's assistant entries keyed by assistant name, in authored
      order. None when not specified (an empty map equals absence). Each
      entry is a reference, a full inline declaration, an extension of a
      name declared by the pipeline-file stage, or a skip veto; the
      origin decides at compilation.
    "gates -> list[WorkflowGateStep] | None": |
      The stage's check steps in authored order, or None when not specified
      (an empty list equals absence).

"WorkflowReflect(file: str, mode: str = \"rw\")":
  location: workflow_reflect.py
  annotations: |
    Data model of a per-stage memory-reflection instruction — which memory
    file the stage reflects into and with which access mode. Constructed by
    `parse_workflow`; carried inside `WorkflowStage`.

    `file`: the reflection file — a path shape inside the memory root;
            carried verbatim
    `mode`: the access mode — one of "r", "w", "rw"; materialized to "rw"
            when the authoring entry omits 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`)
    - `file` is required (no default); `mode` defaults to "rw" — a
      materialized value, not an omission
    - Field order is fixed: file, mode

    Constraints:
    - Do not validate the path shape or the mode domain here —
      `parse_workflow` enforces them during parsing
    - Do not resolve `file` against any memory root here — the consumer
      composes paths
  properties:
    "file -> str": |
      The reflection file — a path shape inside the memory root; carried
      verbatim.
    "mode -> str": |
      The access mode — one of "r", "w", "rw"; materialized to "rw" when the
      authoring entry omits it.

"WorkflowExtendStage(before: list[str] | None = None, after: list[str] | None = None, agent: str | None = None, loop: int | None = None, approve: str | None = None, body: dict[str, Any])":
  location: workflow_extend_stage.py
  annotations: |
    Data model of a single extend-entry — a new stage to be embedded into a
    target pipeline, carrying positioning instructions and the verbatim stage
    body. Constructed by `parse_workflow`; carried verbatim inside
    `WorkflowDocument`. The compiler embeds the stage and derives depends_on —
    this cell performs NO embedding and NO depends_on derivation.

    `before`: list of stage names the new stage precedes, or None
    `after`: list of stage names the new stage follows, or None
    `agent`: agent name composed into the new stage's wrapper path (default
             override; a stages-block entry for the same name wins), or None
    `loop`: positive integer (>= 1) for loop-expansion (default override), or None
    `approve`: optional auto-approval directive (one of "auto"/"plan"/"dialog",
               validated by `parse_workflow`), EXTRACTED from the extend-entry
               into the model — exactly like agent/loop. Acts as a DEFAULT
               override; the compiler consumes it against the extend-stage body
               (each value drives a subset of the two effects). None when not
               specified.
    `body`: verbatim copy of the stage body EXCLUDING before, after, agent,
            loop, approve, and depends_on. Open-ended — this cell does not
            know the stage field schema. trigger is a legal full stage-body
            field: it stays in body verbatim, and its value is validated at
            compilation. The entry carries no manual instruction — the launch
            mode of the new stage is authored in its body via trigger.

    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`)
    - `before`/`after` default to None; `agent`/`loop`/`approve` default to None;
      `body` is required (no default)
    - Field order is fixed: before, after, agent, loop, approve, body
    - `approve` is EXTRACTED from the extend-entry (excluded from body) — like
      agent/loop; it never leaks into body as a stray stage field
    - `approve` accepts ONLY "auto"/"plan"/"dialog"
    - No manual field on this model — manual is rejected in an extend-entry
      before the model is built; the extend-stage body owns the launch mode

    Constraints:
    - Do not embed the stage or derive depends_on here — the compiler does both
    - Do not act on `approve` here — declarative; the compiler applies it
  properties:
    "before -> list[str] | None": |
      Stage names the new stage precedes, or None.
    "after -> list[str] | None": |
      Stage names the new stage follows, or None.
    "agent -> str | None": |
      Agent name composed into the new stage's wrapper path (default override).
    "loop -> int | None": |
      Positive iteration count for loop-expansion (default override), or None.
    "approve -> str | None": |
      Optional auto-approval directive (one of "auto"/"plan"/"dialog"), extracted
      inline from the extend-entry. Default override; the compiler consumes it
      (each value drives a subset of the two effects). None when absent.
    "body -> dict[str, Any]": |
      Verbatim stage body excluding before, after, agent, loop, approve, and
      depends_on. Open-ended.

"WorkflowMemory(method: str = \"reflect\", path: str | None = None, max_rules: int = 25, commit: bool = False, mode: str | None = None)":
  location: workflow_memory.py
  annotations: |
    Data model of the workflow-memory configuration block — the authoring
    form of the flow-level memory settings. Constructed by `parse_workflow`
    with materialized defaults; carried inside `WorkflowDocument`.

    `method`: the authoring method — "reflect" or "alignment". A goga-side
              selector of the instruction vocabulary; never part of any
              output.
    `path`: authored suffix inside the fixed memory root; None means no
            suffix.
    `max_rules`: the maximum number of memory rules; always >= 1.
    `commit`: whether memory changes are committed.
    `mode`: the project-memory access mode — one of "r", "w", "rw"; exists
            only for the "alignment" method (None for "reflect").

    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`)
    - Defaults are materialized values, not omissions: method "reflect",
      max_rules 25, commit False; mode "rw" for the "alignment" method, None
      for "reflect"
    - path carries the authored suffix only — the fixed root prefix is not
      part of this model
    - Field order is fixed: method, path, max_rules, commit, mode

    Constraints:
    - Do not validate keys, types, or value domains here — `parse_workflow`
      enforces them during parsing
    - Do not compose the memory root prefix here — the consumer composes the
      final path
    - Do not act on `method` here — it is declarative; the consumer selects
      the emission form
  properties:
    "method -> str": |
      The authoring method — "reflect" or "alignment". A goga-side selector
      of the instruction vocabulary; never part of any output.
    "path -> str | None": |
      Authored suffix inside the fixed memory root; None means no suffix.
    "max_rules -> int": |
      The maximum number of memory rules; always >= 1.
    "commit -> bool": |
      Whether memory changes are committed.
    "mode -> str | None": |
      The project-memory access mode — one of "r", "w", "rw"; exists only for
      the "alignment" method, None for "reflect".

"WorkflowAssistant(name: str, prompt: str | None = None, skills: list[str] | None = None, agent: str | None = None, delegate: bool | None = None, env: dict[str, str] | None = None, gate: bool | None = None, when: str | None = None, skip: bool | None = None)":
  location: workflow_assistant.py
  annotations: |
    Data model of one assistant authoring entry — a named helper
    declaration and, on a stage entry, its attachment, extension, or
    veto parameters. Constructed by parse_workflow from a catalog entry
    or a stage attachment; carried inside WorkflowDocument (the
    catalog) and WorkflowStage (the stage entries).

    `name`: the assistant name — the map key of the entry on every
            authoring surface; matches [A-Za-z0-9._-]; "assistant" is
            rejected
    `prompt`: the assistant's instruction text, or None when not
              authored
    `skills`: list of the assistant's own skill names, or None when not
              authored — an authored empty list is carried as an
              explicit override that clears
    `agent`: agent name the delivery resolves into the assistant's
             launch command, or None — None resolves to the effective
             global pipeline agent
    `delegate`: whether the assistant may create child tasks — None when
                not authored (an inheritable value at the overlay
                merge), False when explicitly authored off, True when
                authored on
    `env`: the assistant's environment instruction (string map); None
           when not authored — an authored empty map is an explicit
           override that clears
    `gate`: whether the assistant's verdict must pass before the stage
            may finish — None when not authored (an entry addressing a
            pipeline-declared name inherits its gate; a reference or an
            inline declaration materializes false at emission), True or
            False when authored
    `when`: when the assistant engages — one of start, checkpoints,
            finish, message, or None when not authored (an entry
            addressing a pipeline-declared name inherits its engagement;
            a reference or an inline declaration requires one at
            compilation)
    `skip`: the veto carriage — None on every non-skip entry, True on a
            {skip: true} entry addressing a pipeline-declared name of
            that stage

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

    Requirements:
    - Use @dataclass(kw_only=True) (per `convention`)
    - gate/when/skip default to None — absence stays distinguishable
      from every authored value; field order is fixed: name, prompt,
      skills, agent, delegate, env, gate, when, skip

    Constraints:
    - Do not validate the name grammar, types, or value domains here —
      parse_workflow enforces them during parsing
    - Do not classify the entry origin, resolve references, derive
      profile ids, or map gate/when onto engine values here — the
      consumers perform both
  properties:
    "name -> str": |
      The assistant name — the map key on every authoring surface.
    "prompt -> str | None": |
      The assistant's instruction text, or None when not authored.
    "skills -> list[str] | None": |
      The assistant's own skill names, or None when not authored; an
      authored empty list is an explicit override that clears.
    "agent -> str | None": |
      Agent name resolved at delivery into the launch command; None
      resolves to the effective global pipeline agent.
    "delegate -> bool | None": |
      Whether the assistant may create child tasks — None inheritable
      at the overlay merge, explicit False an authored opt-out.
    "env -> dict[str, str] | None": |
      The assistant's environment instruction (string map); None when
      not authored — an authored empty map is an explicit override that
      clears.
    "gate -> bool | None": |
      Whether the assistant's verdict holds stage completion — None
      when not authored (an entry addressing a pipeline-declared name
      inherits its gate; a reference or an inline declaration
      materializes false at emission), authored True/False otherwise.
    "when -> str | None": |
      When the assistant engages — start, checkpoints, finish, or
      message, or None when not authored (an entry addressing a
      pipeline-declared name inherits its engagement; a reference or an
      inline declaration requires one at compilation).
    "skip -> bool | None": |
      The veto carriage — None on every non-skip entry, True on a
      {skip: true} entry addressing a pipeline-declared name of that
      stage.

"WorkflowDelegation(depth: int | None = None, max_tasks: int = 50)":
  location: workflow_delegation.py
  annotations: |
    Data model of the workflow delegation block — the bounds of helper
    delegation for the run. Constructed by `parse_workflow` from the
    optional top-level block with materialized defaults; carried inside
    `WorkflowDocument`.

    `depth`: the maximum delegation depth — an integer >= 0, or None when
             not authored (no depth bound is delivered)
    `max_tasks`: the whole-run helper task budget; materialized 50
                 whenever the block is authored, the authored value
                 otherwise

    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`)
    - `depth` defaults to None; `max_tasks` defaults to 50 — a
      materialized value, not an omission
    - Field order is fixed: depth, max_tasks

    Constraints:
    - Do not validate types or bounds here — `parse_workflow` enforces
      them during parsing
    - Do not decide which channel each bound travels — the consumers
      deliver depth into the flow and max_tasks into the engine
      configuration
  properties:
    "depth -> int | None": |
      The maximum delegation depth (>= 0), or None when not authored.
    "max_tasks -> int": |
      The whole-run helper task budget; 50 whenever the block is authored
      without a value.

"WorkflowRepeat(max_cycles: int | None = None, keep_runs: int | None = None)":
  location: workflow_repeat.py
  annotations: |
    Data model of the workflow run-cycle tuning block — the authored bounds
    of a repeating run. Constructed by `parse_workflow` from the optional
    top-level block; carried inside `WorkflowDocument`.

    `max_cycles`: the maximum number of complete run cycles, or None when
                  not authored
    `keep_runs`: the number of recent cycle run-directories to retain, or
                 None when not 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`)
    - Both fields default to None — the model carries authored values only
      and materializes no defaults; an authored zero is a value, not an
      omission, and stays distinguishable from None
    - Field order is fixed: max_cycles, keep_runs

    Constraints:
    - Do not validate types or bounds here — `parse_workflow` enforces them
      during parsing
    - Do not interpret the bounds — cycle semantics belong to the consumer
      and the engine
  properties:
    "max_cycles -> int | None": |
      The maximum number of complete run cycles, or None when not authored.
    "keep_runs -> int | None": |
      The number of recent cycle run-directories to retain, or None when
      not authored.

"WorkflowGates(patience: int | None = None, max_iterations: int | None = None, fresh_correction: bool | None = None)":
  location: workflow_gates.py
  annotations: |
    Data model of the workflow quality-gate settings — the authored retry
    tuning for stage completion checks. Constructed by `parse_workflow`;
    carried inside `WorkflowDocument`.

    `patience`: the authored tolerance for an unchanged correction
                stalemate, or None when not authored
    `max_iterations`: the authored bound of failed correction attempts, or
                      None when not authored
    `fresh_correction`: whether a correction session starts fresh, or None
                        when not authored

    Requirements:
    - Use @dataclass(kw_only=True) (per `convention`)
    - All fields default to None — the model carries authored values only
      and materializes no defaults; an authored zero is a value, not an
      omission, and stays distinguishable from None
    - Field order is fixed: patience, max_iterations, fresh_correction

    Constraints:
    - Do not validate types or bounds here — `parse_workflow` enforces
      them during parsing
    - Do not translate the field names into the engine vocabulary here —
      the consumer performs the translation
    - Do not interpret the settings — retry semantics belong to the
      consumer and the engine
  properties:
    "patience -> int | None": |
      The authored tolerance for an unchanged correction stalemate, or
      None when not authored.
    "max_iterations -> int | None": |
      The authored bound of failed correction attempts, or None when not
      authored.
    "fresh_correction -> bool | None": |
      Whether a correction session starts fresh; None when not authored.

"WorkflowGateStep(name: str, script: str | None = None, agent: str | None = None, timeout: str | None = None, prompt: str | None = None, env: dict[str, str] | None = None)":
  location: workflow_gate_step.py
  annotations: |
    Data model of one authored check step — a single stage-completion
    check, shell or AI-review. Constructed by `parse_workflow`; carried
    inside `WorkflowStage`.

    `name`: the check's dashboard label — required on every step
    `script`: the shell command of a shell check step, or None — a list-form
              authored payload arrives already joined with newlines into ONE
              multi-line string (the model carries no list form)
    `agent`: the agent name of an AI-review step, or None — the same name
             vocabulary as the per-stage agent override; a single string,
             never a list
    `timeout`: the authored timeout value, carried verbatim, or None when
               not authored
    `prompt`: the review instruction of an AI step, carried verbatim, or
              None when not authored
    `env`: the step's environment instruction (string map, literal and/or
           rendered) — valid on BOTH step kinds, or None when not
           authored (an empty map equals absence). Declarative — extracted
           here, consumed by the pipeline run coordination's gate wrapper
           generation (the stage-env delivery precedent), NOT the compiler

    Requirements:
    - Use @dataclass(kw_only=True) (per `convention`)
    - `name` is required (no default); every other field defaults to None
    - Exactly one of `script`/`agent` is not None on every constructed
      instance — `parse_workflow` enforces the exclusivity before
      construction
    - Field order is fixed: name, script, agent, timeout, prompt, env

    Constraints:
    - Do not validate the step form here — `parse_workflow` enforces it
      during parsing
    - Do not compose `agent` into a launch command here — the consumer
      composes it
    - Do not act on `env` here — its delivery is the pipeline run
      coordination's responsibility
    - Do not validate the `timeout` duration grammar, the `name` text, or
      the `env` key shapes here — values pass verbatim; value-format
      errors belong to the consumers and the engine
  properties:
    "name -> str": |
      The check's dashboard label; required on every authored step.
    "script -> str | None": |
      The shell command of a shell check step, or None. A list-form authored
      payload is joined with newlines into one multi-line string at parse.
    "agent -> str | None": |
      The agent name of an AI-review step, or None — a single string.
    "timeout -> str | None": |
      The authored timeout value, carried verbatim, or None when not
      authored.
    "prompt -> str | None": |
      The review instruction of an AI step, carried verbatim, or None
      when not authored.
    "env -> dict[str, str] | None": |
      The step's environment instruction (string map), valid on both step
      kinds; None when not authored (an empty map equals absence).

"WorkflowDocument(prompt: str | None = None, stages: dict[str, WorkflowStage] | None = None, extend: dict[str, WorkflowExtendStage] | None = None, memory: WorkflowMemory | None = None, profile: str | None = None, build: WorkflowBuild | None = None, assistants: dict[str, WorkflowAssistant] | None = None, delegation: WorkflowDelegation | None = None, repeat: WorkflowRepeat | None = None, gates: WorkflowGates | None = None, agent: str | None = None, env: dict[str, str] | None = None)":
  location: workflow_document.py
  annotations: |
    Aggregated workflow-file document — the parsed representation of a
    workflow-file as a single value, combining an optional top-level prompt,
    a map of per-stage override instructions, and an optional workflow-memory
    configuration. Built by `parse_workflow`
    and consumed by the compiler via its workflow parameter.

    `prompt`: top-level prompt text that the compiler emits as the first
              top-level key of the compiled flow-file, or None when the
              workflow-file has no top-level prompt directive
    `stages`: map of per-stage override instructions keyed by stage name;
              an entry's key MUST match the name/id of a stage in the
              target pipeline-file. Stages in `stages` that do not match any
              pipeline stage OR any extend-stage are a STRUCTURAL ERROR at
              compile time — "unknown stage name in workflow.stages: <name>"
              (a workflow-file does not silently cover multiple pipelines;
              strict validation runs on the full original∪extend name set
              before skip removal, so a really-existing skipped stage is NOT
              flagged). An
              empty map (default) means the workflow provides only a
              top-level prompt and no per-stage overrides.
    `extend`: map of new-stage extend-instructions keyed by stage name; an
              entry is embedded into the target pipeline by the compiler and
              positioned via before/after. A before/after ref in `extend`
              naming no pipeline stage and no extend-stage is a STRUCTURAL
              ERROR at compile time — "unknown stage name in
              workflow.extend.<name>.before/.after: <ref>".
              An empty map (default) means the workflow provides no new stages.
    `memory`: workflow-memory configuration extracted from the optional
              top-level memory block, or None when the workflow-file carries
              no block. A workflow consisting of the block alone is valid.
    `profile`: the parsed counterpart of the peeked workflow default —
               activation reads the raw text via the peek, not this field;
               None when the workflow-file carries no top-level profile key
    `build`: the six-field build block model (`WorkflowBuild`) consumed by
             the build path, or None when the workflow-file carries no
             block. A workflow consisting of the block alone is valid
    `assistants`: the assistant catalog — an insertion-ordered map of
                  `WorkflowAssistant` keyed by name (the authored order is
                  the delivery order of the run agents); an empty map
                  (default) means no catalog
    `delegation`: the delegation block, or None when the workflow-file
                  carries no block. A workflow consisting of the block
                  alone is valid
    `repeat`: the run-cycle tuning block, or None when the workflow-file
              carries no block or authors an empty block. A workflow
              consisting of the block alone is valid
    `gates`: the quality-gate settings block, or None when the workflow-file
             carries no block or authors an empty block. A workflow
             consisting of the block alone is valid
    `agent`: the workflow-global agent name — the global run-settings
             layer every consumer resolves ahead of the configuration's
             pipeline agent, or None when the key is absent or empty
    `env`: the workflow-global environment layer (string map, literal
           and/or rendered), or None when the key is absent (an empty
           map equals absence)

    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
    - `stages` defaults to an empty dict via field(default_factory=dict)
      in the implementation; the signature default None is a DSL
      representation, the actual default factory is applied at construction
    - `extend` defaults to an empty dict via field(default_factory=dict)
      in the implementation; the signature default None is a DSL
      representation, the actual default factory is applied at construction
    - `assistants` defaults to an empty dict via field(default_factory=dict)
      in the implementation; the signature default None is a DSL
      representation, the actual default factory is applied at construction
    - memory defaults to None; profile defaults to None; build defaults to
      None; delegation defaults to None; repeat defaults to None; gates
      defaults to None; agent defaults to None; env defaults to None (an
      empty map equals absence — normalized by `parse_workflow`); field
      order is fixed: prompt, stages, extend, memory, profile, build,
      assistants, delegation, repeat, gates, agent, env — the two global
      run-settings fields close the canonical order
    - The empty-workflow rule counts the new keys: a workflow is empty
      only when prompt is None AND stages is empty AND extend is empty
      AND memory is None AND build is None AND assistants is empty AND
      delegation is None AND repeat is None AND gates is None AND agent
      is None AND env is None — the global keys count as content;
      `profile` never counts (activation is not content: a profile-only
      workflow is still empty)
    - A workflow-file with none of a top-level `prompt`, any stage
      entries, any extend entries, the memory block, the build block, the
      assistants block, the delegation block, the repeat block, the gates
      block, the agent key, or the env block is rejected by
      `parse_workflow` with a structural error before this dataclass is
      built — at least one must be present

    Constraints:
    - Do not validate stage-name keys against any pipeline — the compiler
      performs that match during apply and raises a structural error on
      names absent from both the pipeline and the extend-stages (strict
      validation; not a warning+skip). This cell does NOT validate
      names itself — it stays declarative
    - Do not mutate `stages` after construction — consumers treat the
      document as read-only
  properties:
    "prompt -> str | None": |
      Top-level prompt text emitted by the compiler as the first top-level key
      of the compiled flow-file, or None when the workflow-file has no
      top-level prompt directive.
    "stages -> dict[str, WorkflowStage]": |
      Map of per-stage override instructions keyed by stage name. Empty map
      when the workflow-file has no stages section.
    "extend -> dict[str, WorkflowExtendStage]": |
      Map of new-stage extend-instructions keyed by stage name. Empty map when
      the workflow-file has no extend section.
    "memory -> WorkflowMemory | None": |
      Workflow-memory configuration extracted from the top-level memory
      block, or None when the workflow-file carries no block.
    "profile -> str | None": |
      The parsed counterpart of the peeked workflow default; activation
      reads the raw text via the peek, not this field. None when the
      workflow-file carries no top-level profile key.
    "build -> WorkflowBuild | None": |
      The six-field build block, consumed by the build path. None when the
      workflow-file carries no block.
    "assistants -> dict[str, WorkflowAssistant]": |
      The assistant catalog keyed by name, in authored order. Empty map
      when the workflow-file has no assistants section.
    "delegation -> WorkflowDelegation | None": |
      The delegation block, or None when the workflow-file carries no
      block.
    "repeat -> WorkflowRepeat | None": |
      The run-cycle tuning block, or None when the workflow-file carries no
      block or authors an empty block.
    "gates -> WorkflowGates | None": |
      The quality-gate settings block, or None when the workflow-file carries
      no block or authors an empty block.
    "agent -> str | None": |
      The workflow-global agent name — the global run-settings layer
      consumers resolve ahead of the configuration's pipeline agent;
      None when the key is absent or empty.
    "env -> dict[str, str] | None": |
      The workflow-global environment layer (string map); None when
      the key is absent (an empty map equals absence).

"parse_workflow(text: str) -> workflow: WorkflowDocument":
  location: parse_workflow.py
  annotations: |
    Structurally parse a rendered workflow-file text into a
    `WorkflowDocument`. Accept the rendered text (rendering happens before
    parsing — the caller renders), parse it as YAML, validate the expected
    keys and field types, build `WorkflowStage` instances per entry, and
    return the aggregated `WorkflowDocument`. No content validation beyond
    the structural schema (key set, types, loop bounds); no agent-name
    resolution, no loop expansion, no depends_on rewriting — all of those are
    the compiler's responsibility.

    `text`: the rendered workflow-file text
    `workflow`: the parsed `WorkflowDocument` carrying declarative
                instructions for the compiler

    Algorithm:
    1. Accept the rendered `text`
    2. Parse the text as YAML. On invalid YAML — raise a structural
       error "invalid YAML in workflow-file"
    3. If the loaded value is not a dict (e.g. a scalar, a string, a list)
       — raise a structural error "workflow must be a mapping"
    4. Extract the optional top-level keys:
       - prompt: if present, must be a str; otherwise raise a structural
         error "non-str value in workflow.prompt"
       - stages: if present, must be a dict; otherwise raise a structural
         error "non-mapping stages block in workflow"
       - extend: if present, must be a dict; otherwise raise a structural
         error "non-mapping extend block in workflow"
       - memory: if present, must be a dict; otherwise raise a structural
         error "non-mapping memory block in workflow"
       - profile: if present, must be a str; otherwise raise a structural
         error "non-str value in workflow.profile". An empty or
         whitespace-only value normalizes to None
       - build: if present, must be a dict; otherwise raise a structural
         error "non-mapping build block in workflow"
       - assistants: if present, must be a dict; otherwise raise a
         structural error "non-mapping assistants block in workflow; author
         the map form keyed by assistant name"
       - delegation: if present, must be a dict; otherwise raise a
         structural error "non-mapping delegation block in workflow"
       - repeat: if present, must be a dict; otherwise raise a structural
         error "non-mapping repeat block in workflow"
       - gates: if present, must be a dict; otherwise raise a structural
         error "non-mapping gates block in workflow"
       - agent: if present, must be a str; otherwise raise a structural
         error "non-str value in workflow.agent". An empty or
         whitespace-only value normalizes to None
       - env: if present, must be a dict of str→str; a non-dict value
         raises a structural error "non-mapping env in workflow"; a
         non-str key raises "non-str key in workflow.env"; a non-str
         value raises "non-str value in workflow.env.KEY". An empty map
         equals absence — build with env=None
    5. For every other top-level key that is not a hidden declaration
       key — raise a structural error
       "unknown key in workflow: KEY; valid keys: prompt, stages, extend,
       memory, profile, build, assistants, delegation, repeat, gates,
       agent, env". A hidden declaration key (a str starting with ".") is
       skipped: it is a YAML anchor site — by parse time YAML resolution
       has already merged the anchored content into its use sites
       (aliases and "<<" merge keys), so the key carries no workflow
       content, never satisfies the empty-workflow rule, and is not
       listed among valid keys
    6.0. For the memory block (when present), validate each key and value:
       - an unknown key raises "unknown key in workflow.memory: KEY; valid
         keys: method, path, max_rules, commit, mode"
       - method must be a str and one of "reflect"/"alignment"; otherwise
         raise "non-str value in workflow.memory.method" (non-str) or
         "method must be one of: reflect, alignment in workflow.memory"
         (str outside the set)
       - path must be a str of a valid path shape (non-empty, no leading "/",
         not absolute, no ".."); otherwise raise "non-str value in
         workflow.memory.path" (non-str) or "invalid path in
         workflow.memory.path: VALUE" (bad shape)
       - max_rules must be an int >= 1; otherwise raise "non-int value in
         workflow.memory.max_rules" (non-int) or "max_rules must be >= 1
         in workflow.memory" (int < 1)
       - commit must be a bool; otherwise raise "non-bool value in
         workflow.memory.commit"
       - mode must be a str and one of "r"/"w"/"rw"; otherwise raise
         "non-str value in workflow.memory.mode" (non-str) or "mode must
         be one of: r, w, rw in workflow.memory" (str outside the set).
         An authored mode together with the "reflect" method raises "mode
         is forbidden in workflow.memory with method: reflect"
       - build `WorkflowMemory` with materialized defaults (method "reflect",
         max_rules 25, commit False; mode "rw" under "alignment", None under
         "reflect")
    6.1. For each entry of stages (when present), identified by stage name
       and stage value:
       6.1.1. If the stage value is not a dict — raise a structural error
          "non-mapping stage NAME in workflow.stages"
       6.1.2. Validate the key set of the stage value against agent, env,
          prompt, loop, skills, skip, approve, manual, notes, reflect,
          memory, assistants, gates: an unknown key raises "unknown key in
          workflow.stages.NAME: KEY; valid keys: agent, env, prompt, loop,
          skills, skip, approve, manual, notes, reflect, memory,
          assistants, gates"
       6.1.3. agent (when present) must be a str; otherwise raise
          "non-str value in workflow.stages.NAME.agent"
       6.1.4. env (when present) must be a dict of str→str; a non-dict
          value raises a structural error "non-mapping env in
          workflow.stages.NAME"; a non-str key raises "non-str key in
          workflow.stages.NAME.env"; a non-str value raises "non-str
          value in workflow.stages.NAME.env.KEY". An empty map equals
          absence — build with env=None
       6.1.5. prompt (when present) must be a str; otherwise raise
          "non-str value in workflow.stages.NAME.prompt"
       6.1.6. loop (when present) must be an int and >= 1; otherwise raise
          "non-int value in workflow.stages.NAME.loop" (non-int) or
          "loop must be >= 1 in workflow.stages.NAME" (int < 1)
       6.1.7. skills (when present) must be a list[str]; otherwise raise
          "non-list-of-str skills in workflow.stages.NAME"
       6.1.8. skip (when present) must be a bool; otherwise raise a structural
          error "non-bool value in workflow.stages.NAME.skip"
       6.1.9. approve (when present) must be a str and one of "auto"/"plan"/"dialog";
          otherwise raise "non-str value in workflow.stages.NAME.approve"
          (non-str) or "approve must be one of: auto, plan, dialog in
          workflow.stages.NAME" (str outside the set)
       6.1.10. manual (when present) must be a bool; otherwise raise a structural
           error "non-bool value in workflow.stages.NAME.manual"
       6.1.11. notes (when present) must be a dict and every value must be a
           str; otherwise raise a structural error "non-mapping notes in
           workflow.stages.NAME" (non-dict) or "non-str value in
           workflow.stages.NAME.notes.KEY" (non-str value). An empty map equals
           absence — build with notes=None
       6.1.12. reflect (when present) must be a dict with a key set within
           {file, mode}: a non-dict value raises "non-mapping reflect in
           workflow.stages.NAME"; an unknown key raises "unknown key in
           workflow.stages.NAME.reflect: KEY; valid keys: file, mode". file
           is required, a str of a valid path shape — a missing file raises
           "file is required in workflow.stages.NAME.reflect", a non-str
           value raises "non-str value in workflow.stages.NAME.reflect.file",
           a bad shape raises "invalid path in
           workflow.stages.NAME.reflect.file: VALUE". mode (when present)
           is a str and one of "r"/"w"/"rw" — otherwise raise "non-str
           value in workflow.stages.NAME.reflect.mode" (non-str) or "mode
           must be one of: r, w, rw in workflow.stages.NAME.reflect" (str
           outside the set). Build `WorkflowReflect` with the authored
           file and mode materialized to "rw" when absent
       6.1.13. memory (when present) must be a bool; otherwise raise
           "non-bool value in workflow.stages.NAME.memory". An explicit false
           equals absence — build with memory=None
       6.1.14. gates (when present) must be a list — a non-list value raises
           "non-list gates in workflow.stages.NAME"; an empty list equals
           absence (None). Validate each step:
           - a non-mapping step raises "non-mapping gate step in
             workflow.stages.NAME.gates[i]"
           - the step key set is {name, script, agent, timeout, prompt,
             env}; an unknown key raises "unknown key in
             workflow.stages.NAME.gates[i]: KEY; valid keys: name, script,
             agent, timeout, prompt, env"
           - name is required: a missing name raises "gates step without
             name in workflow.stages.NAME.gates[i]"; a non-str value raises
             "non-str value in workflow.stages.NAME.gates[i].name"
           - exactly one of script/agent is required: both or neither
             raises "gates step must carry exactly one of script/agent in
             workflow.stages.NAME.gates[i]"
           - agent must be a non-empty string; otherwise raise "agent must
             be a non-empty string in workflow.stages.NAME.gates[i]". script
             must be a non-empty string or a non-empty list of non-empty
             strings — a scalar outside that raises "script must be a
             non-empty string in workflow.stages.NAME.gates[i]"; a list that
             is empty or carries a non-str or empty element raises "script
             must be a non-empty list of non-empty strings in
             workflow.stages.NAME.gates[i]". A list payload joins with
             newlines into ONE multi-line script string (shell-identical to
             authoring the same text as a block scalar)
           - timeout/prompt (when present) must be a str; otherwise
             raise "non-str value in
             workflow.stages.NAME.gates[i].timeout" / ".prompt"
           - prompt requires an agent step: a prompt authored on a step
             carrying script raises "prompt is forbidden on a script gate
             step in workflow.stages.NAME.gates[i]" (the engine accepts
             prompt on AI steps only)
           - env (when present) must be a dict of str→str — valid on BOTH
             step kinds (the string-map pattern of the per-stage env): a
             non-dict value raises "non-mapping env in
             workflow.stages.NAME.gates[i]"; a non-str key raises
             "non-str key in workflow.stages.NAME.gates[i].env"; a
             non-str value raises "non-str value in
             workflow.stages.NAME.gates[i].env.KEY". An empty map equals
             absence — build with env=None
           - build a `WorkflowGateStep` list in authored order and thread it
             into the `WorkflowStage` construction of 6.1.15
       6.1.15. Build a `WorkflowStage` from the validated values (agent, env,
           prompt, loop, skills, skip, approve, manual, notes, reflect,
           memory, assistants, gates — the list built by 6.1.14); an absent
           manual key yields None (NOT False);
           an empty notes map yields None; an empty env map yields None; an
           empty assistants map yields None
    6.2. For each entry of extend (when present), identified by stage name
        and entry value:
        6.2.1. If the entry value is not a dict — raise a structural error
           "non-mapping extend entry NAME in workflow.extend"
        6.2.2. If the entry value contains a depends_on key — raise a structural
           error "depends_on is forbidden in workflow.extend.NAME"
        6.2.3. If the entry value contains a skip key — raise a structural
            error "skip is forbidden in workflow.extend.NAME"
        6.2.4. If the entry value contains a manual key — raise a structural
            error "manual is forbidden in workflow.extend.NAME"
        6.2.5. If the entry value contains a notes key — raise a structural
            error "notes is forbidden in workflow.extend.NAME"
        6.2.6. If the entry value contains a reflect key — raise a structural
            error "reflect is forbidden in workflow.extend.NAME"
        6.2.7. If the entry value contains a memory key — raise a structural
            error "memory is forbidden in workflow.extend.NAME"
        6.2.8. If the entry value contains an env key — raise a structural
            error "env is forbidden in workflow.extend.NAME"
        6.2.9. before (when present) must be a list[str]; otherwise raise
           "non-list-of-str before in workflow.extend.NAME"
        6.2.10. after (when present) must be a list[str]; otherwise raise
           "non-list-of-str after in workflow.extend.NAME"
        6.2.11. agent (when present) must be a str; otherwise raise
           "non-str value in workflow.extend.NAME.agent"
        6.2.12. loop (when present) must be an int and >= 1; otherwise raise
           "non-int value in workflow.extend.NAME.loop" (non-int) or
           "loop must be >= 1 in workflow.extend.NAME" (int < 1)
        6.2.13. approve (when present) must be a str and one of "auto"/"plan"/"dialog";
           otherwise raise "non-str value in workflow.extend.NAME.approve"
           (non-str) or "approve must be one of: auto, plan, dialog in
           workflow.extend.NAME" (str outside the set)
        6.2.14. If neither before nor after is present — raise a structural error
           "extend entry NAME requires at least one of before/after"
        6.2.15. Other keys of the entry value are NOT validated (open-ended:
           title, prompt, skills, roles, communication, trigger — a full
           stage-body field — and any other stage field) and pass through
           verbatim
        6.2.16. Build a `WorkflowExtendStage` from the validated before/after,
           agent/loop/approve, and the REMAINING entry value (excluding before,
           after, agent, loop, approve, and depends_on) as body — agent/loop/
           approve are extracted into the model, not carried in body, so they
           never reach the flow-file as stray stage fields
    6.3.  Validate the correspondence between the materialized method and the
        per-stage instructions (the method is "reflect" when no block is
        authored):
        - a reflect instruction under "alignment" raises "reflect is forbidden
          in workflow.stages.NAME with method: alignment"
        - a memory instruction under "reflect" raises "memory is forbidden in
          workflow.stages.NAME with method: reflect"
    6.4. For the build block (when present), validate each key and value:
        - the strict key set is agent, env, review (with agent, env,
          additional with agent, env); an unknown key anywhere in the block
          raises "unknown key in workflow.build.KEY…: KEY; valid keys: agent,
          env, review.agent, review.env, review.additional.agent,
          review.additional.env" — proxy and hosts are unknown keys and
          therefore structural errors (the host launcher must not read
          workflow files)
        - agent values (root, review, review.additional) must be a str;
          otherwise raise "non-str value in workflow.build.agent" /
          "non-str value in workflow.build.review.agent" / "non-str value in
          workflow.build.review.additional.agent"
        - env maps (root, review, review.additional) follow the string-map
          pattern: a non-mapping value raises "non-mapping env in
          workflow.build" / "non-mapping env in workflow.build.review" /
          "non-mapping env in workflow.build.review.additional"; a non-str
          key raises "non-str key in workflow.build.env" (and the review /
          review.additional counterparts); a non-str value raises
          "non-str value in workflow.build.env.KEY" (and the review /
          review.additional counterparts)
        - build a `WorkflowBuild` from the validated six-field set
    6.5. For the assistants catalog (when present): the block must be a
        mapping keyed by assistant name (otherwise "non-mapping assistants
        block in workflow; author the map form keyed by assistant name");
        each entry value must be a mapping (otherwise "non-mapping
        assistant entry in workflow.assistants.NAME"). Entry value key set:
        prompt, skills, agent, delegate, env — an unknown key (including
        name, gate, and when) raises "unknown key in
        workflow.assistants.NAME: KEY; valid keys: prompt, skills, agent,
        delegate, env". prompt and agent (when present) are str; skills
        (when present) is a list[str] (an authored empty list is carried
        as an explicit empty value — an override that clears); delegate
        (when present) is a bool (absent builds None — not False); env
        (when present) is a str→str map (an authored empty map is
        carried as an explicit empty value — NOT normalized to absence).
        An entry may carry none of prompt/skills — an override-style
        entry; the effective-content requirement is enforced at
        compilation. Every entry key must match [A-Za-z0-9._-] and must
        not be "assistant"
        ("assistant name is reserved"); names are unique within the map (a
        YAML mapping cannot repeat a key) — uniqueness of a name across
        the catalog, the stage attachment maps, and the pipeline
        declarations of the compiled pipeline-file is a compilation
        check, not a parse rule. Build a `WorkflowAssistant` per entry
        with the key as name
    6.6. For the delegation block (when present): the block must be a dict
        (otherwise "non-mapping delegation block in workflow"); the key set
        is depth, max_tasks — an unknown key raises "unknown key in
        workflow.delegation: KEY; valid keys: depth, max_tasks". depth
        (when present) must be an int >= 0; max_tasks (when present) must
        be an int >= 1. Build a `WorkflowDelegation` with max_tasks
        materialized to 50 when not authored
    6.7. For each stage entry carrying an assistants key: the value must
        be a mapping keyed by assistant name (otherwise "non-mapping
        assistants in workflow.stages.NAME; author the map form keyed by
        assistant name"); an empty map equals absence (None). Each entry
        value must be a mapping (otherwise "non-mapping assistant
        attachment in workflow.stages.NAME.ASSISTANT"). Every entry
        carries exactly one meaningful instruction:
        - skip form: the value carries skip alone, strictly bool;
          skip: true is the veto entry; a lone skip: false raises
          "skip: false requires an extension field in
          workflow.stages.NAME.assistants.ASSISTANT"; skip together with
          any other key raises "skip cannot be combined with extension
          keys in workflow.stages.NAME.assistants.ASSISTANT"; an empty
          entry raises "empty assistant entry in
          workflow.stages.NAME.assistants.ASSISTANT"
        - every other form: the key set is prompt, skills, agent,
          delegate, env, gate, when — an unknown key raises "unknown key
          in workflow.stages.NAME.assistants.ASSISTANT: KEY; valid keys:
          prompt, skills, agent, delegate, env, gate, when". prompt and
          agent (when present) are str; skills (when present) is a
          list[str] (an authored empty list is an explicit override that
          clears); delegate (when present) is a bool (absent builds
          None — not False); env (when present) is a str→str map (an
          authored empty map is an explicit override — NOT normalized to
          absence). gate (when present) is strictly bool, carried as
          None when absent. when (when present) is one of
          start/checkpoints/finish/message, carried as None when absent.
          The name rules apply to every entry key; names are unique
          within the map. Build a WorkflowAssistant per entry with the
          key as name
    6.8. An assistants key in an extend-entry raises a structural error
        "assistants is forbidden in workflow.extend.NAME" — attachments of
        a new stage are authored in the stages block by the new stage's
        name
    6.9. For the repeat block (when present): the block must be a dict
        (otherwise "non-mapping repeat block in workflow"); the key set is
        max_cycles, keep_runs — an unknown key raises "unknown key in
        workflow.repeat: KEY; valid keys: max_cycles, keep_runs". Each
        value (when present) must be an int and not negative — otherwise
        raise "non-int value in workflow.repeat.max_cycles" / "non-int
        value in workflow.repeat.keep_runs" (non-int, a boolean included)
        or "max_cycles must be >= 0 in workflow.repeat" / "keep_runs must
        be >= 0 in workflow.repeat" (negative). Build a `WorkflowRepeat`
        from the authored values only; an empty block equals absence —
        carry repeat=None
    6.10. For the gates settings block (when present), validate each key and
        value:
       - an unknown key raises "unknown key in workflow.gates: KEY; valid
         keys: patience, max_iterations, fresh_correction"
       - patience/max_iterations must be an int >= 0 and not a bool;
         otherwise raise "non-int value in workflow.gates.KEY" (non-int, a
         boolean included) or "KEY must be >= 0 in workflow.gates"
         (negative)
       - fresh_correction must be a bool; otherwise raise "non-bool value
         in workflow.gates.fresh_correction"
       - an empty block equals absence — carry gates=None; otherwise build a
         `WorkflowGates` from the authored keys only
    6.11. A gates key in an extend-entry raises a structural error "gates
        is forbidden in workflow.extend.NAME" — checks of a new stage are
        authored in the stages block by the new stage's name
    7. If prompt is None AND stages is empty (no entries) AND extend is
       empty (no entries) AND memory is None AND build is None AND
       assistants is empty AND delegation is None AND repeat is None
       AND gates is None AND agent is None AND env is None
       — raise a structural error "empty workflow — provide at least
       prompt, one stage, one extend entry, the memory block, the build
       block, the assistants block, the delegation block, the repeat
       block, the gates block, the agent key, or the env block"
       (profile never rescues a workflow from emptiness — activation
       is not content)
    8. Return `WorkflowDocument` from the parsed prompt, stages, extend,
       memory, profile, build, assistants, delegation, repeat, gates,
       and the two global keys (the authored agent, or None; the
       authored env map, or None)

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

    Requirements:
    - Top-level unknown keys are a structural error — only prompt, stages,
      extend, memory, profile, build, assistants, delegation, repeat,
      gates, agent, and env are accepted
    - extend-entry depends_on is a structural error; before/after (when
      present) must be list[str]; at least one of before/after is required
    - extend-entry names are NOT validated against any pipeline here —
      unknown before/after names pass through; the compiler raises a
      structural error on a name absent from the pipeline and the
      extend-stages
    - Per-stage unknown keys are a structural error — only agent, env,
      prompt, loop, skills, skip, approve, manual, notes, reflect, memory,
      assistants, gates are accepted
    - stages.<name>.env (when present) must be a dict of str→str; a non-dict
      value raises "non-mapping env in workflow.stages.NAME"; a non-str
      key raises "non-str key in workflow.stages.NAME.env"; a non-str
      value raises "non-str value in workflow.stages.NAME.env.KEY"; an
      empty map equals absence (env=None). env is valid ONLY in the stages
      block — env in an extend-entry is a structural error
    - profile (when present) must be a str; a non-str value raises
      "non-str value in workflow.profile"; an empty or whitespace-only
      value normalizes to None
    - The build block carries the strict six-field set — agent, env,
      review.agent, review.env, review.additional.agent,
      review.additional.env; any other key of the block (including proxy
      and hosts) is a structural error — the host launcher must not read
      workflow files; env maps follow the string-map pattern (str
      keys, str values)
    - skip (when present) must be a bool; a non-bool value is a structural
      error
    - skip is forbidden in an extend-entry — a structural error (skip is
      defined only for existing pipeline stages via the stages block)
    - skills (when present) must be a list[str]; a non-list-of-str value is
      a structural error
    - loop must be an int >= 1; zero, negative values, and non-int types
      are structural errors
    - approve (stages-block entry AND inline extend) must be a str and one of
      "auto"/"plan"/"dialog"; any other value or a non-str is a structural error
    - manual is accepted ONLY in the stages block; a non-bool manual is a
      structural error; manual in an extend-entry is a structural error
    - notes (stages-block only) must be a dict of str→str; a non-dict value
      raises "non-mapping notes in workflow.stages.NAME"; a non-str value
      raises "non-str value in workflow.stages.NAME.notes.KEY"; an empty notes
      map is treated as absence (notes=None); notes in an extend-entry is a
      structural error
    - trigger in the stages block is an unknown-key structural error; trigger
      in an extend-entry body passes through verbatim (validated at compile
      time, not here)
    - An extend-entry's inline agent (when present) must be a str, its
      inline loop (when present) must be an int >= 1, and its inline
      approve (when present) must be a str and one of "auto"/"plan"/"dialog" —
      same type/value rules as the stages block; non-conforming values are
      structural errors
    - Inline agent/loop/approve of an extend-entry are EXTRACTED into the
      model and excluded from the verbatim body (like before/after) — they
      do not pass through as stage fields
    - Stage-name keys are NOT validated against any pipeline IN THIS CELL
      — unknown stage names pass through; the compiler raises a structural
      error on names absent from both the pipeline and the extend-stages
      (strict validation; it does not silently apply or ignore with a
      warning). This cell stays declarative — it does NOT
      validate names itself
    - A single workflow-file can apply to several pipelines ONLY when
      every name it references exists in each target pipeline; a name
      absent from a target pipeline is a structural error (not a silent
      warning+skip) — split or prune such workflows
    - Hidden declaration keys — top-level str keys starting with "." — are
      skipped, not rejected and not validated: they are YAML anchor sites
      whose content YAML resolution has already merged into its use sites;
      a hidden key alone does not satisfy the empty-workflow rule
    - A workflow-file with none of a prompt, any stage entries, any extend
      entries, the memory block, the build block, the assistants block, the
      delegation block, the repeat block, the gates block, the agent key,
      or the env block is rejected — at least one must be present
    - agent (when present) must be a str; a non-str value raises
      "non-str value in workflow.agent"; an empty or whitespace-only
      value normalizes to None (absence)
    - env (when present) must be a dict of str→str; a non-dict value
      raises "non-mapping env in workflow"; a non-str key raises
      "non-str key in workflow.env"; a non-str value raises "non-str
      value in workflow.env.KEY"; an empty map equals absence
      (env=None)
    - A workflow consisting of the agent key alone or the env block
      alone is valid — both keys count as content
    - A workflow consisting of the build block alone is valid
    - The assistants catalog grammar: a name-keyed mapping; each entry value
      carries the key set prompt, skills, agent, delegate, env; delegate is
      a bool; env is a str→str map (an authored empty map is an explicit
      override); gate and when are attachment keys —
      authoring either in the catalog is an unknown-key structural error;
      name is the map key — an inner name key is an unknown key
    - The delegation block grammar: the key set depth, max_tasks; depth is
      an int >= 0; max_tasks is an int >= 1; max_tasks materializes to 50
      when the block omits it
    - The stage attachment grammar: a name-keyed mapping; an empty map
      equals absence (None); each entry value is a mapping whose lone key
      skip forms the veto, whose keys within {gate, when} form a
      reference, and whose any further key forms a full inline
      declaration or an extension (the catalog key set plus gate and
      when); the value domain of when is validated whenever authored;
      gate and skip are bools
    - For assistant fields, presence is preserved: skills [] and env {}
      are explicit empty overrides; delegate/gate/when absent are None
    - The repeat block grammar: a mapping whose key set is max_cycles,
      keep_runs; each value is an int >= 0 (a boolean is not an integer); a
      scalar block value is a structural error; an empty block equals
      absence
    - A workflow consisting of the repeat block alone is valid
    - A workflow consisting of the gates block alone is valid
    - gates is forbidden in an extend-entry — a structural error
    - prompt is forbidden on a script gate step — a structural error (the
      engine accepts prompt on AI steps only)
    - A gate step's env (when present) is a dict of str→str valid on BOTH
      step kinds; an empty map equals absence (env=None); the env key shape
      (a legal environment variable name) is NOT validated here — the gate
      wrapper generation rejects an illegal key with a strict pre-run error
    - A malformed timeout value and the name text content are NOT
      validated — passed through verbatim (value grammar is engine-owned)
    - assistants is forbidden in an extend-entry — attachments of a new
      stage are authored in the stages block by the new stage's name
    - A workflow consisting of the assistants block alone or the delegation
      block alone is valid
    - Reference names are not resolved here — the compiler raises on a name
      matching no declaration of the effective document
    - agent value is NOT validated against a known agent set; absence of
      the wrapper file is surfaced by afm at invocation time
    - prompt contents (top-level and per-stage) are NOT validated — passed
      through verbatim to the consumer
    - The memory block and both instructions are validated structurally: key
      sets, types, value domains, path shapes, and the method ↔ instruction
      correspondence
    - Defaults are materialized in the model, not omitted
    - An explicit memory: false equals absence — the model carries None
    - A workflow consisting of the memory block alone is valid
    - reflect and memory are forbidden in an extend entry — participation of a
      new stage is authored in the stages block by its name

    Constraints:
    - Do not resolve agent to a wrapper path here — the compiler performs
      that composition
    - Do not perform loop expansion here — the compiler expands based on the
      loop count
    - Do not rewrite depends_on here — the compiler handles external
      references after expansion
    - Do not validate stage names against any pipeline schema — the compiler
      performs the match (raising a structural error on names absent from
      both the pipeline and the extend-stages)
    - Do not DELETE a stage or RECONNECT dependents when skip is True —
      skip is a declarative instruction; the compiler performs the removal
      and reconnection
    - Do not act on approve here — it is declarative; the compiler applies
      the interactive-suppress / auto_approve logic
    - Do not act on manual here — it is declarative; the compiler applies the
      force / cancel logic
    - Do not emit or act on the buttons here — notes is declarative; the
      compiler emits the per-stage buttons field
    - Do not let an inline extend approve reach the extend-stage body —
      it is extracted into the model (like agent/loop)
    - Do not read files or render here — the caller owns both; `text`
      arrives already rendered
    - Do not accept YAML text whose root is not a mapping — that is a
      structural error
    - Do not compose the memory root prefix here — the consumer composes the
      final path
    - Do not decide block emission or stage participation here — the consumer
      decides both
    - Do not validate reflect/memory keys inside stage bodies here — stage bodies
      are the consumer's input, checked at compilation
    - Do not resolve attachment references or derive profile ids here — the
      compiler resolves a reference against the assistant names of the
      effective document and the delivery materializes the profile
    - Do not enforce a when on any entry and do not check name uniqueness
      beyond the entry's own map — both are origin-aware compilation
      checks
    - Do not classify an entry as skip/extension/reference/inline — the
      origin resolves where both documents meet
    - Do not resolve agent to a wrapper path, merge env with any other
      layer, or apply either global anywhere here — the consumers own
      every resolution law

"WorkflowSyntaxError(message: str)":
  location: parse_workflow.py
  annotations: |
    Structural error of workflow-file parsing — raised, never returned. The
    single exception type every structural rejection in this cell surfaces:
    `parse_workflow` raises it for grammar violations (unknown top-level key,
    malformed stages/extend/memory, an invalid build block, the empty-workflow
    rule) and `load_workflow` lets it propagate from the parse step after
    rendering. 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

"ProfileSource()":
  location: profile_source.py
  annotations: |
    str-backed Enum declaring the origin of a resolved profile. Modeled
    via the standard library enum module; str-mixin so values serialize
    as plain strings (per `convention`).
  properties:
    "PROJECT = \"project\"": |
      Origin = project-level <cwd>/.goga/profiles/ (committed).
    "HOME = \"home\"": |
      Origin = home-level ~/.goga/profiles/ (personal, carried in the
      decoded home bundle).

"ResolvedProfile(name: str, data: dict[str, Any], source: ProfileSource)":
  location: resolved_profile.py
  annotations: |
    The active profile as a single value: its name, its whole content
    mapping, and where it was found.

    `name`: the resolved profile name
    `data`: the entire profile content — every top-level key becomes a
            template variable at rendering
    `source`: where the profile was found — `ProfileSource` value

    Requirements:
    - Immutable frozen dataclass (frozen=True, kw_only=True), per
      `convention`

    Constraints:
    - Do not resolve wrappers, render templates, or apply the content
      anywhere here — consumers own both
  properties:
    "name -> str": |
      The resolved profile name.
    "data -> dict[str, Any]": |
      The entire profile content; the rendering context source.
    "source -> ProfileSource": |
      Origin of the profile: project or home.

"LoadedWorkflow(document: WorkflowDocument, profile: ResolvedProfile | None)":
  location: loaded_workflow.py
  annotations: |
    The result of loading a workflow-file under an activation context:
    the parsed document plus the profile that was active during the load
    (None when no profile resolved).

    `document`: the parsed `WorkflowDocument`
    `profile`: the `ResolvedProfile` active at rendering, or None

    Requirements:
    - Immutable frozen dataclass (frozen=True, kw_only=True), per
      `convention`

    Constraints:
    - Do not revalidate fields here — the parts were validated by their
      producers
  properties:
    "document -> WorkflowDocument": |
      The parsed workflow document.
    "profile -> ResolvedProfile | None": |
      The profile active during rendering, or None when the render ran
      with an empty context.

"WorkflowBuild(agent: str | None = None, env: dict[str, str] | None = None, review_agent: str | None = None, review_env: dict[str, str] | None = None, review_additional_agent: str | None = None, review_additional_env: dict[str, str] | None = None)":
  location: workflow_build.py
  annotations: |
    Data model of the top-level workflow build block — the strict
    six-field set of build-pass settings the workflow may provide. All
    fields default to None (absent); an absent field never overrides the
    configuration.

    `agent`: tasks-pass agent override, or None
    `env`: tasks-pass env overlay (string map), or None
    `review_agent`: review-pass agent override, or None
    `review_env`: review-pass env overlay, or None
    `review_additional_agent`: external-review agent override, or None
    `review_additional_env`: external-review env overlay, or None

    Requirements:
    - Use @dataclass(kw_only=True) (per `convention`)
    - Field order is fixed: agent, env, review_agent, review_env,
      review_additional_agent, review_additional_env
    - Built only by `parse_workflow` from the validated block

    Constraints:
    - Do not merge with any configuration here — the build path owns the
      layering
    - No proxy, hosts, or any other field may appear — the parser
      rejects unknown keys of the block as structural errors
  properties:
    "agent -> str | None": |
      Tasks-pass agent override; None when absent.
    "env -> dict[str, str] | None": |
      Tasks-pass env overlay; None when absent.
    "review_agent -> str | None": |
      Review-pass agent override; None when absent.
    "review_env -> dict[str, str] | None": |
      Review-pass env overlay; None when absent.
    "review_additional_agent -> str | None": |
      External-review agent override; None when absent.
    "review_additional_env -> dict[str, str] | None": |
      External-review env overlay; None when absent.

"load_home_profiles(home_dir: Path) -> profiles: dict[str, dict[str, Any]]":
  location: load_home_profiles.py
  annotations: |
    Read and strictly parse the whole home profiles bundle: every flat
    *.yml file under `home_dir`, collected into one name → mapping.

    `home_dir`: the home profiles directory (typically
                ~/.goga/profiles/)
    `profiles`: mapping of profile name → profile content

    Algorithm:
    1. Scan flat *.yml files (non-recursive) under `home_dir`; a missing
       directory resolves to an empty mapping
    2. For each file: parse as YAML; invalid YAML, a non-mapping root,
       or a non-string key raises one strict error naming the file path
       (the JSON carriage would silently coerce a non-string key,
       mutating the profile across the docker boundary)
    3. For each parsed mapping: reject a value no JSON payload can
       represent (e.g. an unquoted YAML date) with one strict error
       naming the file path — the bundle crosses the docker boundary as
       JSON, so this is part of malformed-profile strictness, not
       content validation
    4. Return the collected mapping (file stem → content)

    Requirements:
    - A malformed home profile is a strict failure — the caller runs this
       on the host before any container launches
    - Deterministic — unchanged directory contents produce the identical
       mapping

    Constraints:
    - Do not read the environment — the directory arrives as a parameter
    - Do not validate profile-name grammar here — bundle keys that fail
      the grammar are inert; the lookup validates the REQUESTED name

"resolve_profile(name: str, project_dir: Path, home_profiles: dict[str, dict[str, Any]]) -> profile: ResolvedProfile":
  location: resolve_profile.py
  annotations: |
    Validate a profile name and resolve it to a `ResolvedProfile`:
    project lookup first, then the home bundle; on the same name the
    project profile wins.

    `name`: the requested profile name
    `project_dir`: the project profiles directory (typically
                   <cwd>/.goga/profiles/)
    `home_profiles`: the decoded home bundle mapping
    `profile`: the resolved `ResolvedProfile`

    Algorithm:
    1. Validate `name` against the profile-name grammar
       ([A-Za-z0-9][A-Za-z0-9._-]*; "." and ".." forbidden) — the name
       becomes a filesystem path component, so a violation raises one
       strict error naming the profile (path-traversal guard)
    2. When <project_dir>/<name>.yml exists: parse it; invalid YAML, a
       non-mapping root, or a non-string key raises one strict error
       naming the profile and the path (the rendering context is keyword
       arguments — a non-string key would crash the render); return
       `ResolvedProfile` with source project
    3. Otherwise, when `name` is present in `home_profiles`: return
       `ResolvedProfile` with source home
    4. Otherwise raise one strict error naming the profile and BOTH
       lookup locations

    Requirements:
    - Project-wins on the same name
    - All failures are strict, pre-run, with actionable messages

    Constraints:
    - Do not read the environment — home data arrives as a parameter
    - Do not render anything here — the consumer renders

"render_workflow(text: str, profile_data: dict[str, Any], source_name: str = \"\") -> rendered: str":
  location: render_workflow.py
  annotations: |
    Render a whole workflow-file text as a Jinja template with the
    active profile content as the template context. Rendering is a step
    BEFORE parsing; the rendered text feeds the standard parser.

    `text`: the raw workflow-file text
    `profile_data`: the template context — the entire active profile
                    content, or an empty mapping for a context-less
                    render
    `source_name`: optional workflow file name carried into error
                   messages
    `rendered`: the rendered text

    Use `jinja2` for the environment configuration and the error
    surfacing.

    Algorithm:
    1. Build the rendering environment per `jinja2` — the fixed flag
       set, the standard Undefined, autoescape off
    2. Render the whole text with `profile_data` as the context
    3. A template syntax error raises one strict error carrying
       `source_name`, the line number, and the message

    Requirements:
    - A plain file without template syntax renders to itself
    - Missing context keys follow standard Jinja semantics — falsy in
      guards, empty when interpolated; nested access on a missing key
      fails at render time

    Constraints:
    - Do not parse YAML here — the consumer parses the rendered text
    - Do not read files or the environment — text and context arrive as
      parameters

"render_contribution(document: WorkflowDocument, profile_data: dict[str, Any]) -> rendered: WorkflowDocument":
  location: render_contribution.py
  annotations: |
    Render every template surface of one committed workflow contribution
    with the active profile's content — the field-level rendering step
    the pipeline amendment applies to a tool's buffered document at its
    commit moment, before the authored-wins merge.

    `document`: the committed contribution — a `WorkflowDocument`-shaped
                set of instructions, raw (pre-render)
    `profile_data`: the template context — the entire content of the
                    active profile, or an empty mapping when no profile
                    is active
    `rendered`: a NEW `WorkflowDocument` with every template surface
                rendered; the input is never mutated

    Use `jinja2` for the rendering engine contract: the fixed
    environment flags, the context rule, the missing-key semantics, and
    the strict syntax-error surfacing.
    Apply `convention` for docstring style.

    Algorithm:
    1. Walk `document` type-driven at any depth, over the typed model
       fields and the verbatim extend-entry bodies alike: render every
       string leaf and every string mapping key individually; carry every
       non-string scalar unchanged. The walk is field-set-complete over
       the document model — a new model field flows through this routine
       without touching it again — and no field is exempt: the
       never-merging global fields (profile, build, agent, env) render
       like every other surface
    2. Render each surface with the fixed environment per `jinja2` and
       exactly `profile_data` as the context — no ambient variables
       (tool, pipeline, workflow name) exist in the context
    3. While rendering the keys of one map — detect a rendered-key
       collision: two distinct source keys rendering to the same result
       key raise one strict error naming the map (its dot-path), the
       source keys, and the colliding result
    4. On a template error in any surface — dead fields included — raise
       one strict error carrying the template cause: the error class, the
       message, and the document path — the dot-path of the string
       within the contribution built from the source (pre-render) keys,
       with list elements indexed and the two gates shapes disambiguated
       positionally (the workflow-level gates settings block path versus
       a stage check-step list path)
    5. Return the new `WorkflowDocument` — every surface rendered, every
       non-string value carried unchanged, field presence unchanged (a
       rendered empty string is a value, not an absence)

    Requirements:
    - Pure — no mutation of `document` or its maps; the result is a new
      document
    - No I/O — no files, no environment reads, no subprocess; string
      rendering only
    - A document whose strings carry no template syntax renders to an
      equal document — every string unchanged, presence and order
      preserved
    - Without an active profile the render runs against an empty
      context — template syntax still processes, missing keys render
      empty
    - Rendering never changes field presence — the presence-based
      empty-contribution check downstream is unaffected

    Constraints:
    - Do not parse, validate, or restructure the document — rendering
      replaces string values and keys only; the structure is preserved
    - Do not merge, apply, or interpret the document — the amendment
      merge and the compilation own both
    - Do not resolve profiles or read the environment — the context
      arrives as `profile_data`
    - Do not build a second template environment, dialect, or ambient
      context — one fixed environment, one context rule, per `jinja2`

"resolve_activation(cli_profile: str | None, env_profile: str | None, workflow_default: str | None) -> name: str | None":
  location: resolve_activation.py
  annotations: |
    Resolve the effective profile name from the three activation
    sources, strongest first: CLI option, environment variable,
    workflow default.

    `cli_profile`: the --profile flag value, or None
    `env_profile`: the GOGA_PROFILE value, or None
    `workflow_default`: the workflow's top-level profile: default, or
                        None
    `name`: the effective profile name, or None when every source is
            unset

    Algorithm:
    1. Return the first non-empty value among `cli_profile`,
       `env_profile`, `workflow_default` — in that order
    2. Empty and whitespace-only strings count as unset
    3. Return None when all sources are unset

    Requirements:
    - Pure — no environment reads; every source arrives as a parameter

    Constraints:
    - Do not load the profile here — only the name resolves

"load_workflow(workflow_path: Path, cli_profile: str | None = None, env_profile: str | None = None, home_profiles: dict[str, dict[str, Any]] | None = None) -> loaded: LoadedWorkflow":
  location: load_workflow.py
  annotations: |
    The single loading chain that turns a workflow-file path into a
    `LoadedWorkflow` under an activation context: read, peek the
    default, resolve activation, resolve the profile, render the whole
    file, parse the rendered text.

    `workflow_path`: absolute path to the workflow-file
    `cli_profile`: the CLI activation channel value, or None
    `env_profile`: the environment activation channel value, or None
    `home_profiles`: the decoded home bundle, or None (treated as empty)
    `loaded`: the `LoadedWorkflow` — document plus the active profile

    Use `jinja2` (through `render_workflow`) for the rendering step.

    Algorithm:
    1. Read the file text; OSError propagates unchanged
    2. Peek a literal top-level profile: value from the RAW text — a
       default that materializes only through template rendering does
       not participate in activation
    3. Resolve the effective profile name via `resolve_activation` from
       the two channel values and the peeked default
    4. When a name resolved: load it via `resolve_profile` against
       <cwd>/.goga/profiles/ and the home bundle; otherwise the profile
       is None
    5. Render the whole text via `render_workflow` with the profile
       content as the context — an empty context when no profile
       resolved
    6. Parse the rendered text via `parse_workflow`; structural errors
       propagate with their readable messages
    7. Return `LoadedWorkflow` of the document and the profile

    Requirements:
    - Rendering runs ALWAYS — a plain file renders to itself; templates
      without activation render with the empty context
    - Rendering never bypasses validation — the rendered text passes
      the standard structural validation unchanged
    - The activation channels arrive as parameters — the chain reads no
      environment

    Constraints:
    - Do not mutate the inputs; do not write anything
    - Do not resolve the workflow path or its existence here — the
      caller owns path composition and guards

---

Author: Goga
CreatedAt: 17/07/26
Description: |
  Pure parser of project-level workflow-files into declarative
  `WorkflowDocument` instructions that downstream consumers apply to
  extend a pipeline at compilation time — the per-stage overrides, the
  extend-stages, the memory configuration, the run-cycle tuning, the
  collaboration instructions (assistant catalog, delegation bounds, stage
  attachments), the stage quality-gate instructions (the retry
  settings block and the per-stage check steps), and the two global run
  settings (agent and env). Additionally owns the
  contributor-profile zone of the
  workflow path: profile resolution, strict profile-name validation,
  activation precedence resolution, whole-file Jinja rendering of
  workflow-files before parsing, and field-level rendering of committed
  workflow contributions.
