# implementation process

## Index

- [1. Purpose](#1-purpose)
- [2. okstra-run wizard flow](#2-okstra-run-wizard-flow)
- [Carry-in](#carry-in)
- [3. runtime gate](#3-runtime-gate)
  - [3.1 design-preparation preflight](#31-design-preparation-preflight)
- [4. executor and verifier](#4-executor-and-verifier)
- [5. stage and consumers](#5-stage-and-consumers)
- [6. Deliverables](#6-deliverables)
- [7. Forbidden actions](#7-forbidden-actions)
- [8. Verified code](#8-verified-code)

## 1. Purpose

`implementation` executes an approved `implementation-planning` final report into actual code changes and local commits. Source edit is allowed only in this phase, but scope is limited to the approved plan and recorded out-of-plan justification.

## 2. okstra-run wizard flow

```mermaid
flowchart TD
    Start[/okstra-run/] --> Common[common task identity flow]
    Common --> Type[task-type = implementation]
    Type --> Worktree{active task worktree?}
    Worktree -->|yes| PlanPick[approved plan pick/text]
    Worktree -->|no| BaseRef[base-ref pick/text]
    BaseRef --> PlanPick
    PlanPick --> Approved{APPROVED marker present?}
    Approved -->|no| Retry[re-prompt same step]
    Approved -->|yes| Stage[stage multi-pick<br/>ready/active markers]
    Stage --> Chain[render-args<br/>stage + chain-stages]
    Chain --> RoleCount[role-count min..max<br/>omit uses recommended; skip if min==max]
    RoleCount --> RoleModel[role-model provider/model per slot]
    RoleModel --> RoleAdd[min=0 roles via role-add only<br/>default skip]
    RoleAdd --> Extras[directive, related tasks, clarification]
    Extras --> Confirm
    Confirm --> Render[render-bundle]
```

Launch selection uses role slots and model refs only: current-session lead is this session (listed on the confirmation summary), then each static role's count in `min..max` (default **recommended**; the count step is skipped when `min == max`), then one `provider/model` per slot. Roles with `min = 0` stay closed unless the user opens them with role-add (default skip). Duplicate model refs in the same role are rejected. There is no provider roster multi-pick and no defaults-vs-customize fork. `executor` is only a compatibility alias for `implementer` in model refs; implementer slots are chosen through role-count / role-model. Dynamic verifiers are not chosen at launch. `--workers` is a CLI compatibility input only, not a launch picker. `stage_pick` is a multi-pick that shows done/in-progress/ready/waiting status. The selected stage set goes through dependency closure and topological sort into a `chain-stages` CSV, and each actual run executes only one of those stages.

The current okstra-run wizard path does not expose `--approve` that directly flips the approval checkbox. The plan file must already have a recognized approval marker.

## Carry-in

Three facts about what reaches an implementation run from its approved plan, gathered
here because they were previously readable only by tracing the runtime sources.

- **What is attached automatically.** The user's answers to the approved plan's `## 1.
  Clarification Items` rows — the `user-response-*.md` sidecars under
  `runs/implementation-planning/user-responses/`, a sibling of the directory holding the
  plan itself — are collected into `instruction-set/clarification-response.md`. Those
  sidecars are written by the user, not by the report renderer. The report HTML's `Export
  user response` button downloads a file the user then saves there. The in-session flow
  reads `user-response list-view` and `user-response show-view --report <path>
  --project-root <root>`, then uses `user-response begin`, typed `user-response answer`
  and decision commands, and `user-response finalize` to publish the sidecar. The
  renderer at most pre-creates that directory empty so the user does not
  have to; it never puts a sidecar in it.
  The plan document is *not* copied: it reaches the run as the `--approved-plan` path and
  the executor re-reads it there. An explicit `--clarification-response` wins when given;
  the automatic attachment is the fallback for an implementation run that supplies none
  (`scripts/okstra_ctl/run.py`, the `implementation` carry-in branch).
- **Who reads it, and when.** The executor, before its first edit
  (`prompts/profiles/_implementation-executor.md`). A CLI executor (codex/antigravity)
  cannot reach that path from inside its sandbox, so the lead transcribes the file's body
  into the dispatched executor prompt — a path reference alone never arrives.
- **What happens when an answer contradicts the plan.** Each answer is an authoritative
  refinement of its matching row's scope, but an answer that contradicts the approved plan
  or expands scope beyond it is a re-plan trigger: it routes to a new
  `implementation-planning` run rather than being absorbed silently mid-run. Quietly
  widening scope inside an implementation run is what this branch exists to prevent.

## 3. runtime gate

```mermaid
sequenceDiagram
    participant W as okstra-run
    participant P as prepare_task_bundle
    participant Plan as approved final-report
    participant QA as project.json qaCommands
    participant Stage as stage target policy
    participant Reg as worktree registry
    participant WT as stage worktree

    W->>P: task-type=implementation, approved-plan, stage, executor
    P->>Plan: file exists?
    P->>Plan: approval marker regex matches?
    P->>Plan: unresolved Blocks=approval rows?
    P->>Stage: build Stage Lifecycle Snapshot
    P->>Reg: read active stage-key reservations
    P->>Stage: select exactly one ready stage
    P->>Plan: resolve selected stage design preparation
    P->>WT: provision stage-N worktree + branch
    P->>QA: validate qaCommands deny-list
    P->>P: executor provider in resolved roster?
    P->>P: namespace run artifacts under stage-N
    P-->>W: prepared implementation prompt or PrepareError
```

`--approve` exists in the Python runtime, but the okstra-run wizard does not emit it as args. On the shell path, `--approve` sets the report record `frontmatter.approved` to `true` and then follows the same validation path.

### 3.1 design-preparation preflight

Right after stage selection, before worktree provisioning and appending `status:"started"` to `consumers.jsonl`, it resolves the design preparation of the approved plan. The resolver reads only items whose `stageRefs` includes the selected stage, so an undecided decision in another stage does not block the current run.

| outcome | runtime behavior |
|---|---|
| `proceed` | Inject the effective AI proposal, confirmed override, guardrail, and provisional working assumption into the executor prompt as `DESIGN_PREP_CONTEXT`, and create the worktree. |
| `wait_for_input` | Stop with `stage <N> waits for design input: ...; <request paths>`. Do not create the worktree or the started consumer row. |
| `replan` | Stop with `stage <N> requires implementation-planning rerun: ...`. Let a newly approved/edited decision change the planning snapshot or the Stage Map. |

`ready`, `not-applicable`, and `no-design-inputs` proceed. `provisional` can proceed even without a response because there is a safe working assumption, and a non-triggering approval/edit states that assumption and override in the prompt. A `blocked` non-response makes only that stage wait, and when a blocked draft is approved/edited, it replans so that authorization is reflected into the approved plan. A markerless legacy plan proceeds with a `legacy-unassessed` warning without modifying the report.

`manual-user-test` input uses the same flexible status. The planning draft is a seed for implementation to concretize the verification method against the actual diff, and the SSOT of the final execution method is the implementation report's `implementation.manualUserTest`. final-verification does not directly execute the planning sidecar.

Tier 3 conformance uses the same ownership boundary during execution and
verification.

| Entry policy | PASS | FAIL / MISSING / unavailable |
|---|---|---|
| `requires` contains `db`, `http`, or `external` | Evidence recorded | Advisory; user rerun method recorded; run continues |
| `requires=[]` or `requires=[io]` | Evidence recorded | Blocking |

These outcomes are enforced by
`scripts/okstra_ctl/conformance.py::decide_conformance_gate` and
`validators/validate-run.py::_validate_conformance`.

## 4. executor and verifier

```mermaid
flowchart TD
    Lead[Okstra lead<br/>host native] --> Exec[Executor<br/>selected provider]
    Lead --> CV[Claude verifier<br/>read-only]
    Lead --> XV[Codex verifier<br/>read-only]
    Lead --> GV{Antigravity in roster?}
    GV -->|yes| Gem[Antigravity verifier<br/>read-only]
    Exec --> Diff[Source edits + local commits]
    CV --> QA[Independent QA rerun]
    XV --> QA
    Gem --> QA
    QA --> External{External Tier 3<br/>non-PASS?}
    External -->|yes| Advisory[ADVISORY<br/>user-owned rerun]
    External -->|no| Verdict[PASS / CONCERNS / FAIL]
    Advisory --> Report
    Verdict --> Report[Final report preserves dissent]
```

Only the executor may mutate project files. The verifier independently re-runs the diff and validation command read-only in the same worktree. Even a verifier with the same provider as the executor runs again in a separate fresh CLI session. This is to prevent a structure where the same session approves a diff the same session wrote.

## 5. stage and consumers

```mermaid
flowchart LR
    Plan[approved plan<br/>Stage Map] --> Parse[parse stage map]
    Parse --> Snapshot[Stage Lifecycle Snapshot<br/>carry + consumers + reservations]
    Snapshot --> Resolve{stage arg}
    Resolve -->|auto| Next[lowest ready<br/>not done/started/reserved]
    Resolve -->|number| Forced[selected stage]
    Next --> Prep{selected-stage<br/>design preflight}
    Forced --> Prep
    Prep -->|proceed| Base[resolve stage base commit]
    Prep -->|wait / replan| Stop[stop before worktree<br/>and started consumer]
    Base --> WT[create/reuse stage worktree]
    WT --> Started[append consumer status=started]
    Started --> Run[implementation executes one selected stage]
```

Stage selection is `auto` or a number. If `--stage` comes from another task-type, it is a `PrepareError`. The runtime reads `done`/`started` of `consumers.jsonl`, carry sidecar backfill, and the active stage-key of the registry together in the Stage Lifecycle Snapshot, and excludes occupied stages. The Snapshot is not a new stored file but a read-side view of `stage_targets.py`.

The stage worktree base is decided by dependency shape. An independent stage uses the task-key worktree HEAD fixed at first implementation entry as its anchor, and a single-dependency stage branches from the predecessor stage's done `head_commit`. A multi-dependency stage branches from the task-key worktree HEAD after confirming that every predecessor done commit is an ancestor of that HEAD.

## 6. Deliverables

```mermaid
flowchart TD
    Code[Commits] --> Report[implementation final report]
    Diff[git diff --stat base..HEAD] --> Report
    TDD[TDD evidence] --> Report
    Validation[Validation evidence<br/>actual output + exit code] --> Report
    Verifiers[Verifier results<br/>command logs + verdicts] --> Report
    Rollback[Rollback verification] --> Report
    Report --> Next[Routing recommendation<br/>final-verification or loop back]
```

The final report requires at least the following.

- approved plan path and quoted approval marker
- selected stage, isolated stage worktree path, run artifact path (`runs/implementation/stage-<N>/`)
- commit SHA, message, plan step mapping
- diff summary and per-file summary
- out-of-plan edits block
- actual stdout/stderr and exit code of the plan validation command
- TDD failing-then-passing evidence
- per-verifier independent validation rerun result
- `carry/stage-<N>.json` evidence sidecar and `consumers.jsonl` started/done row
- rollback verification
- `implementation.manualUserTest` finalized against the actual diff and whether it is executable
- follow-up tasks table

## 7. Forbidden actions

```mermaid
flowchart TD
    Impl[implementation] --> Allowed[local edit/write/build/test/git add/git commit]
    Impl -. forbidden .-> Push[git push]
    Impl -. forbidden .-> Publish[publish/release/deploy]
    Impl -. forbidden .-> RealDB[source migration or<br/>shared/staging/prod datastore write]
    Impl -. forbidden .-> VerifierWrite[verifier edit/write]
    Impl -. forbidden .-> Scope[silent scope expansion]
    Impl -. forbidden .-> Acceptance[declaring final acceptance]
```

This phase does not declare final acceptance. It says only ready for final-verification or needs new loop.

## 8. Verified code

- [`prompts/profiles/implementation.md`](../../prompts/profiles/implementation.md)
- [`templates/reports/implementation-input.template.md`](../../templates/reports/implementation-input.template.md)
- [`scripts/okstra_ctl/run.py`](../../scripts/okstra_ctl/run.py)
- [`scripts/okstra_ctl/wizard.py`](../../scripts/okstra_ctl/wizard.py)
- [`validators/validate-implementation-plan-stages.py`](../../validators/validate-implementation-plan-stages.py)
- [`scripts/okstra_ctl/qa_commands.py`](../../scripts/okstra_ctl/qa_commands.py)
- [`prompts/lead/okstra-lead-contract.md`](../../prompts/lead/okstra-lead-contract.md)
