Imports:
  - Types:
      - compile_flow
      - translate_role
      - parse_dsl
      - StructuralError
      - PipelineRoles
      - PipelineDocument
      - FlowStage
      - FlowDocument
      - FlowVerify
      - FlowVerifyStep
      - FlowTeamMember
      - FlowAssistant
    Usages:
      - compile-flow
      - parse-dsl
      - serialize-flow
      - memory-emission
      - collaboration-emission
    From: goga/pipeline/compiler
  - Types:
      - run_flow
    Usages:
      - run-flow
    From: goga/afm
  - Types:
      - ensure_in_docker
      - decode_extra_env
      - decode_home_profiles
    Usages:
      - ensure-in-docker
      - extra-env-carriage
      - home-profiles-carriage
    From: goga/docker
  - Types:
      - load_workflow
      - WorkflowDocument
      - WorkflowStage
      - WorkflowGateStep
      - LoadedWorkflow
      - WorkflowSyntaxError
      - ResolvedProfile
    Usages:
      - parse-workflow
      - memory
      - load-workflow
      - profiles
      - assistants
    From: goga/pipeline/workflow
  - Types:
      - resolve_project_name
      - load_project_config
    Usages:
      - project-configuration
    From: goga/config
  - Types:
      - ConfigHooks
      - ConfigOverlay
    From: goga/config/hooks
  - Types:
      - resolve_wrapper_path
    Usages:
      - resolve-wrapper-path
    From: goga/agents
  - Types:
      - PipelineHooks
      - PipelineIdentity
      - WorkflowDecision
      - WorkIdentity
      - WorkflowOverlay
      - CompositionStage
      - RunIdentity
      - StageTransition
      - RunEvent
      - StageEvent
    Usages:
      - checkpoints
    From: goga/pipeline/hooks
  - Types:
      - resolve_current_branch_name
      - resolve_topic_dir
      - resolve_topic_status
      - assemble_status_scale
    Usages:
      - topic-paths
      - topic-statuses
    From: goga/history

Usages:
  convention: .goga/usages/conventions.md
  afm: .goga/usages/cooks/afm.md
  argparse: |
    Use the standard library argparse module for in-container CLI parsing.
    Three subcommands: list (with an optional --info flag), run (a required
    name, an optional --info flag, the workflow flags -w/--workflow NAME and
    --no-workflow, the profile flag -p/--profile NAME, a repeatable
    -s/--skip NAME, and a --fail-on-error flag — all five available with
    and without --info (fail-on-error takes effect in run mode only),
    --port required only without --info, and an optional --parallel N
    (run mode only)), and hook
    (no options — the afm-facing machinery entry receiving the event through
    the process environment and stdin).
  cli_entrypoint: |
    The in-container CLI is launched through the package runpy entrypoint
    (python -m goga.pipeline). The package __main__ module MUST stay a thin
    wrapper: it imports `pipeline_cli` from the local cli module and calls
    it with process argv under the standard __main__ guard. The
    `pipeline_cli` implementation itself MUST live in the cli module —
    never in the __main__ module — so that importing the goga.pipeline
    package does not pull __main__ into sys.modules and trigger a runpy
    RuntimeWarning about __main__ being pre-imported. The single piece of
    logic permitted in __main__.py besides the runpy delegation is the
    in-container docker guard (`ensure_in_docker`, per the
    `ensure-in-docker` practice): it is invoked as the very first
    statement of the __main__ guard block, before `pipeline_cli` is called,
    so host-side invocations of python -m goga.pipeline fail loudly before
    any pipeline work. The guard does NOT move into `pipeline_cli` itself
    — `pipeline_cli` stays a pure parse-and-dispatch routine whose
    contract is unchanged by the guard. The guard invocation MUST be
    covered by tests for both branches: the success path (GOGA_DOCKER=1)
    proceeds to `pipeline_cli`, and the refusal path (marker unset or not
    "1") writes to stderr and exits with code 1 before `pipeline_cli` is
    reached.
  default_prompts: |
    The four default agent prompt files ship inside the installed goga
    package at
    goga/assets/afm/prompts/{planning,implementation,review,summary}.md.
    The directory contains exactly four files; the file stem matches the
    canonical afm agent name. Three of them (planning, implementation,
    review) correspond to the overridable DSL roles planner/executor/
    reviewer (the role-field-name → stem mapping is resolved via
    `translate_role`, imported from goga/pipeline/compiler); summary
    is NOT overridable from the DSL — summary.md is always materialized
    from the default. Resolution from the installed package location is an
    implementation detail — the consumer may use any standard mechanism
    (e.g. importlib.resources or Path(__file__) composition) that yields
    the absolute path to the package's goga/assets/afm/prompts/
    directory at runtime. All four files are expected to exist in a
    properly installed image — when a default is missing AND no inline
    override is supplied for the corresponding role, materialization
    fails with a readable error before launch.
  default_skin: |
    The goga dashboard skin ships inside the installed goga package at
    goga/assets/afm/skin/ — a flat directory of skin files (currently
    index.css, goga.css, favicon.png, and title.txt). The afm
    configuration the run coordination writes points the engine's
    skin_dir at /home/goga/.afm/skins/goga (the static field, the very
    directory that must hold index.css for afm to serve the custom skin;
    the engine-builtin theme is the fallback when it does not), and the skin
    materialization copies the packaged
    directory verbatim into /home/goga/.afm/skins/goga/ on every launch
    (validate-all, then reset, then copy — a missing or empty packaged
    directory is one strict pre-run error that never wipes the
    previously materialized skin). Resolution from the installed package
    location is an implementation detail of the same shape as
    `default_prompts` — the consumer may use any standard mechanism
    that yields the absolute path to the package's goga/assets/afm/skin/
    directory at runtime. The file set is whatever the package carries:
    no fixed-name requirement beyond a non-empty directory, so the skin
    evolves with the package without a contract change.

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 owns the pipeline workflow surface: discovery of *.yml pipeline
  files across the project and user pipeline directories, the pipeline-file
  entity model, the informational surface (overview and card), run
  coordination, and the in-container CLI entrypoint `pipeline_cli`.
  Subprocess execution is delegated to `run_flow` — afm run is invoked inside
  the container, never directly.

  The run interior arrives through afm-facing machinery of this cell: the
  afm configuration write registers goga's own observer hook on every
  launch, the dashboard skin materialization populates the skins directory
  the written configuration points at (per `default_skin`), and the hook
  entry of the in-container CLI bridges the lifecycle
  events onto the platform — one short-lived process per event, the
  curated vocabulary mapped in one place, the emission delivered through
  the pipeline hooks zone. The bridging is observer-only: no bridge
  outcome ever changes the run. Use `afm` for the lifecycle-hooks
  mechanism — the payload, the AFM_* environment, the execution model,
  the failure semantics, and the registration stance.

  Build the data models `PipelineEntry`, `PipelineSummary`, `PipelineCard`,
  and `CardStage` with the standard library dataclasses module (kw_only=True
  per `convention`); `PipelineSource` with the standard library enum module
  (str-backed). Use pathlib.Path for directory and path resolution.

  The pipeline directories are <cwd>/.goga/pipelines/ (project-level,
  user-authored) and ~/.goga/pipelines/ (user-level, populated by goga
  connect). On a name conflict, the project source wins. The workflow
  directory is <cwd>/.goga/workflows/ (project-level).

  Workflow resolution is one rule set shared by run coordination and the
  card: an explicit workflow name, forced disabling, and the basename
  auto-match of the pipeline name are resolved by `resolve_workflow`, so the
  card always reflects the workflow a run with the same flags would apply.
  Use `parse-workflow` for the accepted workflow-file structure.

  The CLI skip names arrive as an explicit parameter of run coordination and
  the card: applied in-memory onto the resolved workflow before compilation.
  The CLI performs no stage-name validation — unknown names surface as the
  compiler's structural error.

  The run coordination and the card compose through the pipeline hooks zone:
  the workflow amendment is delivered after the runner-skip merge and before
  compilation, the run notifications fire around the runner launch, and the
  card reports the contributing tools. An explicit workflow disable turns
  the layer off — the raw authored DSL composes and no amendment delivers;
  a silent auto-match miss keeps the layer active onto the empty base. The
  branch, topic, and status facts resolve in the operation before the
  delivery — the checkpoints read nothing. The amendment delivery is
  profile-aware in both forms: the operation's already-resolved active
  contributor profile — the loaded workflow's profile, None when no
  workflow resolved — travels into the delivery as operation data; every
  tool's view reads the same profile fact and the delivery renders each
  committed contribution's strings with that profile's content before
  the merge. The run form and the card form deliver the identical fact
  and the identical rendering. With no tool packages installed the
  overlay is the passthrough — every form behaves exactly as with the
  amendment layer absent.
  Use the `checkpoints` practice for the checkpoint surface of the zone.
  Use the `topic-paths` practice for the topic directory resolution behind
  the work identity and the `topic-statuses` practice for the status facts
  of the run events.

  The run coordination owns the in-container run parameters: the opening
  load-and-amend of the project configuration (the effective configuration
  feeds everything downstream), the afm configuration authorship, the afm
  home's dashboard-skin materialization (per `default_skin`), and the
  launch environment composition around the afm launch. The config amendment
  delivery of the load moment follows the one-action-two-moments rule — the
  same action, vocabulary, and semantics as the host delivery; each side
  consumes only the fields it owns. Use `project-configuration` for the
  authored load, `afm` for the written
  configuration-file contract, `resolve-wrapper-path` for the agent command
  resolution, and `extra-env-carriage` for the CLI entries carriage of the
  launch layer.

  The listing, overview, and card forms load no configuration and deliver no
  checkpoint — only the run form performs the load-and-amend. Docker-level
  fields of the effective configuration (image, proxy, hosts) are
  applied-but-unconsumed in-container — silently, summary lines only.

  The cell runs inside the goga Docker image when invoked through
  python -m goga.pipeline; the host-side launcher lives in
  goga/commands/pipeline (docker runtime boundary — no Python Imports).

  Use the `argparse` practice for the in-container CLI parsing and the
  `cli_entrypoint` practice for the thin __main__ delegation with the
  in-container docker guard (`ensure-in-docker`).

  Compilation step: run coordination invokes `compile_flow` (see
  `compile-flow`) to transform the discovered pipeline-file into an afm
  flow-file at runtime inside the container; use `parse-dsl` and
  `serialize-flow` for the intermediate stages when a lower-level view is
  required. Use `memory-emission` for the compiled memory surface of the
  flow-file — the top-level memory block and the per-stage memory keys.

  Prompt materialization step: after compilation, run coordination
  materializes the four default agent prompt files (per `default_prompts`)
  into <AFM_DIR>/prompts/ and applies per-role inline overrides.

  Skin materialization step: after the afm configuration write, run
  coordination materializes the packaged goga dashboard skin (per
  `default_skin`) into /home/goga/.afm/skins/goga/ — the very directory
  the written skin_dir points at, served wholesale by afm as the active
  skin while it holds index.css (the engine-builtin theme is the
  fallback when it does not).

  Informational surface: the overview lists every discovered pipeline with
  its description from the DSL header; the card reports the name, the
  description, and the post-workflow stage composition produced by the same
  compilation machine a run uses. The card applies the CLI skip names through the same in-memory merge a run
  applies, and workflow-file skip directives arrive through the shared
  compilation machine — both are part of the composition a run with the same
  flags executes. The card writes nothing into the project or
  runtime directories.

  Per-stage environment delivery: the stages.<name>.env instruction is
  delivered in one of two forms, by the compiled shape of the stage. A
  script stage (its body carries script) gets a generated per-step
  payload closure carrying the authored script lines as-is — the stage's
  script field is patched to run it, no agent is resolved, and a script
  claim never fails on a missing agent. An agent stage keeps the
  exec-closure form: a generated per-stage closure wrapper the afm stage
  command points at (the absolute-executable-path convention; Use `afm`
  for the command-field contract). The wrapper exports the stage env,
  then execs the stage agent's wrapper, else the extend-entry agent's
  wrapper for the stage, else the effective global
  agent's wrapper (resolved the same way for both consumers), else
  fails strictly before the run. Wrappers live in a container-local
  temp directory — never under /workspace; per-stage values layer
  above all global env layers. Gate check steps carry their own env
  delivery: a step of stages.<name>.gates with an authored env map gets
  its gate wrapper generated by `apply_gate_env_wrappers` over the
  already compiled verify emission.

  The run coordination resolves the effective global agent and the
  effective launch env base from the effective workflow document and
  the effective project configuration. The workflow's global agent,
  when the effective workflow carries one, is the global agent of the
  run — the single value feeding the afm client command, the per-stage
  wrapper exec fallback, and the assistant fallback; with no workflow
  global the effective pipeline agent holds the role (the pipeline
  section is optional — an absent section resolves to the empty
  default: agent None, env empty). The effective
  launch env base is the key-wise merge of the effective pipeline.env
  with the workflow's global env — a workflow key overrides the
  same-named configuration key, untouched configuration keys survive;
  the CLI entries layer above the base and the engine-variable keys drop
  from it silently. The globals activate only through the run's
  workflow: with the layer off or no workflow resolved, the
  configuration values feed the same consumption points. Gate AI-review
  steps keep their own strict agent requirement — the global agent is
  never their fallback. The card form performs no global resolution —
  wrapper generation and launch layers are run-only surfaces.

  Collaboration delivery: the afm configuration write materializes the
  engine's collaboration plumbing from the artifacts the run already
  produces — the compiled flow, the effective workflow, and the parsed
  pipeline document. The section writes on EVERY launch, always headed
  by collaboration.runtime_context: wrapper and
  collaboration.hide_attach_helpers: true — the static
  execution-context decision (every command goga hands the engine,
  client and generated profiles alike, is an as-claude wrapper or a
  closure over one) and the static dashboard decision (helpers join a
  goga-managed run only through the authored plumbing — the
  workflow-file instructions and the pipeline-file stage declarations —
  never through dynamic dashboard attachment). The compiled flow is the
  single source of truth: the helper profiles are materialized exactly
  for the generated profile ids the flow references, so the two
  artifacts cannot diverge and no dead profile remains for an attachment
  removed by an assistant veto or a stage skip; without the artifacts
  the section stays the bare static head. Every command the write
  produces — the client wrapper and each profile command, wrapper or
  closure alike — is labeled in the top-level command_names map with the
  bare agent id of its underlying as-claude wrapper, so the dashboard
  never falls back to the file base name; the map is written only when
  at least one labeled command exists. A generated profile is exactly
  {title, command, delegate}: the title from the assistant name, the
  delegate permission from the delivery source, and the command resolved
  the stage-agent way — the source's agent, else the effective global
  pipeline agent; a name that resolves to nothing fails the launch with
  a pre-run error naming the assistant and its authoring site (the
  catalog, the stage whose attachment declares it, or the pipeline stage
  whose body declares it). A pipeline-declared assistant carries no
  delivery fields of its own: its delivery configuration comes from the
  workflow extension entry addressing its name (agent, env, delegate),
  and without one it launches under the effective global agent. An
  assistant carrying an env instruction is delivered through a generated
  sh closure whose path becomes the profile's command (a profile carries
  its own command and inherits none); closures are regenerated on every
  launch, so the authored configuration survives the per-launch rewrite
  by living in the workflow-file. The whole-run task budget is written
  as collaboration.limits.max_tasks only when the workflow carries a
  delegation block — the materialized value, 50 when the block omits it.
  The goga- profile prefix is the intended override channel: a
  user-authored same-named profile in the project layer deliberately
  replaces goga's plumbing, and the project-layer engine configuration
  is user territory goga never touches. goga neither reads nor writes
  the collaboration kill-switch — an environment that disables
  collaboration gets engine warnings and skipped helpers, and the run
  proceeds.

  Use `afm` for the collaboration configuration contract — the profile
  shape, the limits, and the config layers.
  Use `collaboration-emission` for the compiled flow surface the profile
  ids are read from.
  Use `assistants` for the authoring vocabulary of the delivered
  instructions.

  The stage script/command rewrite runs AFTER compilation as a targeted
  patch of the flow-file `compile_flow` already wrote: the compiler's
  direct serialization for env-free stages is untouched, keeping the flow
  output byte-identical for runs that declare no stage env (wrappers
  are generated and the file is patched only for stages that declare
  env; with none, the file is neither read nor rewritten).

  Activation: the run coordination and the card apply the profile
  through one channel set — the CLI --profile flag value, the
  GOGA_PROFILE value, and the decoded GOGA_HOME_PROFILES bundle; the
  card keeps reflecting what a run with the same flags would apply.
  When a profile resolves, the run coordination exports its name into
  the afm launch layer as GOGA_PROFILE — pipeline stages (and builds
  invoked inside the runtime) inherit the effective profile with no
  additional options. Use `load-workflow` and `profiles` for the
  loading chain and the activation rules.

  Launch feedback: the run coordination prints one stdout line —
  Pipeline running with workflow "<w>" and profile "<p>" — when a
  workflow resolved; without an effective profile the line names the
  workflow only; without a workflow no line prints.

---

"PipelineEntry(name: str, source: PipelineSource)":
  location: pipeline_entry.py
  annotations: |
    Describe a single pipeline-file discovered by `list_pipelines`: its `name`
    and where it comes from (`source`).

    `name`: pipeline name without extension (e.g. "deploy"); the .yml extension
            is implied and never stored here
    `source`: origin of the pipeline — `PipelineSource` enum value

    Build the data model with the standard library dataclasses module (NOT
    pydantic, per project convention; pydantic is treated as tech debt). Use
    @dataclass(kw_only=True) and validate `name` at construction time
    (raising ValueError on invalid input).

    Requirements:
    - Use @dataclass(kw_only=True) (per `convention`)
    - `name` must not contain path separators ("/", "\\") or the .yml extension
    - `name` must not be empty

  properties:
    "name -> str": |
      Pipeline name without extension.
    "source -> PipelineSource": |
      Origin of the pipeline: `PipelineSource`.PROJECT for project-level
      <cwd>/.goga/pipelines/, `PipelineSource`.USER for user-level ~/.goga/pipelines/.

"PipelineSource()":
  location: pipeline_entry.py
  annotations: |
    str-backed Enum declaring the origin of a pipeline-file.

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

  properties:
    "PROJECT = \"project\"": |
      Origin = project-level <cwd>/.goga/pipelines/.
    "USER = \"user\"": |
      Origin = user-level ~/.goga/pipelines/.

"PipelineSummary(name: str, source: PipelineSource, description: str, display_name: str = \"\")":
  location: pipeline_summary.py
  annotations: |
    Describe one row of the overview: the discovered pipeline name, its
    origin, its DSL header description, and the authored header name.

    `name`: pipeline name without extension
    `source`: origin of the pipeline — `PipelineSource` value
    `description`: pipeline description taken from the DSL header
    `display_name`: authored pipeline name from the DSL header; may differ
                    from `name`; defaults to an empty string

    Build with the standard library dataclasses module and
    @dataclass(kw_only=True) (per `convention`).

    Requirements:
    - Use @dataclass(kw_only=True)
    - `name` follows the `PipelineEntry` validation rules — non-empty, no
      path separators, no .yml suffix
    - `display_name` defaults to an empty string — constructions without it
      remain valid

  properties:
    "name -> str": |
      Pipeline name without extension.
    "source -> PipelineSource": |
      Origin of the pipeline.
    "description -> str": |
      Description from the DSL header.
    "display_name -> str": |
      Authored pipeline name from the DSL header; may differ from the
      discovered stem.

"PipelineCard(name: str, description: str, stages: list[CardStage], provenance: list[str] = [])":
  location: pipeline_card.py
  annotations: |
    Describe the card of a single pipeline: the authored name and
    description, the ordered stage rows, and the tools whose contributions
    shaped the composition.

    `name`: pipeline name from the DSL header
    `description`: pipeline description from the DSL header
    `stages`: stage rows in execution order — one per compiled stage
    `provenance`: the tools whose contributions committed into the
                  composition, in enumeration order; empty when none
                  contributed

    Build with the standard library dataclasses module and
    @dataclass(kw_only=True) (per `convention`).

    Requirements:
    - Use @dataclass(kw_only=True)
    - `provenance` defaults to an empty list — constructions without it
      remain valid

  properties:
    "name -> str": |
      Pipeline name from the DSL header.
    "description -> str": |
      Pipeline description from the DSL header.
    "stages -> list[CardStage]": |
      Stage rows in execution order; loop-expanded copies appear as
      separate rows.
    "provenance -> list[str]": |
      The tools whose contributions committed into the composition, in
      enumeration order; empty when none contributed.

"CardStage(id: str, title: str)":
  location: pipeline_card.py
  annotations: |
    Describe one stage row of the card.

    `id`: stage identifier
    `title`: stage display title

    Build with the standard library dataclasses module and
    @dataclass(kw_only=True) (per `convention`).

    Requirements:
    - Use @dataclass(kw_only=True)

  properties:
    "id -> str": |
      Stage identifier.
    "title -> str": |
      Stage display title — the display name of the compiled `FlowStage`.

"list_pipelines(project_dir: Path, user_dir: Path) -> entries: list[PipelineEntry]":
  location: list_pipelines.py
  annotations: |
    Discover pipeline files across two source directories and return them as
    `entries`: a list of `PipelineEntry`-s.

    `project_dir`: project-level pipelines directory (typically <cwd>/.goga/pipelines/)
    `user_dir`: user-level pipelines directory (typically ~/.goga/pipelines/)
    `entries`: list of `PipelineEntry`-s, one per unique pipeline name

    Algorithm:
    1. Scan flat *.yml files (non-recursive) in `project_dir`; for each valid
       stem, record a `PipelineEntry` with the name set to the stem and source
       set to `PipelineSource`.PROJECT. Skip stems that fail `PipelineEntry`
       validation (invalid chars, .yml suffix, empty) silently.
    2. Scan flat *.yml files (non-recursive) in `user_dir`; for each valid stem
       not already present from step 1, record a `PipelineEntry` with source
       set to `PipelineSource`.USER.
    3. Return the combined `entries` list.

    Apply the `convention` practice for the filesystem scanning code
    (relative imports, logging, docstring style).

    Requirements:
    - Scan only the top level of each directory — do not descend into subdirectories
    - Drop the .yml extension when forming the entry name
    - A missing source directory is treated as empty (no error)
    - Skip stems that fail `PipelineEntry` validation silently — they are not pipelines

    Constraints:
    - Do not parse or validate the contents of pipeline files — only their names
      matter here
    - When a name exists in both sources, the project source wins (no duplicate
      entries)

"describe_pipelines(project_dir: Path, user_dir: Path) -> summaries: list[PipelineSummary]":
  location: describe_pipelines.py
  annotations: |
    Compose the overview of every discovered pipeline: each entry paired with
    the authored name and description from its DSL header.

    `project_dir`: project-level pipelines directory (absolute)
    `user_dir`: user-level pipelines directory (absolute)
    `summaries`: one `PipelineSummary` per discovered pipeline, in discovery
                 order

    Apply `convention` for filesystem reading, logging, and docstring style.

    Algorithm:
    1. Discover entries via `list_pipelines`
    2. For each entry: compose the pipeline-file path inside its source
       directory, read the file, parse it via `parse_dsl`, and take the header
       name and description
    3. Build a `PipelineSummary` from the entry name, entry source, the
       header description, and the authored header name (the summary
       display_name field)
    4. Return the summaries in discovery order

    Requirements:
    - The description and the authored header name (summary display_name
      field) come from the DSL header; the name is the discovered stem
    - A damaged pipeline file (unreadable or structurally invalid) aborts the
      whole overview with a readable error — no partial list, no silent
      skips, no placeholder markers
    - Read the filesystem only; write nothing

    Constraints:
    - Do not sort or filter the summaries — discovery order is preserved
    - Do not compile pipeline files — the overview reads headers only
    - Do not extend the discovery contract — names and sources come from
      `list_pipelines` unchanged

"resolve_workflow(pipeline_name: str, workflow_name: str | None, no_workflow: bool, cli_profile: str | None = None, env_profile: str | None = None, home_profiles: dict[str, dict[str, Any]] | None = None) -> workflow: LoadedWorkflow | None":
  location: resolve_workflow.py
  annotations: |
    Resolve the optional workflow for a pipeline: the single rule set shared
    by run coordination and the card.

    `pipeline_name`: pipeline name without extension (the basename auto-match
                     key)
    `workflow_name`: optional explicit workflow name (without the .yml
                     extension)
    `no_workflow`: when True, workflow application is disabled
    `cli_profile`: the CLI activation channel value (the --profile flag),
                   or None
    `env_profile`: the environment activation channel value (the
                   GOGA_PROFILE engine variable), or None
    `home_profiles`: the decoded home bundle (decode_home_profiles result),
                     or None (treated as empty)
    `workflow`: the loaded `LoadedWorkflow` — the parsed `WorkflowDocument`
                plus the active profile — or None when no workflow applies

    Apply `load-workflow` for the loading chain and the parse contract.
    Apply `profiles` for the activation rules.
    Apply `convention` for docstring style.

    Algorithm:
    1. When `no_workflow` is True — return None
    2. Compose the workflow-file path under <cwd>/.goga/workflows/: named
       `workflow_name`.yml when provided (an empty string counts as not
       provided), otherwise the pipeline basename `pipeline_name`.yml
    3. Containment guard: when the composed path resolves outside the
       <cwd>/.goga/workflows/ directory (a ".." segment or an absolute
       prefix in the name) — return None (silent miss; workflow files are
       project-only, never resolved into the wider filesystem)
    4. When the composed file exists — load it via the workflow-cell
       loading chain (per `load-workflow`) with
       the activation channels (`cli_profile`, `env_profile`,
       `home_profiles`) and return the resulting `LoadedWorkflow`;
       structural errors propagate with their readable messages
    5. Otherwise — return None (silent miss; an absent workflow-file is not an
       error)

    Requirements:
    - The resolution rules are exactly: disabled → None; explicit name → that
      file (an empty string counts as no name — the basename auto-match
      applies); otherwise basename auto-match; a name escaping the workflows
      directory → None; missing file → None
    - Workflow files are project-only — the directory resolves from the
      current working directory, and a composed path outside it is a silent
      miss, never a traversal into the wider filesystem
    - Consumers read the loaded value's parts: .document (amendment
      machinery, compilation) and .profile (the feedback line)

    Constraints:
    - Do not treat a missing workflow-file as an error — the auto-match is
      opt-in
    - Do not validate workflow contents beyond what the loading chain
      enforces
    - Do not read environment variables — callers own their flag and
      activation sources

"order_stages(stages: list[FlowStage]) -> ordered: list[FlowStage]":
  location: order_stages.py
  annotations: |
    Order flow stages for execution: a topological sort over the depends_on
    references of each `FlowStage`.

    `stages`: flow stages in declaration order
    `ordered`: the same stages ordered for execution

    Apply `convention` for docstring style.

    Algorithm:
    1. Build the ordering graph from the depends_on references of each
       `FlowStage`
    2. Repeatedly emit, among the stages whose references are all already
       emitted, the one earliest in declaration order
    3. Treat a reference naming no stage in the list as satisfied — dangling
       references are the flow executor's concern, not an ordering error
    4. When no remaining stage qualifies (a reference cycle), append the
       remaining stages in declaration order

    Requirements:
    - Deterministic — declaration order is the tie-break at every step and
      the fallback under cycles
    - The result contains every input stage exactly once — none dropped,
      none duplicated
    - Pure — the input list and its stages are not mutated

    Constraints:
    - Do not validate references for dangling ids, cycles, or duplicates
    - Do not rewrite depends_on — ordering only

"describe_pipeline(name: str, project_dir: Path, user_dir: Path, workflow: str | None, no_workflow: bool, profile: str | None = None, skip: list[str] | None = None) -> card: PipelineCard":
  location: describe_pipeline.py
  annotations: |
    Compose the card of a single pipeline: name, description, the
    post-workflow stage composition as it would execute, and the tools
    that contributed to it.

    `name`: pipeline name without extension
    `project_dir`: project-level pipelines directory (absolute)
    `user_dir`: user-level pipelines directory (absolute)
    `workflow`: optional explicit workflow name (without the .yml extension)
    `no_workflow`: when True, workflow application is disabled
    `profile`: the CLI activation channel value (the --profile flag), or
               None; the card applies the profile through the same channels
               a run applies (the same environment reads)
    `skip`: stage names to skip — merged exactly as a run with the same flags
            merges them; None and an empty list both mean no skip
    `card`: `PipelineCard` — the pipeline name and description from the DSL
            header, one `CardStage` per stage in execution order, and the
            provenance of the amendment

    Apply `compile-flow` for the compilation contract and the documents tuple.
    Apply `checkpoints` for the amendment delivery of the pipeline hooks
    zone.
    Apply `topic-paths` for the work identity resolution behind the
    amendment facts.
    Apply `convention` for docstring style and intra-package imports.

    Algorithm:
    1. Discover entries via `list_pipelines` and locate the matching name;
       on no match report the missing pipeline with a readable error
    2. Resolve the workflow via `resolve_workflow` with the pipeline name,
       the workflow flags, and the activation channels (the `profile`
       parameter, the GOGA_PROFILE value, and the decoded home bundle)
    3. Apply the `skip` names via `apply_skip_stages` onto the resolved
       workflow (None/empty — no skip)
    4. Resolve the amendment facts (the `PipelineIdentity` — the authored
       header name and description read via `parse_dsl` from the
       pipeline-file text; the `WorkflowDecision`; and the `WorkIdentity` —
       the current branch via `resolve_current_branch_name`, the literal
       "unknown" when it resolves None; the hosting topic slug and year via
       `resolve_topic_dir` when its directory exists, the branch-only form
       otherwise) and, unless the decision is disabled, deliver the
       amendment via the `PipelineHooks` checkpoint surface with the merged
       workflow and the operation's resolved profile (the `LoadedWorkflow`
       profile of step 2 — None when no workflow resolved) — receiving the
       overlay result; a disabled decision delivers nothing and the overlay
       is the passthrough `WorkflowOverlay` of the merged workflow
    5. Compile the pipeline-file via `compile_flow` into a temporary flow-file
       located in a system temporary directory — outside the project
       directory and outside every runtime directory — with the overlay
       workflow, and receive the documents tuple
    6. Order the compiled stages via `order_stages`
    7. Build the card: name and description from the parsed pipeline document
       header; one `CardStage` per ordered stage — id from the `FlowStage`
       id, title from the `FlowStage` name (the display label); the card
       provenance from the overlay
    8. Discard the temporary flow-file and return the card

    Requirements:
    - The stage composition equals the composition a run of the same pipeline
      with the same workflow, profile, and skip flags would execute — the
      same amendment layer with the same precedence and the same compilation
      machine produce both; the card/run equivalence is structural — the
      card never generates the per-stage env wrappers (an env-declaring
      stage appears in the card exactly as it composes in a run with the
      same flags; wrapper generation and its pre-launch failure modes are
      run-only)
    - The card applies the profile through the same channels a run applies
      — the same environment reads (GOGA_PROFILE, GOGA_HOME_PROFILES) feed
      the resolution; no feedback line prints in card form
    - The card names the contributing tools — the provenance is empty when
      nothing contributed
    - An explicit workflow disable turns the layer off — no delivery
      happens and the raw authored DSL composes
    - A silent auto-match miss keeps the layer active — the delivery runs
      onto the empty base
    - The card delivers the amendment with the resolved profile exactly as
      the run form does — the same fact on every tool's view and the same
      rendering of contributed strings; the card's merged composition
      equals what a run with the same flags executes
    - Loop-expanded stage copies appear as separate stages
    - The CLI skip names apply through the same in-memory merge a run applies
      and are reflected in the stage list; workflow-file skip directives
      apply through the shared compilation machine — both compose exactly
      as a run with the same flags
    - The temporary flow-file lives outside the project and runtime
      directories and is removed afterwards
    - The card name and description are the authored DSL header values

    Constraints:
    - Do not launch afm and do not run any stage — the card is read-only
    - Do not emit run events in card form
    - Do not write into the project directory or any runtime directory
    - Do not re-parse the pipeline-file for the card fields — the card's
      name and description come from the documents tuple; the single early
      `parse_dsl` read of step 3 serves the amendment facts only
    - Do not reorder stages beyond `order_stages`

"run_pipeline(name: str, project_dir: Path, user_dir: Path, port: int, workflow: str | None = None, no_workflow: bool = False, profile: str | None = None, skip: list[str] | None = None, parallel: int | None = None, fail_on_error: bool = False) -> exit_code: int":
  location: run_pipeline.py
  annotations: |
    Load and amend the project configuration, resolve a pipeline name to an
    absolute file path via `list_pipelines`, resolve an optional workflow via
    `resolve_workflow` from the CLI-provided decision under the profile
    activation context, merge the CLI skip
    names via `apply_skip_stages`, deliver the workflow amendment through the
    pipeline hooks zone, compile the pipeline-file (extended by the effective
    workflow) into an afm flow-file at runtime via `compile_flow`, apply the
    per-stage env wrappers as a targeted post-compile patch of the written
    flow-file, apply the per-step gate env wrappers the same way, materialize
    the four agent prompt files (the defaults plus the inline overrides of
    the resolved `PipelineRoles`) into the
    runtime prompts directory, write the afm configuration file via
    `write_afm_config` with the compiled flow document and the effective
    workflow document, emit the run-creation facts, launch afm through
    `run_flow` with the composed launch environment layer, and emit the
    run-completion facts on its return. This is the run coordination routine
    — it performs the configuration load-and-amend, discovery, workflow
    resolution, path resolution, fact resolution, amendment delivery,
    compilation, wrapper application, prompt materialization, and afm
    configuration authorship;
    the actual subprocess execution lives in `run_flow`.

    `name`: pipeline name without extension
    `project_dir`: project-level pipelines directory (same meaning as in `list_pipelines`)
    `user_dir`: user-level pipelines directory (same meaning as in `list_pipelines`)
    `port`: TCP port forwarded to afm run --port via `run_flow`
            (resolved by the host-side caller: the --port CLI value when
            the user pinned one, else an allocated free ephemeral port)
    `workflow`: optional explicit workflow name (without the .yml extension) —
                the CLI decision from the -w flag; None with `no_workflow`
                unset resolves the basename auto-match
    `no_workflow`: when True, workflow application is disabled — the CLI
                   decision from the --no-workflow flag
    `profile`: the CLI activation channel value — the -p/--profile flag
               decision; composes with the GOGA_PROFILE value and the
               workflow default per the shared activation precedence
    `skip`: stage names to skip — the CLI decision from the repeatable -s
            flags; None and an empty list both mean no skip
    `parallel`: optional cap on concurrently executing stages, forwarded to
                `run_flow` as its max_parallel argument. When None (default) —
                afm runs unbounded (run_flow omits --max-parallel). Read from
                the in-container CLI --parallel flag
    `fail_on_error`: the CLI fail-fast decision from the --fail-on-error
                flag of the in-container run subcommand; forwarded to
                `run_flow` as its exit_on_fail argument — a failed stage
                ends the run with the engine's failure exit code.
                False (default) changes nothing
    `exit_code`: 0 on success, non-zero on error (missing pipeline, missing
                 binary, afm failure, structural DSL error, workflow parse
                 error, materialization error, configuration load or delivery
                 failure). 127 means afm is not on PATH inside the container.

    Apply `convention` for error-handling style and docstring formatting.
    Apply `project-configuration` for the authored configuration load.
    Apply `checkpoints` for the workflow amendment delivery and the two
    emissions of the pipeline hooks zone.
    Apply `parse-workflow` for the workflow-file contract consumed through
    `resolve_workflow`.
    Apply `compile-flow` for the compilation step contract and the documents
    tuple.
    Apply `default_prompts` for resolving the packaged default prompt files.
    Apply `default_skin` for resolving the packaged dashboard skin and its
    materialization target.
    Apply `afm` for the written afm configuration-file contract.
    Apply `resolve-wrapper-path` for the agent command resolution inside
    `write_afm_config`.
    Apply `run-flow` for the subprocess launch contract and its environment
    layer parameter.
    Apply `extra-env-carriage` for the CLI entries carriage of the launch
    layer.
    Apply `topic-paths` for the work identity resolution and
    `topic-statuses` for the status facts of the run events.

    Algorithm:
    1. Load the authored project configuration via `load_project_config` —
       a load failure returns with a clean error before any work; no events
       fire
    2. Deliver the config amendment via the `ConfigHooks` checkpoint surface
       with the authored configuration — the first failing tool stops the
       run with a clean error naming the tool and the action (no events
       fire, afm never launches); print the amendment summary lines of the
       `ConfigOverlay` to stderr; every downstream step consumes the
       effective configuration of the `ConfigOverlay`
    3. Discover pipelines via `list_pipelines` and find the entry whose name
       matches
    4. If no match — report that the pipeline is missing and return a
       non-zero exit code
    5. Build the absolute pipeline path from the matching entry's source
       directory and the pipeline name
    6. Resolve the in-container runtime directory from the AFM_DIR
       environment variable; when unset raise a readable "AFM_DIR not set"
       error; resolve the value to an absolute path
    7. Compose the output flow path inside that directory
    8. Resolve the workflow via `resolve_workflow` with the pipeline name and
       the `workflow` / `no_workflow` parameters — the CLI decision arrives
       as explicit arguments, never from the environment — under the
       activation context: decode the home bundle via `decode_home_profiles`
       from the GOGA_HOME_PROFILES engine variable (per
       `home-profiles-carriage`; a damaged bundle is one clean error here —
       no events fire, afm never launches) and read the GOGA_PROFILE value
       once; both feed the resolution together with the `profile` parameter
    9. Print the launch feedback line to stdout when a workflow resolved —
       Pipeline running with workflow "<name>" and profile "<profile>" when
       the loaded workflow carries an effective profile, Pipeline running
       with workflow "<name>" without one; without a workflow no line
       prints
    10. Apply the `skip` names via `apply_skip_stages` onto the resolved
        workflow's document (None/empty — no skip)
    11. Resolve the amendment facts from the operation's own data: the
        `PipelineIdentity` (discovered name; authored header name and
        description read via `parse_dsl` from the pipeline-file text; entry
        source), the `WorkflowDecision` (disabled /
        explicit / auto-match / silent-miss with the resolved name), and the
        `WorkIdentity` (current branch via `resolve_current_branch_name`,
        the literal "unknown" when it resolves None; the hosting topic slug
        and year via `resolve_topic_dir` when its
        directory exists, the branch-only form otherwise)
    12. Unless the decision is disabled, deliver the amendment via the
        `PipelineHooks` checkpoint surface with the authored workflow after
        the skip merge and the operation's resolved profile — the profile
        of the loaded workflow (`LoadedWorkflow` profile: a
        `ResolvedProfile`, or None when no workflow resolved): the views
        read it as their profile fact and the delivery renders the
        committed contributions' strings with its content — receiving the
        overlay result; a disabled decision delivers nothing (the layer is
        off) and the overlay is the passthrough `WorkflowOverlay` of the
        merged workflow
    13. Resolve the in-container project name via `resolve_project_name`
        (None when the git origin remote is unavailable). Compile via
        `compile_flow` with the overlay workflow (the resolved workflow when
        the layer is off), the in-container project root (Path.cwd()) as
        root_dir, and the project name; receive the documents tuple;
        structural errors propagate unchanged
    14. Resolve the effective global agent: the agent field of the
        overlay workflow document when it carries one, otherwise the
        effective configuration's pipeline.agent (an absent pipeline
        section resolves to the empty default before any read — the
        section is optional, the workflow globals hold the run
        settings). The resolved value
        feeds the per-stage wrapper generation (its exec fallback), the
        afm configuration write (the client command and the assistant
        fallback), and nothing else
    15. Apply the per-stage env wrappers via `apply_stage_env_wrappers`
        over the compiled stages — the overlay workflow document, the
        effective global agent (resolved at step 14), and the composed
        flow path — a
        post-compile script/command rewrite of exactly the env-declaring
        stages in the flow-file `compile_flow` already wrote (a script
        stage wraps its script payload, every other stage its resolved
        agent command); a no-op that touches no
        file when none declare env. Then apply the per-step gate env
        wrappers via `apply_gate_env_wrappers` over the same compiled
        stages and flow path — the same closure delivery for the env maps
        authored on gates check steps (both step kinds); a no-op that
        touches no file when no step declares env
    16. Materialize agent prompts atomically (validate-all, then wipe, then
        write): resolve the default prompts directory per `default_prompts`;
        for each overridable role (planner, executor, reviewer) require an
        inline override from the documents tuple or an existing default file
        (stem via `translate_role`); require the summary default; then reset
        <AFM_DIR>/prompts/ and write exactly four files — overrides where
        present, defaults otherwise, summary always from the default
    17. Author the afm home: write the afm configuration file via
        `write_afm_config` with the
        effective global agent (resolved at step 14), the compiled flow
        document, the
        effective workflow document (the overlay workflow; the resolved
        workflow when the amendment layer is off; None when no workflow
        resolved), and the parsed pipeline document (the compile step's
        returned PipelineDocument — the carrier of the pipeline-file
        stage-body assistant declarations) as the pipeline parameter of
        `write_afm_config` —
        the whole file at the fixed in-container home path,
        before the launch; the collaboration section (always headed by
        runtime_context: wrapper and hide_attach_helpers: true)
        materializes its profiles from
        the documents, and a collaboration pre-run error (an
        unresolvable assistant agent name or an illegal env key) fails
        the launch with a clean error naming the assistant and its
        authoring site before any events fire; then materialize the
        packaged goga dashboard skin via `materialize_afm_skin` (per
        `default_skin`) into /home/goga/.afm/skins/goga/ — the same
        failure window (no events have fired), a missing packaged skin
        failing the launch with a clean error
    18. Order the compiled stages via `order_stages` and build one
        `CompositionStage` per ordered stage — id from the `FlowStage` id,
        title from the `FlowStage` name
    19. Resolve the work statuses — the maximal present statuses of the
        hosting topic via `assemble_status_scale` and `resolve_topic_status`;
        an empty list in the branch-only form
    20. Compose the afm launch environment layer per `extra-env-carriage`:
        decode the CLI entries payload via `decode_extra_env` from the
        dedicated engine variable; apply the decoded entries above the
        effective launch env base — the key-wise merge of the effective
        pipeline.env task env layer with the overlay workflow's global
        env (a workflow key overrides the same-named configuration key,
        untouched configuration keys survive); add
        GOGA_PROFILE=<effective profile name> when a profile resolved
        — the afm subprocess and its stages inherit it, so a build
        invoked inside the pipeline runtime picks the same profile up
        through its env channel with no additional options (the
        workflow travels via GOGA_WORKFLOW of the launch environment;
        the launcher env-file line stays ambient-only); drop the keys
        of the composed base and the CLI entries colliding with the
        engine set — GOGA_PROFILE, GOGA_WORKFLOW, GOGA_HOME_PROFILES,
        GOGA_EXTRA_ENV, AFM_DIR, AFM_DOCKER_FILE_ROOTS, HTTP_PROXY,
        HTTPS_PROXY, NO_PROXY — silently, the inherited launch values
        stand. A damaged payload is one clean error here — no events
        fire, afm never launches
    21. Emit the run-creation facts via the checkpoint surface immediately
        before the launch: the identity, the decision, the overlay, the
        composition, the work identity, the statuses, and the runtime dir as
        a posix string
    22. Launch afm via `run_flow` with the compiled flow-file path, `port`,
        max_parallel=`parallel`, exit_on_fail=`fail_on_error`, and the
        composed layer as its env parameter
        — the process environment of the container stays untouched
    23. On every return of `run_flow` — zero, non-zero, and spawn failures
        alike — recompute the work statuses at the completion moment and
        emit the run-completion facts with the actual exit code
    24. Return the exit code returned by `run_flow`

    Requirements:
    - The environment reads are exactly four: AFM_DIR, the CLI entries
      payload engine variable, GOGA_PROFILE, and GOGA_HOME_PROFILES
      (decoded via `decode_home_profiles`; a damaged bundle is one clean
      error before events) — the workflow decision, the profile flag, and
      the skip names arrive as parameters
    - Print the launch feedback line to stdout when a workflow resolved —
      with the profile name when one resolved, without it otherwise;
      without a workflow no line prints
    - After `compile_flow`, the per-stage env wrappers apply as a targeted
      post-compile patch of the written flow-file — only for env-declaring
      stages; an env-free run keeps the flow-file byte-identical (neither
      read nor rewritten). The per-step gate env wrappers apply the same
      way, immediately after — only for env-declaring gate steps; a run
      whose gates declare no step env keeps the flow-file byte-identical
      (neither read nor rewritten)
    - When a profile resolved, the afm launch layer carries
      GOGA_PROFILE=<effective profile name> — the afm subprocess and its
      stages inherit the effective profile; keys of the composed base
      and the CLI entries colliding with the engine set (GOGA_PROFILE,
      GOGA_WORKFLOW, GOGA_HOME_PROFILES, GOGA_EXTRA_ENV, AFM_DIR,
      AFM_DOCKER_FILE_ROOTS, HTTP_PROXY, HTTPS_PROXY, NO_PROXY) are dropped
      silently from the layer, the inherited launch values stand
    - The effective global agent resolves once per run from the overlay
      workflow document's agent field, falling back to the effective
      pipeline.agent; it feeds exactly the three consumption points
      and nothing else; with the workflow layer off or no workflow
      resolved the effective pipeline.agent holds the role; the
      pipeline section is optional — an absent section normalizes to
      the empty PipelineConfig right after the config overlay
    - The launch env base is the key-wise merge of pipeline.env with
      the workflow global env (workflow wins per key, config keys
      survive); CLI entries stay above; engine-variable keys still
      drop silently
    - A gate AI-review step carries its own agent requirement — the
      global agent never backs a gate step
    - Always pass the absolute pipeline path to `compile_flow` — never the
      bare name
    - Always pass the absolute compiled flow path to `run_flow` — never the
      bare name or the DSL path
    - Always forward `port` to `run_flow`; forward `parallel` (None
      propagates — no --max-parallel flag)
    - Always forward fail_on_error to run_flow (exit_on_fail); False
      propagates — no flag, no env variable
    - A configuration load failure and a configuration delivery failure fire
      no events — the return happens before the pipeline checkpoints; afm
      never launches on a delivery failure
    - The amendment summary lines of the config delivery print to stderr
      (nothing when empty)
    - Docker-level fields of the effective configuration (image, proxy,
      hosts) are consumed nowhere in-container — applied-but-unconsumed,
      silently, no warning
    - `no_workflow` takes precedence over `workflow` (the host-side launcher
      rejects the combined use; the precedence is defensive)
    - Workflow resolution and parsing go through `resolve_workflow` — one
      rule set shared with the card
    - The amendment delivery and its precedence are the same rule set the
      card applies — the same flags compose the same overlay in both forms
    - The amendment delivery carries the operation's resolved profile —
      the loaded workflow's profile, or None when no workflow resolved;
      one resolved value feeds every tool's view and the contribution
      rendering, identically in the run and the card forms
    - A missing workflow-file is a silent miss, not an error; the layer
      stays active onto the empty base
    - An explicit disable turns the layer off — no delivery happens and the
      raw authored DSL composes
    - Skip merges onto any resolved workflow and applies to a workflow-less
      pipeline; unknown skip names surface as the compiler's structural
      error
    - The branch, topic, and status facts resolve in the operation before
      the delivery — the checkpoints read nothing
    - The "run_created" action fires immediately before the runner launch;
      the "run_completed" action fires on every launch-attempt return path
      — no exit path skips the completion emission
    - A missing pipeline, a structural composition error, and a
      configuration load or delivery failure fire no events — the return
      happens before the checkpoints
    - A damaged CLI entries payload is one clean error before the
      run-creation facts — no events fire, afm never launches
    - The runtime dir fact is the resolved AFM_DIR path as a posix string
    - With no tool packages installed the overlay is the passthrough — the
      compiled workflow, the prompts, and the output behave exactly as with
      the amendment layer absent
    - <AFM_DIR>/prompts/ contains exactly four files after step 15 succeeds;
      validation precedes any wipe or write — atomicity guarantees no
      partial state on disk
    - The afm configuration file is written exactly once per run, before
      the launch, via `write_afm_config`
    - The afm configuration write receives the compiled flow document and
      the effective workflow document — the profile set derives from the
      flow's references, the declarations from the workflow; a
      collaboration pre-run error fires no events and afm never launches
    - The packaged goga dashboard skin is materialized exactly once per
      run, immediately after the configuration write and before any run
      event fires, via `materialize_afm_skin`; a missing or empty
      packaged skin is one clean pre-run error — no events fire, afm
      never launches, and the previously materialized skin survives
    - The launch layer applies to the afm subprocess only, through the env
      parameter of `run_flow` — engine-variable keys never enter the layer,
      and the container's process environment is never mutated
    - Inline prompt overrides come exclusively from the documents tuple
      header roles; the override is a full file replacement — no merge, no
      concatenation
    - Default prompt files resolve from the installed package location per
      `default_prompts` — never from AFM_DIR, CWD, or an environment
      variable
    - root_dir resolution is CWD-based (Path.cwd() resolves to /workspace
      inside the goga container); project_name resolves in-container via
      `resolve_project_name`
    - Do not mutate the documents tuple returned by `compile_flow` — read
      the inline prompt overrides as-is

    Constraints:
    - Do not load the configuration outside `load_project_config` followed
      by the checkpoint delivery — one load, one delivery, one effective
      configuration
    - Do not invoke afm directly outside `run_flow`
    - Do not invoke the compiler outside `compile_flow`
    - Do not invoke the workflow loading chain outside `load_workflow`
    - Do not allocate the port — the caller allocates it
    - Do not default `parallel` — None means unbounded
    - Do not accept relative `project_dir` or `user_dir`
    - Do not mask or wrap exceptions from `compile_flow` or the workflow
      chain — structural errors (`StructuralError`,
      `WorkflowSyntaxError`) propagate with their readable messages
    - Do not resolve git or topic facts inside a hook delivery — the
      operation owns the resolution
    - Do not skip the completion emission on any launch-attempt return path
    - Do not write prompts inside the project directory or /workspace —
      always <AFM_DIR>/prompts/
    - Do not write the afm configuration anywhere but the fixed in-container
      home path — never in the project directory, never in the afm state
      directory
    - Do not materialize the skin anywhere but the fixed in-container home
      skins path — never in the project directory, never in the afm state
      directory, never under /workspace
    - Do not write inline prompt overrides into the compiled flow-file
    - Do not delete skipped stages or rewrite depends_on — `compile_flow`
      does both
    - Do not write or generate a workflow-file for skip — the merge is
      in-memory only
    - Do not mutate the process environment — composed layers travel only
      through the env parameter of `run_flow`
    - Do not print configuration values — summary lines carry the tool, the
      path, set or forced only

"write_afm_config(agent: str | None, flow: FlowDocument | None = None, workflow: WorkflowDocument | None = None, pipeline: PipelineDocument | None = None) -> config_path: Path":
  location: afm_config.py
  annotations: |
    Write the whole afm configuration file in-container before the afm
    launch: the agent client command resolved from the effective global
    agent, the five static launcher-side fields, goga's own observer hook
    entry, the command-name label map, and the collaboration section — the
    static runtime-context head with the hidden attach-helpers toggle, the
    generated helper profiles, and the whole-run task budget.

    `agent`: the effective global agent — the workflow global agent of
             the effective workflow when it carries one, otherwise the
             authored pipeline.agent as amended by the config
             delivery; None when neither resolves
    `flow`: the compiled flow document (a `FlowDocument`) —
            the source of the generated profile ids (the binding of every
            team member and of every stage attachment the flow carries);
            None writes no collaboration profiles (the section head still
            writes)
    `workflow`: the effective workflow document — the source of each
                referenced assistant's declaration (agent, delegate,
                env) and of the delegation block; None when no workflow
                resolved — the pipeline declarations remain the sole
                profile source and the task budget stays unwritten
    `pipeline`: the parsed pipeline document (a `PipelineDocument`) —
                the carrier of the pipeline-file stage-body assistant
                declarations. Together with `flow` and `workflow` it
                completes the delivery resolution: a pipeline-declared
                name resolves its delivery fields from the workflow
                extension entry addressing it, and its authoring site
                (the pipeline stage whose body declares it) is named by
                strict pre-run errors. None when no pipeline document is
                at hand — the section head still writes and no
                pipeline-declared profile resolves
    `config_path`: the fixed in-container path of the written file

    Apply `convention` for docstring style and intra-package imports.
    Apply `afm` for the configuration-file contract — the field set, the
    fixed home path, the per-stage override relationship, the
    lifecycle-hooks registration of the observer hook entry, the
    collaboration runtime-context, hide-attach-helpers, profile, and limits
    contract, and the command-name label map.
    Apply `resolve-wrapper-path` when resolving the client agent command
    and every generated profile command.
    Apply `collaboration-emission` for the compiled flow surface the
    profile ids are read from.
    Apply `assistants` for the authoring vocabulary of the delivered
    instructions.

    Algorithm:
    1. Resolve the absolute wrapper path via `resolve_wrapper_path` — only
       when `agent` is not None
    2. Compose the base content: the client command carrying the resolved
       absolute wrapper path (never a bare agent name) — written only when
       an agent resolved, omitted otherwise so per-stage workflow agents
       or the binary's own defaults cover the absent global default; the
       FIVE static fields — the disabled browser launch, the disabled
       internal proxy provider, the in-container prompts directory, the
       disabled dashboard stage-addition (add_stage.enabled false — the
       stage set presented to the engine stays exactly the compiled
       pipeline), and the engine's custom skin directory (skin_dir
       /home/goga/.afm/skins/goga — served wholesale as the active skin
       while it holds index.css; the engine-builtin theme is the fallback
       when it does not; the run coordination materializes the packaged
       skin there per `default_skin`); and the observer hook entry — the
       stable id goga, the in-container hook command of this package's
       CLI, the all-events subscription, the inherited environment, and
       the afm default timeout and retries
    3. Compose the collaboration section — ALWAYS written, headed by
       collaboration.runtime_context = wrapper (the static
       execution-context decision: every command goga hands the engine is
       an as-claude wrapper or a closure over one) and
       collaboration.hide_attach_helpers = true (the static dashboard
       decision: the run's dynamic attach-helpers entry point stays
       hidden — helpers join a goga-managed run only through the authored
       plumbing). When `flow` is not None and at least one of `workflow`
       and `pipeline` is not None —
       materialize the rest of the
       plumbing under the head:
       1. Collect the referenced profile ids: the profile binding of
          every `FlowTeamMember` of the flow plus the profile binding of
          every stage attachment entry (`FlowAssistant`) of the flow
       2. For each referenced id, locate the assistant's delivery source
          by name across the effective namespace — the workflow's
          assistant declarations (the catalog plus every full inline
          declaration of the stages block) and the pipeline declarations
          the `pipeline` document carries:
          - a workflow catalog or inline declaration supplies agent,
            delegate, and env as authored
          - a pipeline declaration carries no delivery fields: the
            workflow entry addressing the name (its extension entry)
            supplies agent, delegate, and env; the pipeline stage whose
            body declares the name is the authoring site
          - a name resolving to no declaration is a caller-side
            inconsistency (compilation validated the flow) — one strict
            pre-run error naming the assistant
       3. Resolve each profile's command: when the declaration carries
          a NON-EMPTY effective env map (not None and not empty — an
          explicitly cleared env is no env) — validate every declared key as a legal
          environment variable name BEFORE writing any file (an illegal
          key is one strict pre-run error naming the assistant and the
          key), generate the sh closure in a container-local temp
          directory (owner-only access) exporting the env values and
          exec-ing the resolved target wrapper, and the closure path
          becomes the command; otherwise the wrapper of the declaration's
          agent, else the wrapper of the effective global agent (`agent`);
          no agent resolves at all — one strict pre-run error naming
          the assistant and its authoring site (the catalog, the stage
          whose attachment declares it, or the pipeline stage whose body
          declares it), raised before the file is written; the effective
          delegate materializes False when None
       4. Write collaboration.profiles.<id> = {title: <name>, command:
          <resolved>, delegate: <declaration delegate>} — nothing else in
          the profile
       5. While resolving each profile, collect the command-name labels:
          when the base name of the profile's resolved TARGET wrapper
          follows <agent>-as-claude.sh — record command_names[<command>]
          = <agent> (the bare agent id; the exact command key is the
          wrapper itself or the generated closure path when one
          materialized — the engine's dashboard label otherwise falls
          back to the file base name)
       6. When the workflow carries a delegation block — write
          collaboration.limits.max_tasks = the materialized max_tasks
    4. Compose the top-level command_names map from the collected profile
       labels plus the same label for the resolved client wrapper when an
       agent resolved — and write it ONLY when the composed map is
       non-empty (an agentless run without profiles writes no map)
    5. Write the whole file to the fixed in-container home configuration
       path — the path is independent of the afm state directory variable
    6. Return the written path

    Requirements:
    - The whole file is rewritten on every run — a repeated invocation
      stays safe; the collaboration plumbing is regenerated with it, so
      the same authoring takes effect on every consecutive launch
    - The collaboration section is written on every launch and always
      carries runtime_context: wrapper and hide_attach_helpers: true
      first; the profiles join it when `flow` is given with `workflow`
      or `pipeline` (either completes the delivery resolution); the task
      budget joins it only when `workflow` is given
    - A pipeline-declared assistant's profile resolves through the
      workflow extension entry's delivery fields, else the effective
      global agent — the declaration itself contributes no command, no
      env, and no delegate; the goga-<name> id scheme and the {title,
      command, delegate} profile shape are unchanged
    - The profiles are materialized exactly for the ids the compiled flow
      references — no more, no less; an attachment removed by an
      assistant veto or a stage skip leaves no profile behind
    - A generated profile carries exactly title, command, and delegate
    - collaboration.limits.max_tasks is written only when the workflow
      carries a delegation block
    - command_names is written only when at least one labeled command
      exists — an agentless run without collaboration profiles writes no
      map; every key is the exact command path (the wrapper or the
      generated closure over it) and every value the bare agent id of the
      underlying <agent>-as-claude.sh wrapper; a command whose base name
      does not follow that convention gets no label and no entry
    - The five static fields and the hook entry are constants — never
      configurable through the project configuration or the CLI
    - add_stage.enabled false is written unconditionally on every launch
      — the dashboard of a goga-managed run accepts no out-of-model stage
      addition
    - skin_dir is written unconditionally on every launch — the
      goga-managed skin directory it names is served as the active skin
      whenever it holds index.css
    - Assistant env delivery keys on a non-empty effective map only —
      None and {} both mean "no closure"; delegate materializes False
      when the effective value is None
    - The assistant fallback resolves to the `agent` parameter — the
      effective global agent including the workflow global layer; an
      assistant declaration without its own agent launches under the
      workflow's global agent when the workflow carries one
    - The hook entry declares no secret environment references of its own
    - The content is serialized programmatically — never hand-escaped as a
      string
    - The file lands only at the fixed home configuration path — never in
      the project directory, never in the afm state directory

    Constraints:
    - Do not write a bare agent name as a client or profile command —
      always the resolved absolute wrapper path or closure path
    - Do not derive the prompts directory value, the skin directory
      value (skin_dir), or the hook entry values from arguments or
      configuration fields — all three are fixed
    - Do not create or manage the prompts directory — the run coordination
      materializes it
    - Do not create or manage the skin directory the skin_dir field
      names — the run coordination materializes the skin into it
    - Do not print any part of the written content
    - Do not write collaboration profiles from the workflow alone — the
      compiled flow decides which ids exist
    - Do not read or write the collaboration kill-switch (the enabled
      flag or its environment variable) — a disabled environment gets
      engine warnings and skipped helpers, and the run proceeds
    - Do not write closures under the project directory or /workspace —
      container-local temp only
    - Do not print or log env values
    - Do not resolve a pipeline-declared name's delivery from the
      pipeline document — it carries content and engagement only;
      delivery fields come from the workflow entry addressing the name
      or the global fallback

"materialize_afm_skin() -> skin_dir: Path":
  location: afm_skin.py
  annotations: |
    Materialize the packaged goga dashboard skin into the afm skins
    directory in-container before the afm launch — the flat per-launch
    copy of the very directory the written skin_dir points at, served
    wholesale by afm as the active skin while it holds index.css (the
    engine-builtin theme is the fallback when it does not), so the
    dashboard shows the packaged skin instead of the engine's built-in
    copy.

    `skin_dir`: the materialized skin directory
                (/home/goga/.afm/skins/goga)

    Apply `convention` for docstring style and intra-package imports.
    Apply `default_skin` for the packaged skin directory, its file set,
    and the fixed materialization target.

    Algorithm:
    1. Resolve the packaged skin directory per `default_skin` — relative
       to this module, so it holds in an installed image regardless of
       CWD/AFM_DIR
    2. Validate BEFORE touching the target: collect the regular files of
       the packaged directory; a missing directory or one with no regular
       file is one strict pre-run error (the installed package is
       damaged) raised with a readable message — the target directory is
       never touched, so a previously materialized skin survives
    3. Reset the skin entry /home/goga/.afm/skins/goga/ — the whole file
       set is regenerated per launch, so a removed packaged file never
       lingers as a stale dashboard artifact
    4. Copy every collected file flat into the reset entry
    5. Return the materialized skin directory path

    Requirements:
    - Validate-all precedes wipe-and-write — a failed validation never
      wipes the previously materialized skin
    - The materialized file set is exactly the packaged directory's
      regular files — verbatim contents, flat copy, no transformation
    - Idempotent per launch — a repeated invocation resets and rewrites
      the same content
    - The skin lands only at the fixed home skins path — never in the
      project directory, never in the afm state directory, never under
      /workspace

    Constraints:
    - Do not derive the skin directory value (the skin_dir target) from
      arguments or configuration fields — it is fixed
    - Do not create or manage the afm configuration file — the
      configuration write is `write_afm_config`
    - Do not read the engine's built-in skins — the packaged directory is
      the single source
    - Do not print any part of the copied content

"apply_skip_stages(workflow: WorkflowDocument | None, skip_stages: list[str]) -> workflow: WorkflowDocument | None":
  location: apply_skip_stages.py
  annotations: |
    Pure in-memory merge of CLI skip directives into a workflow document.
    Each name in `skip_stages` is applied as a `WorkflowStage` carrying
    skip=True over the workflow's stages map, so the downstream `compile_flow`
    removes those stages and transparently reconnects their dependents'
    depends_on. This routine does NOT delete stages or rewrite depends_on — it
    only prepares the declarative workflow that the compiler consumes.

    `workflow`: optional `WorkflowDocument` resolved by `run_pipeline` (loaded
                from a workflow-file via `load_workflow`, or None when no
                workflow resolved)
    `skip_stages`: stage names to skip (the repeatable -s/--skip flag names
                   passed by run coordination and the card); an empty list
                   is a no-op
    `workflow`: the resulting `WorkflowDocument` carrying the skip directives,
                or the input unchanged when `skip_stages` is empty (None stays
                None — `compile_flow` then runs with no workflow)

    Algorithm:
    1. When `skip_stages` is empty — return `workflow` unchanged (None stays
       None; no skip applied)
    2. Build a new stages map: start from a copy of the stages map of `workflow`
       when `workflow` is not None, otherwise an empty dict
    3. For each name in `skip_stages` — set stages[name] = a `WorkflowStage`
       carrying skip=True (skip wins over any pre-existing entry for that name;
       the compiler removes the stage before applying overrides). The
       replacement CARRIES the pre-skip entry's assistants map: the
       compiler removes the skipped stage before the attachment walk (its
       own attachments are never checked or emitted), but the
       document-wide assistant namespace reads every stage entry, so the
       stage's inline declarations stay resolvable for other stages'
       references — the same carry an authored skip: true keeps. The
       replacement carries NO gates — the compiler removes the skipped
       stage before the gates walk, and gates declare no document-wide
       namespace other stages reference
    4. Return a NEW `WorkflowDocument`: prompt = the prompt of `workflow` when
       `workflow` is not None else None; stages = the new map; extend = a copy
       of the extend map of `workflow` when `workflow` is not None else the
       default empty map; memory = the memory field of `workflow` when
       `workflow` is not None else None; profile = the profile field of
       `workflow` when `workflow` is not None else None; build = the build
       field of `workflow` when `workflow` is not None else None; assistants
       = the assistants field of the workflow when it is not None else the
       default empty map; delegation = the delegation field of the workflow
       when it is not None else None; repeat = the repeat field of
       `workflow` when `workflow` is not None else None — carried verbatim;
       gates = the gates field of `workflow` when it is not None else None
       — carried verbatim; agent = the agent field of `workflow` when it
       is not None else None; env = the env field of `workflow` when it is
       not None else None — carried verbatim.
       The input `workflow` and its maps are NOT mutated

    Requirements:
    - Empty `skip_stages` is a no-op — return the input unchanged
    - Skip always wins — a name present in both the workflow stages and
      `skip_stages` is replaced with a `WorkflowStage` carrying skip=True
    - Do not mutate the input `workflow` or its stages/extend maps — build a
      new `WorkflowDocument` and a new stages map
    - When `workflow` is None and `skip_stages` is non-empty — construct a
      `WorkflowDocument` whose stages map carries only the skip entries (prompt
      None, extend empty, profile None, build None); skip applies to a
      workflow-less pipeline
    - Construct `WorkflowStage` with skip=True, every field at its default
      EXCEPT assistants (the pre-skip entry's map rides along — see
      algorithm step 3) — notes stays None (the model field default)
    - The memory configuration, the profile field, the build block, the
      assistant catalog, the delegation block, and the repeat block of the
      input workflow survive the rebuild verbatim — a rebuild that drops
      them would silently disable memory participation, change activation,
      lose build instructions, lose collaboration, or recompile an authored
      cycle bound as the scalar default for skip-driven runs
    - The gates settings block of the input workflow survives the rebuild
      verbatim — a rebuild that drops it would strip the retry tuning from
      every remaining gated stage of a skip-driven run
    - The skip-replacement `WorkflowStage` carries no gates — the skipped
      stage's checks drop silently downstream
    - When `workflow` is None and `skip_stages` is non-empty — the
      constructed `WorkflowDocument` carries gates None
    - The global run settings (agent, env) of the input workflow
      survive the rebuild verbatim — a rebuild that drops them would
      silently revert a skip-driven run to configuration-level globals
    - When `workflow` is None and `skip_stages` is non-empty — the
      constructed `WorkflowDocument` carries agent None and env None
    - Stage-name validation is NOT performed here — the compiler's strict check
      raises a structural error on a name absent from the pipeline body; this
      routine stays declarative
    - Apply `convention` for code style and docstring formatting

    Constraints:
    - Do not delete stages or rewrite depends_on here — the compiler does both
    - Do not validate stage names against any pipeline here
    - Do not write, read, or generate any workflow-file — the merge operates
      purely on in-memory Python objects
    - Do not mutate the input `workflow` object or its maps
    - Do not interpret, validate, or rebuild the memory configuration — it is
      carried as an opaque value (per `memory`)
    - Do not interpret, validate, or rebuild the gates values — the block
      is carried as an opaque value, whole

"apply_stage_env_wrappers(stages: list[FlowStage], workflow: WorkflowDocument | None, global_agent: str | None, flow_path: Path) -> stages: list[FlowStage]":
  location: stage_env_wrappers.py
  annotations: |
    Deliver the per-stage env instructions of a compiled flow: generate
    one sh closure wrapper per env-declaring stage, patch the script or
    command fields of exactly those stages in the ALREADY WRITTEN
    flow-file, and return a new stage list where those stages' fields
    point at their wrappers. The delivery form follows the claimed
    stage's own compiled fields: a script stage (carrying a script
    field — the stage's action; the compiler rejects an agent
    instruction or a verbatim command key on a script body, so a
    script claim never carries a command) receives a
    payload closure carrying the authored script lines as-is and its
    script field is patched; every other stage receives an exec closure
    over the resolved agent wrapper and its command field is patched
    (inserted when the compiler emitted none). Stages without an env
    instruction pass through as the SAME objects, untouched.

    `stages`: the compiled flow stages
    `workflow`: the effective workflow document (its stages map carries
                the env instructions), or None (no stage is wrapped)
    `global_agent`: the effective global agent — the workflow global
                    agent of the effective workflow when it carries
                    one, otherwise the effective pipeline agent; None
                    when no global agent resolved (a script claim
                    needs no agent at all)
    `flow_path`: the path of the flow-file written by `compile_flow` —
                 the target of the post-compile script/command patch
    `stages`: the new stage list — claimed script stages carry script
              fields and every other claimed stage carries command
              fields pointing at their generated wrappers

    Apply `resolve-wrapper-path` when resolving each exec target.

    Algorithm:
    1. Select the stages whose workflow entry carries a non-None env
       (matched by stage name); with none — return the input list
       unchanged WITHOUT reading or writing `flow_path` (the env-free
       invariant). Loop expansion multiplies the match: EVERY compiled
       copy descended from an env-declaring loop stage (its id carries
       the expansion suffix of the workflow stage name) is selected and
       receives its own wrapper carrying the same env values
    2. Classify every selected stage by its own compiled fields: a
       stage carrying a script field is a script claim (the stage's
       action — the compiler rejects an agent instruction or a
       verbatim command key on a script body, so no command rides
       beside the script); every other stage is an agent claim
    3. Per agent claim, resolve the exec target with the compiler's
       agent precedence: the stage agent's wrapper, else the
       extend-entry agent's wrapper of the same workflow stage name
       (the compiler's per-field default — loop-expansion suffix claims
       resolve through their base name), else the global agent's
       wrapper, else raise one strict pre-run error naming the stage.
       A script claim resolves no exec target — its closure carries the
       authored script itself
    4. Validate every declared env key as a legal environment variable
       name (POSIX shape) BEFORE writing any file — an illegal key (a
       shell metacharacter, a non-string key) would inject into or break
       the generated export line; raise one strict pre-run error naming
       the stage and the key
    5. Generate one sh closure per selected stage in a container-local
       temp directory (owner-only access, 0o700): export the stage's env
       values, then carry the payload — the authored script lines as-is
       on a script claim (the gate script-step closure shape), or the
       exec of the resolved wrapper path forwarding ``"$@"`` on an
       agent claim
    6. Patch `flow_path`: rewrite ONLY the script fields of the script
       claims and the command fields of the agent claims in the
       serialized flow-file to the absolute wrapper paths — every other
       byte of the file stays untouched. The script patch matches the
       exact two-space ``script:`` field prefix (script_before /
       script_after never match) and consumes a block-literal value
       whole; a command patch rewrites the line in place or inserts it
       at the canonical position when absent. The stage-block search is
       bounded to the top-level stages: section — the team: list that
       precedes it serializes member headers (``- id: NAME`` at column
       0) indistinguishable from stage headers, and an assistant named
       like a stage must never capture the stage's patch
    7. Return the new list: claimed script stages carry script = and
       every other claimed stage carries command = the absolute wrapper
       path; every other stage is the SAME input object

    Requirements:
    - The input list and its stage objects are never mutated
    - Wrappers are generated ONLY for env-declaring stages — env-free
      runs keep byte-identical flow output (the flow-file is neither
      read nor rewritten when no stage declares env)
    - The file patch touches only the script fields of the script
      claims and the command fields of the agent claims; the rest of
      the serialized flow-file is byte-identical
    - A script claim inserts no command field — the stage keeps its
      script-action form
    - Per-stage values layer above all global env layers (the wrapper
      exports them last)
    - A declared env key that is not a legal environment variable name
      is a strict pre-run error naming the stage and the key — raised
      before any wrapper file is written

    Constraints:
    - Do not compile, reorder, or restructure stages — this runs after
      compilation
    - Do not write anything under the project directory or /workspace
      — container-local temp only
    - Do not print or log env values

"apply_gate_env_wrappers(stages: list[FlowStage], workflow: WorkflowDocument | None, flow_path: Path) -> stages: list[FlowStage]":
  location: gate_env_wrappers.py
  annotations: |
    Deliver the per-step gate env instructions of a compiled flow: generate
    one sh closure wrapper per env-declaring gates check step (a
    `WorkflowGateStep` with a non-None env map), patch the
    run/command fields of exactly those steps in the ALREADY WRITTEN
    flow-file, and return a new stage list where those steps' verify gates
    point at their wrappers. Steps without an env instruction pass through
    as the SAME objects, untouched.

    `stages`: the compiled flow stages
    `workflow`: the effective workflow document (its stages map carries
                the gate instructions), or None (no step is wrapped)
    `flow_path`: the path of the flow-file written by `compile_flow` —
                 the target of the post-compile verify-step patch
    `stages`: the new stage list — claimed stages carry rebuilt verify
              gates whose env steps point at their generated wrappers

    Apply `resolve-wrapper-path` when composing an agent step's exec
    target — the same in-container wrapper path the compiler composed.

    Algorithm:
    1. Select the compiled stages whose workflow entry's gates list
       carries at least one non-None step env map (matched by stage name —
       exact id first, then the loop-expansion suffix of the workflow
       stage name, the same resolution `apply_stage_env_wrappers`
       applies); with none — return the input list unchanged WITHOUT
       reading or writing `flow_path` (the env-free invariant)
    2. Validate every claimed step's env keys as legal environment
       variable names (POSIX shape) BEFORE writing any file — an illegal
       key (a shell metacharacter, a non-string key) would inject into or
       break the generated export line; raise one strict pre-run error
       naming the stage, the step, and the key
    3. Generate one sh closure per claimed step in a container-local temp
       directory (owner-only access, 0o700): export the step's env values
       (verbatim, shell-quoted), then carry the payload — the authored
       script lines as-is on a script step (the same shell, working
       directory, and exit status the engine gives the authored run
       value), or the exec of the agent's in-container wrapper forwarding
       "$@" on an AI step. The file name composes the stage id, the step
       index, and the step name through the shared safe-name helper — the
       index guarantees uniqueness (step names are not unique-checked)
    4. Patch `flow_path`: rewrite ONLY the claimed steps' run (a script
       step) or command (an agent step) lines in the serialized verify
       sections of the claimed stages to the absolute wrapper paths — a
       block-literal old value (a multi-line authored script) is consumed
       whole with its continuation lines; both emission forms (the list
       form and the settings container form) patch identically; every
       other byte of the file stays untouched
    5. Return the new list: claimed stages carry rebuilt verify gates
       (fresh `FlowVerify`/`FlowVerifyStep` objects — the compiled values are
       never mutated); every other stage is the SAME input object

    Requirements:
    - The input list and its stage objects are never mutated
    - Wrappers are generated ONLY for env-declaring gate steps — a run
      whose gates declare no step env keeps byte-identical flow output
      (the flow-file is neither read nor rewritten)
    - The file patch touches only the claimed steps' run/command lines;
      the rest of the serialized flow-file is byte-identical
    - Per-step values layer above all global env layers (the closure
      exports them last)
    - A declared env key that is not a legal environment variable name is
      a strict pre-run error naming the stage, the step, and the key —
      raised before any wrapper file is written
    - The engine's verify-step schema carries no env field (an emitted
      env key is rejected at flow load) — the delivery is exclusively
      goga-side composition, never an emitted key

    Constraints:
    - Do not compile, reorder, or restructure stages — this runs after
      compilation
    - Do not write anything under the project directory or /workspace
      — container-local temp only
    - Do not print or log env values

"run_hook() -> exit_code: int":
  location: hook_bridge.py
  annotations: |
    Receive one lifecycle event of a running flow and bridge it onto the
    hooks platform — the entry the afm configuration registers as goga's
    observer hook; one short-lived process per event.

    `exit_code`: 0 on success, on ignored events, and on subscriber soft
                 failures; non-zero only on a bridge-internal failure

    Apply `afm` for the execution model of the hook command — the launch
    shape, the payload on stdin, the AFM_* environment, and the failure
    semantics.
    Apply `convention` for docstring style and intra-package imports.

    Algorithm:
    1. Read the event name from the AFM_HOOK_EVENT environment value
       and resolve it via `map_event_action`; a non-curated event returns
       0 immediately, before any platform import
    2. Read the payload from stdin and parse it as a JSON object;
       damaged input is a bridge-internal failure — return a non-zero
       exit
    3. Form the context via `build_run_event` for a run-level action or
       `build_stage_event` for a stage-level action
    4. Emit the soft event via `PipelineHooks` with the mapped action
       name and the built context; subscriber soft failures warn inside
       the platform and never change the exit code
    5. Return 0

    Requirements:
    - The command completes far inside the afm default per-hook timeout
    - No cross-event state — every event is a fresh process
    - The curated filter runs before any platform import
    - The context builder follows the mapped action — the two run-level
      names compose via `build_run_event`, the thirteen stage names via
      `build_stage_event`; an unset or empty AFM_HOOK_EVENT resolves as
      non-curated and exits 0

    Constraints:
    - Do not read anything besides stdin and the AFM_* environment
      values
    - Do not write files and do not mutate the process environment
    - Do not let a subscriber failure change the outcome
    - Do not emit the run boundaries here — they belong to the run
      coordination's checkpoints

"map_event_action(event: str) -> action: str | None":
  location: hook_bridge.py
  annotations: |
    Resolve a lifecycle event name onto the platform action vocabulary —
    the curated filter of the bridge in one place.

    `event`: the lifecycle event name as delivered by the environment
    `action`: the platform action name, or None for an event outside the
               curated vocabulary

    Apply `afm` for the lifecycle event catalog the names come from.
    Apply `convention` for docstring style and intra-package imports.

    Algorithm:
    1. Match `event` against the curated vocabulary — the thirteen stage
       transitions keep their names verbatim; the run-level pair maps
       flow_resumed to run_resumed and flow_interrupted to run_interrupted
    2. Return the matched action name; every other name — the script
       events, the remaining flow boundaries, and unknown names —
       returns None

    Requirements:
    - Pure and deterministic — the same name always resolves the same way
    - Callable before any platform import — no platform modules are
      needed to resolve a name

    Constraints:
    - Do not read the environment or the filesystem — the name arrives
      as `event`

"build_run_event(payload: dict[str, Any]) -> context: RunEvent":
  location: hook_bridge.py
  annotations: |
    Form the run-level context of one bridged event from the parsed
    payload.

    `payload`: the parsed lifecycle event object
    `context`: the read-only facts of the run-level event

    Apply `afm` for the payload shape — the flow block and the event
    facts.
    Apply `convention` for docstring style and intra-package imports.

    Algorithm:
    1. Read the flow block: the name becomes the pipeline name; the run
       identity facts fill `RunIdentity`
    2. Read the event facts: event_id, occurred_at, and reason —
       an absent or null reason becomes the empty string
    3. Return the composed `RunEvent`

    Requirements:
    - Pure passthrough — values carry under idiomatic names only; the
      raw payload never attaches to the context
    - A payload without the flow block or the event facts raises a clean
      error naming the missing fact

    Constraints:
    - Do not invent or default a missing required fact — the error names
      it

"build_stage_event(payload: dict[str, Any]) -> context: StageEvent":
  location: hook_bridge.py
  annotations: |
    Form the stage-level context of one bridged event from the parsed
    payload.

    `payload`: the parsed lifecycle event object
    `context`: the read-only facts of the stage-level event

    Apply `afm` for the payload shape — the flow and stage blocks.
    Apply `convention` for docstring style and intra-package imports.

    Algorithm:
    1. Read the flow block and the event facts the way `build_run_event`
       does
    2. Read the stage block: the stage facts fill `StageTransition` — the
       stage identifier, the stage name, the transition statuses under
       from_status / to_status, and the phase — an absent phase becomes
       the empty string (the live binary omits it on the start/retry
       transitions)
    3. Return the composed `StageEvent`

    Requirements:
    - Pure passthrough — values carry under idiomatic names only
    - A payload without the stage block raises a clean error — a
      stage-level event always carries one

    Constraints:
    - Do not invent or default a missing required fact — the error names
      it

"pipeline_cli(argv: list[str]) -> exit_code: int":
  location: cli.py
  annotations: |
    In-container CLI implementation for python -m goga.pipeline. Parses argv
    via argparse and dispatches to one of five operations: the flat listing
    (`list_pipelines`), the overview (`describe_pipelines`), the card
    (`describe_pipeline`), run coordination (`run_pipeline`), or the
    lifecycle-event bridge (`run_hook`). Invoked through the runpy
    entrypoint in __main__.py — never imported by Python from the host side
    (runtime docker boundary, no Imports).

    `argv`: argument list (typically the process argv minus the program name)
    `exit_code`: 0 on success, 2 on argparse error, non-zero on operation
                 failure

    Apply the `argparse` practice for parser construction.
    Apply the `cli_entrypoint` practice: this routine is defined in the cli
    module; __main__ only delegates to it.
    Apply `convention` for docstring style and intra-package imports.

    Algorithm:
    1. Build the parser with three subcommands:
       - list: an optional --info/-i flag
       - run: a required name positional; an optional --info/-i flag; optional
         --workflow/-w NAME and --no-workflow flags, an optional
         --profile/-p NAME flag, and a repeatable
         --skip/-s NAME flag (all four available with and without --info);
         a --port PORT integer required only when --info is absent; an
         optional --parallel N integer; and a --fail-on-error store-true
         flag
       - hook: no options — the afm-facing machinery entry; the event
         arrives through the process environment and stdin
    2. Parse argv; on argparse error exit with code 2
    3. Resolve the project pipelines directory (<cwd>/.goga/pipelines/) and
       the user pipelines directory (~/.goga/pipelines/)
    4. Dispatch:
       - list without --info — call `list_pipelines`; print the flat list:
         one bullet line per entry — the marker line "* <name>" (with the
         " (project)" suffix for project source entries); return 0
       - list with --info — call `describe_pipelines`; print the overview: one
         bullet block per pipeline — the marker line "* <name>" (with the
         " (project)" suffix for project source entries) followed by indented
         "name:" and "description:" field lines; return 0
       - run with --info — call `describe_pipeline` with the name, the parsed
         workflow flags, the parsed profile value, and the parsed skip
         names; print the card: "name:" and "description:"
         field lines, a blank line, a "---" separator, a blank line, then one
         bullet block per ordered stage — the marker line "* <id>:" and an
         indented "title:" field line; return 0
       - run without --info — call `run_pipeline` with name, port, the parsed
         workflow flags, the parsed profile value, the parsed skip names,
         parallel, and the parsed fail_on_error value; return its exit
         code
       - hook — call `run_hook` and return its exit code
    5. Render an operation failure as a clean readable message to stderr (no
       traceback) and return a non-zero exit code

    Requirements:
    - The run subcommand accepts --info/-i, --workflow/-w NAME,
      --no-workflow, --profile/-p NAME, the repeatable --skip/-s NAME, and
      --parallel N; the workflow, profile, and skip flags bind in both
      info and run modes
    - The run subcommand accepts --fail-on-error; it binds in both info
      and run modes (ignored in info mode) — the same surface pattern as
      the workflow, profile, and skip flags
    - --port is an integer option required only when --info is absent; a
      missing --port without --info is an argparse-style error (exit 2);
      --port is ignored in info mode
    - Long and short flag forms behave identically
    - The flat list template: one marker line "* <name>" per pipeline (with
      the " (project)" suffix for project-source entries) and no header line
      (example: "* deploy (project)" / "* rollback")
    - The overview template: the marker line "* <name>" (with the
      " (project)" suffix for project-source entries) followed by "name:"
      and "description:" field lines indented by four spaces; the name field
      carries the authored header name, the description field the header
      description (example: "* deploy (project)" / "    name: Deploy" /
      "    description: Deploy the service")
    - The card template: a "name:" line, a "description:" line, a blank line,
      a "---" separator, a blank line, then per ordered stage the marker line
      "* <id>:" and a "title:" line indented by four spaces; the separator
      block is printed even when the card carries no stages; when the card
      provenance is non-empty, one blank line and one "tools:" field line
      follow the stage blocks — the contributing tools comma-separated in
      provenance order; an empty provenance adds nothing — the output stays
      byte-identical to the provenance-free card
    - An empty discovery is not an error: the flat list prints nothing —
      zero discovered pipelines, zero lines; the overview likewise prints
      nothing; both return 0
    - Card stage bullet blocks follow execution order; loop-expanded copies
      appear as separate blocks
    - Overview and card output stays within terminal width — no horizontal
      scrolling
    - The hook subcommand carries no options and prints nothing on the
      happy path — it is machinery for the registered observer hook, not
      a user surface

    Constraints:
    - Do not allocate a port inside this CLI — run mode receives it from the
      host-side launcher
    - Do not validate workflow flag combinations or skip stage names — the
      host-side launcher owns the flag-combination validation and the
      compiler owns the stage-name error
    - Do not print tracebacks for operation failures — clean stderr messages
    - Do not import this cell from the host side — invoke via docker only

---

Author: Goga
CreatedAt: 19/08/26
Description: |
  Cell that owns the pipeline workflow: discovery of *.yml pipeline
  files across the project and user pipeline directories, the
  pipeline-file entity model, the informational surface (overview and
  card), run coordination with the in-container run parameters — the
  configuration load-and-amend, the afm configuration authorship with
  the observer-hook registration and the collaboration plumbing
  (the static runtime-context head, generated helper profiles, and the
  task budget), the dashboard-skin materialization of the afm home, the
  workflow-global run-settings resolution (the effective global agent
  and the launch env base), and the launch environment composition —
  the per-stage env delivery
  and the per-step gate env delivery through generated closure wrappers,
  the lifecycle-event bridge of the
  run interior, and the in-container CLI entrypoint pipeline_cli.
