okstra 0.125.5 → 0.127.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/docs/architecture.md +2 -1
  2. package/docs/project-structure-overview.md +2 -0
  3. package/package.json +1 -1
  4. package/runtime/BUILD.json +2 -2
  5. package/runtime/agents/workers/report-writer-worker.md +2 -2
  6. package/runtime/bin/okstra-antigravity-exec.sh +8 -2
  7. package/runtime/bin/okstra-claude-exec.sh +8 -2
  8. package/runtime/bin/okstra-codex-exec.sh +65 -8
  9. package/runtime/prompts/lead/adapters/claude-code.md +1 -0
  10. package/runtime/prompts/lead/convergence.md +4 -1
  11. package/runtime/prompts/lead/okstra-lead-contract.md +24 -1
  12. package/runtime/prompts/lead/report-writer.md +1 -1
  13. package/runtime/prompts/lead/team-contract.md +3 -0
  14. package/runtime/prompts/profiles/_common-contract.md +1 -1
  15. package/runtime/python/okstra_ctl/design_surfaces.py +30 -14
  16. package/runtime/python/okstra_ctl/render_final_report.py +71 -5
  17. package/runtime/python/okstra_ctl/run.py +3 -1
  18. package/runtime/python/okstra_ctl/schema_excerpt.py +17 -1
  19. package/runtime/python/okstra_ctl/worker_heartbeat.py +50 -0
  20. package/runtime/python/okstra_ctl/worker_liveness.py +140 -0
  21. package/runtime/python/okstra_ctl/worker_prompt_headers.py +20 -0
  22. package/runtime/templates/reports/final-report.template.md +9 -9
  23. package/runtime/templates/worker-prompt-preamble.md +1 -0
  24. package/runtime/validators/forbidden_actions.py +43 -4
  25. package/runtime/validators/validate-implementation-plan-stages.py +6 -4
  26. package/runtime/validators/validate-report-views.py +4 -4
  27. package/runtime/validators/validate-run.py +117 -7
  28. package/runtime/validators/validate-schedule.py +6 -4
  29. package/runtime/validators/validate_fanout.py +4 -3
  30. package/runtime/validators/validate_improvement_report.py +6 -4
  31. package/runtime/validators/validate_session_conformance.py +16 -7
  32. package/src/cli-registry.mjs +7 -0
  33. package/src/commands/inspect/worker-liveness.mjs +31 -0
  34. package/src/commands/lifecycle/preflight.mjs +25 -2
  35. package/src/lib/helper-scripts.mjs +23 -0
  36. package/src/lib/python-helper.mjs +1 -1
@@ -732,7 +732,8 @@ Errors that occur while workers (Claude/Codex/Antigravity worker, Report writer,
732
732
 
733
733
  ### Live-log mirror (codex / antigravity wrapper)
734
734
 
735
- - On every dispatch, `scripts/okstra-codex-exec.sh` and `scripts/okstra-antigravity-exec.sh` create a `<prompt>.log` sidecar next to the prompt path and mirror stdout there (`tee`, preserving the exit code with `PIPESTATUS[0]`). stderr is appended to the same file, preserving the subagent stderr-capture contract, and the file is truncated on each dispatch. This solves the problem where a calling subagent polls `BashOutput` every 60 seconds, leaving users unable to detect a stalled state during long-running work such as large-codebase scans in analysis or cargo / pytest in implementation.
735
+ - On every dispatch, `scripts/okstra-codex-exec.sh` and `scripts/okstra-antigravity-exec.sh` create a `<prompt>.log` sidecar next to the prompt path and mirror stdout there through a named FIFO (which keeps the CLI a single addressable PID for the idle watchdog). stderr is appended to the same file, preserving the subagent stderr-capture contract, and the file is truncated on each dispatch. This solves the problem where a calling subagent polls `BashOutput` every 60 seconds, leaving users unable to detect a stalled state during long-running work such as large-codebase scans in analysis or cargo / pytest in implementation.
736
+ - **Per-block cap on the codex log copy** (`okstra_log_mirror` in `scripts/okstra-codex-exec.sh`): workers read their required inputs end-to-end per the Worker Preamble's *Reading rules*, so a single report read can dump 170KB+ into the log and observed sidecars reach 8MB. The mirror keeps the first `log_block_line_cap` (120) lines of each output block and replaces the remainder with a `[okstra log-mirror] N line(s) elided` marker, draining every 500 elided lines so the idle watchdog keeps seeing writes. **Only the log copy is capped** — the stdout passthrough stays byte-identical, so the dispatching subagent's `BashOutput` and Phase 5 synthesis are unaffected (`tests-js/codex-log-mirror.test.mjs` asserts that byte-identity). The marker set is codex-specific; the claude wrapper emits `--output-format=stream-json` and does not share this filter.
736
737
  - When tmux is reachable in the lead environment, the wrapper automatically splits a sibling pane and runs `tail -F <log-path>`. The trace-pane title appends `-tail` to the caller (worker) pane title: `<cli>-<role>-<pid>-tail` (for example, `codex-worker-93421-tail`). At the same time, the caller (worker) pane title is set to `<cli>-<role>-<pid>`. `<pid>` is the wrapper's own PID, so multiple workers with the same role spawned concurrently remain distinguishable, and operators can visually map `<caller> ↔ <caller>-tail`. **Caller-pane resolution**—because the Claude Code Bash tool now removes both `$TMUX` and `$TMUX_PANE` from the environment, the wrapper does not depend on environment variables. It (1) derives `<RUN_DIR>` as `dirname(dirname(prompt_path))` from the prompt path (paths.py SSOT), and (2) reads `<RUN_DIR>/state/lead-pane.id`, written once by the lead in its foreground pane, as the split anchor. This remains reliable for background dispatches, unlike active-pane guessing, even if the user changes panes. If the file is absent or the pane is stale, it falls back to `tmux display-message -p '#{pane_id}'` (the active pane). The trace split explicitly anchors to that caller pane with `-t`. The role is the wrapper's fifth optional positional argument and defaults to `worker`. The caller pane title is captured and restored by an EXIT trap, preventing stale titles across dispatches. Focus returns to the caller pane, and the trace pane remains after CLI exit so its scrollback is available. All paths silently degrade when tmux is unreachable, splitting fails, or tmux is outdated.
737
738
  - **Run-scoped tagging for cleanup**: A trace pane's `tail -F` is a child of the tmux shell and survives Claude's exit. The wrapper tags each spawned pane with `tmux set-option -p @okstra_trace_run=<RUN_DIR>`, and `okstra-trace-cleanup.sh` discovers panes server-wide from that tag via `tmux list-panes -a` and runs `tmux kill-pane`. It requires neither tmux environment variables nor a pane-ID registry. Because the tag is run-scoped, it does not kill trace panes from other simultaneous okstra runs. Cleanup has two entry forms: the lead invokes it with `--run-dir <RUN_DIR>` to clean traces and worker-agent panes for that run, or the `hooks.SessionEnd` entry in `templates/reports/settings.template.json` invokes it with `--reap` to clean all trace panes tagged below `$CLAUDE_PROJECT_DIR/.okstra/` when no single run directory exists at session end. Missing tmux and stale pane IDs silently degrade.
738
739
  - **Automatic cleanup on phase transitions, including worker-agent panes**: `okstra-trace-cleanup.sh --run-dir <RUN_DIR>` closes not only tagged trace panes but also worker-agent panes occupied by dispatched subagents. These harness-owned panes cannot be tagged, so the script identifies them within the lead session (`tmux list-panes -s -t <lead-pane>`) through a title allowlist: `claude-worker` / `codex-worker` / `antigravity-worker` / `report-writer-worker`. Implementation role titles such as `claude-executor` / `codex-verifier` / `agy-executor-tail`, and FleetView teammate prefixes `✳ ` / `⠂ `, are also treated as okstra panes. Session scoping and exclusion of the lead's own pane are determined by `<RUN_DIR>/state/lead-pane.id`; the lead pane is never killed even if its title matches. Immediately before dispatching workers for a new phase (before the `PROGRESS: phase-5.5-convergence` / `phase-6-synthesis` marker), the lead calls this script with `--run-dir` to clean previous-phase panes without prompting.
@@ -169,6 +169,7 @@ Runtime/install asset changes follow this checklist:
169
169
  | `resolve-task-key` | `src/commands/inspect/resolve-task-key.mjs` | Resolve a bare task-id to candidate task-keys from the project catalog |
170
170
  | `set-work-status` | `src/commands/inspect/set-work-status.mjs` | Set a task's user-managed `workStatus` in task-manifest.json (Python: `okstra_ctl.set_work_status`) |
171
171
  | `time-report`, `log-report`, `error-report`, `error-zip` | `src/commands/inspect/*.mjs` | Read-side task runtime, wrapper log, and error aggregation helpers |
172
+ | `worker-liveness` | `src/commands/inspect/worker-liveness.mjs` | Report whether pending workers are still alive, so the lead's poll ends a stalled wait early instead of paying the deadline (Python: `okstra_ctl.worker_liveness`) |
172
173
  | `context-cost` | `src/commands/inspect/context-cost.mjs` | Estimate task bundle file/read context cost |
173
174
  | `worktree-lookup` | `src/commands/execute/worktree-lookup.mjs` | Look up a task-key's registered worktree |
174
175
  | `plan-validate` | `src/commands/execute/plan-validate.mjs` | Check approved-plan approval marker |
@@ -249,6 +250,7 @@ Important modules:
249
250
  | `index.py`, `jsonl.py`, `reconcile.py`, `listing.py`, `batch.py`, `backfill.py` | `~/.okstra` run index and history operations |
250
251
  | `run_index_row.py` | single reference point for creating / slimming / hydrating a `~/.okstra` run-index row — runId SSOT, preserves projectId raw |
251
252
  | `error_report.py`, `error_log_core.py`, `error_zip.py` | backend for the okstra-inspect errors/error-zip facets — `error_log_core` is the read-only core that globs/parses/aggregates `errors-*.jsonl`, `error_report` renders the errors facet, and `error_zip` collects cross-project run directories, allowlist-anonymizes, aggregates clusters, and produces a zip |
253
+ | `worker_heartbeat.py`, `worker_liveness.py` | `worker_heartbeat` is the single definition of the `- PROGRESS:` heartbeat line shape and its 5-minute (+60s grace) cadence budget, shared by the Phase 7 audit (`validators/validate_session_conformance.py`) and the live probe; `worker_liveness` backs `okstra worker-liveness`, reporting a pending worker as `stalled` (heartbeat past the budget) or `did-not-launch` (no wrapper `.log`/`.status.json` past the launch grace) |
252
254
  | `log_report.py`, `time_report.py` | read-side backend for the okstra-inspect logs/time facets (`okstra log-report` is the wrapper sidecar log inventory, `okstra time-report` is per-task time aggregation) |
253
255
  | `rollup.py` | read-side backend for the okstra-rollup skill — fans the catalog out per task-group (or the whole project) and deterministically aggregates each task's run count, elapsed time (raw ms), error count, and latest report path, plus group-level totals/status, category, and phase distribution. Reuses the `time_report`/`error_log_core` functions and delegates report-body synthesis to the skill |
254
256
  | `usage_report.py` | Read-only okstra-usage backend — scans the whole current project's recent run timelines, defaults to 30 days, and returns task-type coverage, raw/billable tokens, known USD cost, CPU-sum and wall-clock milliseconds, unavailable reason counts, and unmatched pricing models |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "okstra",
3
- "version": "0.125.5",
3
+ "version": "0.127.0",
4
4
  "description": "Multi-agent cross-verification orchestrator runtime + Claude Code skills.",
5
5
  "license": "MIT",
6
6
  "author": "devonshin",
@@ -1,5 +1,5 @@
1
1
  {
2
- "package": "0.125.5",
3
- "builtAt": "2026-07-20T12:43:22.033Z",
2
+ "package": "0.127.0",
3
+ "builtAt": "2026-07-20T14:29:59.831Z",
4
4
  "repoRoot": "/home/runner/work/okstra/okstra"
5
5
  }
@@ -67,7 +67,7 @@ Before writing the data.json, you MUST:
67
67
 
68
68
  For the report writer specifically, the `## Inputs` list always includes:
69
69
 
70
- - `<instruction-set>/final-report-schema.json` — the **per-task-type excerpt** of the data.json schema (scoped to this run's task-type at prep time: other task-types' deliverable blocks and their unreachable `$defs` are stripped). This is the shape you must author. Read this, NOT the full `schemas/final-report-v1.0.schema.json` (it is not in the task bundle and its `schemas/...` path is not resolvable here). Validation still runs against the full schema post-hoc, so the excerpt never relaxes the contract.
70
+ - `<instruction-set>/final-report-schema.json` — the **per-task-type excerpt** of the data.json schema (scoped to this run's task-type at prep time: other task-types' deliverable blocks and their unreachable `$defs` are stripped). This is the shape you must author. Read this, NOT the full `schemas/final-report-v1.0.schema.json` (it is not in the task bundle and its `schemas/...` path is not resolvable here). Validation still runs against the full schema post-hoc, so the excerpt never relaxes the contract. The excerpt is frozen at prep time and carries the okstra version it was cut from (`x-okstraCutFromVersion`); if the renderer rejects a field the excerpt told you to write, the runtime upgraded mid-run — the renderer's error names the version skew, and the **installed schema wins**.
71
71
  - `<instruction-set>/final-report-template.md` — the **phase-stripped** Jinja2 template the renderer uses (only this run's §4.x deliverable block remains). Read it to understand which data.json fields appear where in the rendered markdown; do NOT edit it, and do NOT pull the full `templates/reports/final-report.template.md` source.
72
72
  - `templates/reports/i18n/en.json` and `templates/reports/i18n/ko.json`.
73
73
  - Every analysis worker's result file under `worker-results/`.
@@ -87,7 +87,7 @@ Rules (the schema enforces most of these — they are listed here so you know *w
87
87
 
88
88
  - `header.reportAuthor` is `"Report writer worker"`; `header.reportOwner` is `"Claude lead"`. Set author to `"Claude lead"` only for `release-handoff` runs (single-lead by design) or a recorded report-writer dispatch failure fallback.
89
89
  - **Source items (worker:item) preservation.** Every `consensus[].sourceItems`, `differences[].workersPosition[].itemId`, and `evidence.primary[].sourceItems` entry MUST carry the worker:item-id pair (e.g. `claude:F-001`, `codex:1.1`, `antigravity:F-3`, or `lead:mcp-1` for lead-only evidence). The schema enforces this via the `SourceItem` regex; bare worker-name lists no longer parse.
90
- - **Verdict Card consistency.** `verdictCard.verdictToken` / `.direction` / `.nextStep` MUST byte-match `finalVerdict.verdictToken` / `.direction` / `.nextStep` and `recommendedNextSteps[0].text`. The renderer pulls both from the same data structureduplicating values across `verdictCard` and `finalVerdict` is intentional so the validator can diff them.
90
+ - **Verdict Card consistency.** `verdictCard.verdictToken` and `verdictCard.direction` MUST byte-match `finalVerdict.verdictToken` / `.direction`; `validators/validate-run.py` diffs both and fails the run on divergence. `verdictCard.nextStep` names the same action as `finalVerdict.nextStep` and `recommendedNextSteps[0].text` but is written as the actionable command the reader runs (e.g. `/okstra-run task-key=… task-type=release-handoff`) where the other two are prose it is deliberately not a byte copy. Duplicating the compared values across `verdictCard` and `finalVerdict` is intentional so the validator can diff them.
91
91
  - **Reader Summary.** Populate `readerSummary` when the schema excerpt exposes it. It is the human-first entrypoint for both Markdown and HTML: one sentence for the decision, one for the human action required, one for blockers, one for audit sections safe to skip on first read, and one runnable recommended command. Do not duplicate raw evidence tables here.
92
92
  - **§7 phase-continuation row (mandatory for non-terminal task-types).** When `header.taskType` is one of `requirements-discovery` / `implementation-planning` / `error-analysis` / `implementation` / `final-verification`, `followUpTasks` MUST contain at least one row whose `origin` is `phase-continuation`, `suggestedTaskType` equals the next phase (byte-identical to `finalVerdict.nextStep`'s referenced phase), `newTaskId` reuses the current task-id, `autoSpawn` is `"no"`, and `priority` is `"P0"`. For `release-handoff` runs, omit the phase-continuation row. Schema `allOf` clause enforces this via `contains`.
93
93
  - **No deprecated sections.** The schema has no `4.5.8 User Approval Request` body field, no `4.5.9 Open Questions`, no `5.1 Additional Material Request`, no `5.2 User Confirmation Questions` — clarifications go under the unified `clarificationItems[]` array.
@@ -283,8 +283,14 @@ if (( idle_timeout_secs > 0 )); then
283
283
  # GNU `stat -c` 우선 + 숫자 검증. BSD-ism `stat -f %m` 은 Linux 에서 깨끗이
284
284
  # 실패하지 않고 비숫자 파일시스템 출력으로 성공해 아래 산술을 set -u 에서
285
285
  # 깨뜨린다 — file_mtime(lib/okstra/interactive.sh) 와 동일 가드.
286
- last_mtime="$(stat -c %Y "$log_path" 2>/dev/null)"
287
- [[ "$last_mtime" =~ ^[0-9]+$ ]] || last_mtime="$(stat -f %m "$log_path" 2>/dev/null)"
286
+ #
287
+ # `|| true` 필수다. macOS 에는 GNU `stat -c` 없어 exit 1 이고,
288
+ # `2>/dev/null` 은 stderr 만 막지 종료코드는 막지 못한다. 이 워치독은 명시적
289
+ # `( ) &` 서브셸이라 위쪽 `set -e` 를 상속하므로, 실패한 할당 하나가 첫 폴링에서
290
+ # 워치독을 통째로 죽인다 — 조용히, 로그 한 줄 없이. file_mtime 이 같은 코드로도
291
+ # 멀쩡한 것은 항상 `$( )` 안에서 호출돼 errexit 을 상속하지 않기 때문이다.
292
+ last_mtime="$(stat -c %Y "$log_path" 2>/dev/null || true)"
293
+ [[ "$last_mtime" =~ ^[0-9]+$ ]] || last_mtime="$(stat -f %m "$log_path" 2>/dev/null || true)"
288
294
  [[ "$last_mtime" =~ ^[0-9]+$ ]] || last_mtime=0
289
295
  now=$(date +%s)
290
296
  idle=$(( now - last_mtime ))
@@ -126,8 +126,14 @@ if (( idle_timeout_secs > 0 )); then
126
126
  # GNU `stat -c` 우선 + 숫자 검증. BSD-ism `stat -f %m` 은 Linux 에서 깨끗이
127
127
  # 실패하지 않고 비숫자 파일시스템 출력으로 성공해 아래 산술을 set -u 에서
128
128
  # 깨뜨린다 — file_mtime(lib/okstra/interactive.sh) 와 동일 가드.
129
- last_mtime="$(stat -c %Y "$log_path" 2>/dev/null)"
130
- [[ "$last_mtime" =~ ^[0-9]+$ ]] || last_mtime="$(stat -f %m "$log_path" 2>/dev/null)"
129
+ #
130
+ # `|| true` 필수다. macOS 에는 GNU `stat -c` 없어 exit 1 이고,
131
+ # `2>/dev/null` 은 stderr 만 막지 종료코드는 막지 못한다. 이 워치독은 명시적
132
+ # `( ) &` 서브셸이라 위쪽 `set -e` 를 상속하므로, 실패한 할당 하나가 첫 폴링에서
133
+ # 워치독을 통째로 죽인다 — 조용히, 로그 한 줄 없이. file_mtime 이 같은 코드로도
134
+ # 멀쩡한 것은 항상 `$( )` 안에서 호출돼 errexit 을 상속하지 않기 때문이다.
135
+ last_mtime="$(stat -c %Y "$log_path" 2>/dev/null || true)"
136
+ [[ "$last_mtime" =~ ^[0-9]+$ ]] || last_mtime="$(stat -f %m "$log_path" 2>/dev/null || true)"
131
137
  [[ "$last_mtime" =~ ^[0-9]+$ ]] || last_mtime=0
132
138
  now=$(date +%s)
133
139
  idle=$(( now - last_mtime ))
@@ -167,6 +167,57 @@ log_path="${prompt_path%.md}.log"
167
167
  [[ "$log_path" == "$prompt_path" ]] && log_path="${prompt_path}.log"
168
168
  : > "$log_path"
169
169
 
170
+ # Per-block line cap applied to the LOG COPY of codex's stdout (see
171
+ # okstra_log_mirror below). Workers read their required inputs end-to-end per
172
+ # templates/worker-prompt-preamble.md "Reading rules", so one report read can
173
+ # dump 170KB+ into the log; observed sidecar logs reach 8MB and account for
174
+ # ~93% of a project's `.okstra/` bytes (`okstra log-report` inventories them).
175
+ # 120 lines keeps each block's command and the head of its output — enough to
176
+ # reconstruct what ran — while cutting the whole-file dumps that dominate.
177
+ log_block_line_cap=120
178
+
179
+ # Mirror stdin to stdout verbatim AND to <log-path> with a per-block cap.
180
+ #
181
+ # Only the log copy is capped. The stdout passthrough is never filtered, so the
182
+ # dispatching subagent's `BashOutput` still receives codex's output verbatim for
183
+ # Phase 5 synthesis, and the model's own context is unaffected — the log is a
184
+ # *copy* of output codex already produced, not an input to anything except a
185
+ # human post-mortem and the `tail -n 10` diagnostic in
186
+ # agents/workers/_cli-wrapper-template.md.
187
+ #
188
+ # A "block" starts at one of codex's own top-level markers. Misreading a marker
189
+ # only resets the counter (less truncation); it can never drop a line from
190
+ # stdout. The marker set is codex-specific — the claude wrapper emits
191
+ # `--output-format=stream-json` and must NOT reuse this filter as-is.
192
+ okstra_log_mirror() {
193
+ awk -v logf="$1" -v cap="$2" '
194
+ function drain() {
195
+ if (elided > 0) {
196
+ printf " [okstra log-mirror] %d line(s) elided from this block\n", elided >> logf
197
+ fflush(logf)
198
+ elided = 0
199
+ }
200
+ }
201
+ /^(exec|codex|thinking|user)$/ { drain(); kept = 0 }
202
+ {
203
+ print
204
+ fflush()
205
+ kept++
206
+ if (kept <= cap) {
207
+ print >> logf
208
+ fflush(logf)
209
+ } else {
210
+ elided++
211
+ # Periodic drain keeps the log mtime moving: the idle watchdog below
212
+ # polls that mtime as its liveness proxy and would otherwise SIGTERM
213
+ # codex partway through a long elided block.
214
+ if (elided >= 500) drain()
215
+ }
216
+ }
217
+ END { drain(); close(logf) }
218
+ '
219
+ }
220
+
170
221
  # stdout-mirror FIFO path (created at the dispatch block below). Declared here,
171
222
  # before the EXIT trap is defined, so the trap's cleanup reference is always set
172
223
  # under `set -u`.
@@ -293,11 +344,11 @@ fi
293
344
  # stdin redirect, stderr capture, and pipeline mirroring are intentionally
294
345
  # inside the wrapper — this is the entire reason this script exists.
295
346
  #
296
- # stdout: tee'd to both the live log (for `tail -f`) AND the wrapper's own
297
- # stdout (so the subagent's `BashOutput` still captures the final
298
- # text verbatim for Phase 5 synthesis). Implemented via process
299
- # substitution so codex itself stays a single addressable PID we
300
- # can SIGTERM from the watchdog.
347
+ # stdout: mirrored to both the live log (for `tail -f`, capped per block by
348
+ # okstra_log_mirror) AND the wrapper's own stdout (verbatim, so the
349
+ # subagent's `BashOutput` still captures the final text for Phase 5
350
+ # synthesis). Implemented via a FIFO so codex itself stays a single
351
+ # addressable PID we can SIGTERM from the watchdog.
301
352
  # stderr: appended to the live log only — mirrors the prior `2>/dev/null`
302
353
  # contract of keeping the wrapper's stderr stream clean.
303
354
  # exit: codex's own exit code is preserved by `wait`.
@@ -325,7 +376,7 @@ fi
325
376
  stdout_fifo="${log_path}.stdout.fifo"
326
377
  rm -f "$stdout_fifo"
327
378
  mkfifo "$stdout_fifo"
328
- tee -a "$log_path" < "$stdout_fifo" &
379
+ okstra_log_mirror "$log_path" "$log_block_line_cap" < "$stdout_fifo" &
329
380
  stdout_tee_pid=$!
330
381
 
331
382
  # Disable git's fsmonitor for every git command codex runs in this process
@@ -363,8 +414,14 @@ if (( idle_timeout_secs > 0 )); then
363
414
  # GNU `stat -c` 우선 + 숫자 검증. BSD-ism `stat -f %m` 은 Linux 에서 깨끗이
364
415
  # 실패하지 않고 비숫자 파일시스템 출력으로 성공해 아래 산술을 set -u 에서
365
416
  # 깨뜨린다 — file_mtime(lib/okstra/interactive.sh) 와 동일 가드.
366
- last_mtime="$(stat -c %Y "$log_path" 2>/dev/null)"
367
- [[ "$last_mtime" =~ ^[0-9]+$ ]] || last_mtime="$(stat -f %m "$log_path" 2>/dev/null)"
417
+ #
418
+ # `|| true` 필수다. macOS 에는 GNU `stat -c` 없어 exit 1 이고,
419
+ # `2>/dev/null` 은 stderr 만 막지 종료코드는 막지 못한다. 이 워치독은 명시적
420
+ # `( ) &` 서브셸이라 위쪽 `set -e` 를 상속하므로, 실패한 할당 하나가 첫 폴링에서
421
+ # 워치독을 통째로 죽인다 — 조용히, 로그 한 줄 없이. file_mtime 이 같은 코드로도
422
+ # 멀쩡한 것은 항상 `$( )` 안에서 호출돼 errexit 을 상속하지 않기 때문이다.
423
+ last_mtime="$(stat -c %Y "$log_path" 2>/dev/null || true)"
424
+ [[ "$last_mtime" =~ ^[0-9]+$ ]] || last_mtime="$(stat -f %m "$log_path" 2>/dev/null || true)"
368
425
  [[ "$last_mtime" =~ ^[0-9]+$ ]] || last_mtime=0
369
426
  now=$(date +%s)
370
427
  idle=$(( now - last_mtime ))
@@ -62,6 +62,7 @@ This adapter maps the neutral Okstra lead operations to Claude Code host primiti
62
62
  - Follow the core Result Path + terminal-status completion contract. The Claude adapter's wake mechanism is one `Bash(run_in_background: true)` poll covering every pending Result Path, not foreground sleep or an idle-notification dependency. A spawn acknowledgement is never completion.
63
63
  - The background poll uses a per-worker deadline of twice the expected duration: 20 minutes for `requirements-discovery`, 30 for `error-analysis`, 40 for `implementation-planning`, 40 for `implementation`, and 20 for `final-verification`. On timeout, record terminal status and apply the core's single shared retry budget.
64
64
  - The Claude worker heartbeat audit sidecar must update at least every five minutes while its result is pending. A missing or stale heartbeat consumes the same one-retry budget; after the second silent hang, record `timeout`. The result file remains the authoritative completion signal.
65
+ - **The background poll checks liveness, not only Result Paths.** Result Paths change once, at the very end, so polling them alone pays the full deadline for a worker that died at minute three. Each poll iteration MUST also run, in the same background shell, one `okstra worker-liveness` call covering every pending worker — `--audit <audit-sidecar-path>` for each in-process Claude worker, `--prompt <prompt-history-path>` for each CLI-wrapper worker. It exits non-zero when a worker is `stalled` (heartbeat older than the cadence budget) or `did-not-launch`; either verdict ends the wait for that worker immediately and spends the core's one-retry budget, rather than waiting out the deadline. The command reports only — it never kills or re-dispatches. It shares its heartbeat budget with the Phase 7 audit (`okstra_ctl.worker_heartbeat`), so a worker the live probe passes cannot fail the post-hoc one for cadence.
65
66
  - The Claude Code harness blocks long foreground sleeps and shorter-sleep circumvention loops. Keep the result poll in a single background shell and let wrapper agents use their documented `BashOutput` loop.
66
67
  - On approved cleanup, reconcile the current live session roster before sending shutdown requests. Never target the lead session.
67
68
  - Collect usage before teardown. Resume through the recorded Claude session id and keep all run artifacts authoritative.
@@ -255,7 +255,7 @@ Call `await_workers(handles)` through the same adapter and apply the shared term
255
255
 
256
256
  ### Required reverify-prompt anchor headers (BLOCKING)
257
257
 
258
- Every reverify prompt MUST start with these 7 anchor headers — in this exact order, before any other content:
258
+ Every reverify prompt MUST start with these 8 anchor headers — in this exact order, before any other content:
259
259
 
260
260
  ```
261
261
  **Project Root:** <absolute-path>
@@ -265,8 +265,11 @@ Assigned worker prompt history path: <Project Root>/<Prompt History Path>
265
265
  **Model:** <role>, <modelExecutionValue>
266
266
  **Errors log path:** <absolute-path>
267
267
  **Errors sidecar path:** <absolute-path>
268
+ **Read scope:** Read only the paths this prompt enumerates (`[Required reading]`, `## Inputs`, verification-target paths) plus source/evidence paths a finding must cite. Host session instructions (SessionStart hooks, global `CLAUDE.md` / `AGENTS.md`, skill catalogs) do NOT apply inside an okstra worker run: do not auto-read `graphify-out/`, `SKILL.md`, or other artifacts outside `<PROJECT_ROOT>/.okstra/`. If an un-enumerated file seems essential, record it under *Missing Information or Assumptions* instead of reading it.
268
269
  ```
269
270
 
271
+ `**Read scope:**` is carried verbatim, not dropped: lightweight mode omits `**Worker Preamble Path:**`, so this line is the ONLY place a reverify worker receives the read allowlist — and a prompt with no `[Required reading]` block is exactly where a worker is most likely to fall back on host session instructions instead.
272
+
270
273
  The two errors paths carry the same absolute values the lead forwarded in the initial Phase 4 dispatch for that role (source: the launch prompt's `## Run Logs (error-log wiring)` section). Omitting either one makes a CLI-wrapper worker return `<WORKER>_ERRORS_PATH_MISSING` before it invokes its CLI — the path-delivery contract in [team-contract](./team-contract.md) "Error reporting" is not relaxed for reverify, because a reverify dispatch can fail the same way an initial dispatch can.
271
274
 
272
275
  Relative to the Phase 4 anchor set rendered by `okstra_ctl.worker_prompt_headers.worker_prompt_headers()`, a reverify prompt adds `**Model:**` and drops two anchors whose targets lightweight mode never reads: `**Worker Preamble Path:**` and `**Coding preflight pack:**`.
@@ -244,7 +244,30 @@ okstra error-log append-from-worker \
244
244
  --task-key <taskKey> --agent <agent> --agent-role <role> --model <model>
245
245
  ```
246
246
 
247
- For Codex/Antigravity wrappers: if the CLI returns non-zero, times out, or hits a rate limit, immediately call `okstra error-log append-observed --error-type cli-failure ...` with the captured exit code, duration, message, and stderr excerpt. The wrapper subagent records this through its selected adapter Lead does NOT need to re-record. Token usage is not inferred from dispatch return values; call `collect_usage` at the start of Phase 7.
247
+ `--agent`, `--agent-role`, and `--error-type` are **closed enums**, not free-form labelsthe role names used elsewhere in these contracts (`Codex worker`, `Claude worker`) are rejected. Use exactly:
248
+
249
+ - `--agent` — `claude-worker` | `codex-worker` | `antigravity-worker` | `report-writer`
250
+ - `--agent-role` — `lead` | `worker` | `report-writer`
251
+ - `--error-type` — `cli-failure` | `contract-violation` | `tool-failure`
252
+
253
+ For a lead-attributed event there is no value in the list above — the selected adapter names the lead identity to pass.
254
+
255
+ For Codex/Antigravity wrappers: if the CLI returns non-zero, times out, or hits a rate limit, immediately call `append-observed` with the captured exit code, duration, message, and stderr excerpt. `append-observed` additionally requires `--phase`, `--command`, and `--command-kind`, so copy this form rather than trimming the one above:
256
+
257
+ ```bash
258
+ okstra error-log append-observed \
259
+ --out <absolute-errors-log-path-from-launch-prompt> \
260
+ --task-key <taskKey> --phase 5.5 \
261
+ --agent codex-worker --agent-role worker --model <model> \
262
+ --error-type cli-failure \
263
+ --command "okstra-codex-exec.sh <project-root> <model> <prompt-path>" \
264
+ --command-kind wrapper \
265
+ --exit-code 124 --duration-ms 1800000 \
266
+ --message "reverify-r1 wrapper never launched" \
267
+ --stderr-excerpt "<last stderr lines, or use --stderr-excerpt-file>"
268
+ ```
269
+
270
+ The wrapper subagent records this through its selected adapter — Lead does NOT need to re-record. Token usage is not inferred from dispatch return values; call `collect_usage` at the start of Phase 7.
248
271
 
249
272
  ## Phase 5.5: Convergence loop
250
273
 
@@ -43,7 +43,7 @@ The prompt MUST include, in this order at the top:
43
43
  - `**Errors sidecar path:** <absolute-path>` — this worker's per-run sidecar JSON (`worker-results/report-writer-worker-errors-<task-type>-<seq>.json`).
44
44
  7. `**Model:** Report writer worker, <modelExecutionValue>` (resolved per Phase 5.5 anchor-header rules)
45
45
  8. The full `[Required reading]` clause (see [team-contract](./team-contract.md)) — for Phase 6 it adds two **per-task-type, instruction-set-local** read-only files, both scoped to this run's task-type by `okstra-ctl` at prep time:
46
- - `<instruction-set>/final-report-schema.json` — a task-type excerpt of the data.json schema (the other task-types' deliverable blocks and their unreachable `$defs` are stripped; ~38% of the full schema is `$defs` alone). This is your authoring contract for the data.json shape. Do **NOT** pull the full `schemas/final-report-v1.0.schema.json` — it carries all task-types and its `schemas/...` path is not part of the task bundle. (Validation still runs against the full schema post-hoc via the renderer, so the excerpt never relaxes the contract.)
46
+ - `<instruction-set>/final-report-schema.json` — a task-type excerpt of the data.json schema (the other task-types' deliverable blocks and their unreachable `$defs` are stripped; ~38% of the full schema is `$defs` alone). This is your authoring aid for the data.json shape — the installed schema, not the excerpt, is what the run is judged against. Do **NOT** pull the full `schemas/final-report-v1.0.schema.json` — it carries all task-types and its `schemas/...` path is not part of the task bundle. (Validation still runs against the full schema post-hoc via the renderer, so the excerpt never relaxes the contract.)
47
47
  - `<instruction-set>/final-report-template.md` — the **phase-stripped** template (every other task-type's §5.x deliverable block removed by `render.py`'s `_strip_phase_blocks`, leaving only your run's §5.x). Do **NOT** also pull the full `templates/reports/final-report.template.md` source (it re-adds ~330 lines of other phases' deliverables and is not in the task bundle).
48
48
  9. A one-line MCP pointer instead of the verbatim block (redundant — the brief is already in the report-writer's Required reading, item 8): `**MCP servers:** follow the task brief's "## Available MCP Servers" section (already in your Required reading).`
49
49
  10. The convergence classifications (Full/Partial/Contested/Worker-Unique), the round history data (`roundHistory[]`), the `round2SkippedReason` value, and pointers to all worker result files under `worker-results/`. The report-writer worker populates `crossVerification.roundHistory` in the data.json so Section 6 can show which rounds executed, queue sizes, and why Round 2 was (or was not) skipped. The renderer prints the full per-round table only when more than one round ran; single-round or zero-round histories are auto-collapsed to a one-line summary.
@@ -118,6 +118,9 @@ After each worker subagent returns (regardless of role), Lead MUST verify the ca
118
118
  - The wrapper subagent returned an explicit `*_RESULT_MISSING` sentinel (codex-worker / antigravity-worker step 8c — `CODEX_RESULT_MISSING` / `ANTIGRAVITY_RESULT_MISSING`).
119
119
  - The result file is absent at the resolved absolute path even though the worker returned without a `*_RESULT_MISSING` sentinel — for example, claude-worker returned its final assistant message but never persisted the artifact, or the wrapper exited 0 and the codex/antigravity sub-agent forwarded raw stdout despite the contract.
120
120
  - The result file exists but cannot be parsed (frontmatter unreadable, sections 1–5 entirely missing). A truncated file in the middle of section 5 is NOT covered here — it goes to the validator's regular `error` path, not the retry path.
121
+ - `okstra worker-liveness` reports the worker `did-not-launch` — neither `<prompt-path>.log` nor `<prompt-path>.status.json` exists past the launch grace (default 60s). The wrapper writes its status sidecar before invoking the CLI and hard-fails loudly with a distinct exit code on every argument check before that, so the absence of BOTH artifacts means the dispatch itself never reached the script. Without this trigger the only evidence was a lead noticing two missing files by eye, and the run paid the full polling cap for a worker that never started.
122
+ - `okstra worker-liveness` reports the worker `stalled` — its audit sidecar's newest `- PROGRESS:` heartbeat is older than the cadence budget, or the sidecar carries no heartbeat at all. This is the in-process equivalent of the CLI wrappers' idle watchdog: the wrapper reaps a silent CLI itself, but nothing reaped a silent `claude-worker` until its deadline.
123
+ - The result file exists but its audit sidecar does not, at `runs/<task-type>/worker-results/<worker>-audit-<task-type>-<seq>.md`. Workers write both in the same step, so a result without a sidecar means the Reading Confirmation block — the only evidence the worker read its inputs — was never produced. `validate-run.py` fails the run on this at Phase 7 either way (`validate_worker_results_audit`); checking it here spends the existing one-retry budget while the role can still be re-dispatched, instead of surfacing hours later when the worker session is gone.
121
124
 
122
125
  **One-retry policy:**
123
126
 
@@ -70,7 +70,7 @@ profile document.
70
70
  - the same `final-report.md` file is the canonical artifact carried into the next run; the user appends answers inline before rerunning. The preferred turn-around is `scripts/okstra.sh --resume-clarification --task-key <project-id>:<task-group>:<task-id>` (opens the latest report in `$EDITOR`, then auto-reruns the same phase with `--clarification-response` carry-in). The lower-level form `--clarification-response <path>` remains available for scripted runs.
71
71
  - if a clarification response was carried in for this run, render the conditional `## 0. Clarification Response Carried In From Previous Run` section (the template's `RENDER_IF` guard activates it), walk every `C-*` row of the prior report's `## 1. Clarification Items` table, reconcile each one against new evidence, and update its `Status` to `resolved` or `obsolete` before issuing the next decision/verdict. When no carry-in path was provided, omit the `## 0.` heading entirely — the validator fails reports that emit an empty Section 0 stub (e.g. "No prior clarification response was provided for this run.").
72
72
  - Verdict Card (shared — applies to every final-report regardless of profile):
73
- - The top-of-report `## Verdict Card` block is mandatory in every final-report. Its `Verdict Token`, `Direction`, and `Next Step` cells MUST byte-match the corresponding cells in `## 7. Final Verdict` and the first item of `## 3. Recommended Next Steps`. The validator treats the card as a non-authoritative index when card values diverge from the authoritative sections, the run is `contract-violated`.
73
+ - The top-of-report `## Verdict Card` block is mandatory in every final-report. Its `Verdict Token` and `Direction` cells MUST byte-match the corresponding cells in `## 7. Final Verdict` — the card is a non-authoritative index and divergence makes the run `contract-violated`. **Enforced:** `validators/validate-run.py` `_validate_verdict_card_consistency` (token, on the rendered markdown) and `_validate_verdict_card_fields` (direction, on data.json). The `Next Step` cell points at the SAME action as `## 7. Final Verdict` and the first item of `## 3. Recommended Next Steps`, but is written as the actionable command the reader runs (`/okstra-run task-type=release-handoff`) where §7 states it as prose it is not a byte copy and is not compared.
74
74
  - Cross-worker traceability (shared — applies to every analysis worker output and to the lead's `## 6.` / `## 2.` tables in the final-report):
75
75
  - **Worker-side item IDs (free-form but unique within the worker).** Every row item in sections 1–5 (and any optional section 6) of an analysis worker's output MUST carry an item ID that is unique within that one worker's result file. The ID convention is the worker's choice — `F-001` / `F-002` per the suggested schema, `1.1` / `1.2` / `1.3` as Codex tends to use, or any other shape — but it MUST appear as the leading column of the row (for table-form items) or as a `[<ID>]` prefix (for bullet/numbered items). Workers that emit findings without IDs make cross-worker reconciliation impossible.
76
76
  - **Lead-side ID assignment + source preservation.** When the lead (or `report-writer-worker`) synthesises `## 6.1 Consensus` / `## 6.2 Differences` / `## 2.1 Primary Evidence` rows from worker outputs, the lead assigns a fresh `C-NNN` / `D-NNN` / `E-NNN` row ID. The `Source items` column (or, where the template still calls it `Supporting workers` / `Workers (position)` / `Source`, that same column) MUST list every contributing worker:item pair (e.g. `claude:F-001, codex:1.1, antigravity:F-3`) so a reviewer can trace the synthesised row back to each worker's original wording without re-reading every worker-results file. Bare worker names without item IDs (e.g. `claude, codex, antigravity`) are deprecated for these tables; the validator does not yet fail on them but the readability pass treats it as a contract violation.
@@ -180,11 +180,28 @@ def _stage_rows(planning: Mapping[str, Any]) -> dict[int, Mapping[str, Any]]:
180
180
  return rows
181
181
 
182
182
 
183
- def _stage_for_selected_path(
183
+ _LINE_RANGE_SUFFIX = re.compile(r":\d+(?:-\d+)?$")
184
+
185
+
186
+ def _stages_for_selected_path(
184
187
  path: str,
185
188
  stages: Mapping[int, Mapping[str, Any]],
186
- ) -> int:
187
- normalised = _normalise(path)
189
+ ) -> list[int]:
190
+ """Every stage whose stepwise ``files`` cells touch *path*.
191
+
192
+ A file legitimately edited by more than one stage — the task-level
193
+ ``qa/conformance-manifest.json`` is the standard case, since each
194
+ conformance-declaring stage registers its own entry — yields one design
195
+ surface per stage, which is what the consumer keys on. Requiring a single
196
+ owner instead would force the plan to hide an edit, collapse stage
197
+ boundaries, or re-add the line-range suffixes that used to disambiguate
198
+ stages by accident.
199
+
200
+ Zero stages is still an error: the recommended option declares a file that
201
+ no step creates or edits.
202
+ """
203
+ normalised = _LINE_RANGE_SUFFIX.sub("", _normalise(path))
204
+ path_pattern = rf"(?<![\w./@-]){re.escape(normalised)}(?![\w./@-])"
188
205
  matched = []
189
206
  for stage_number, stage in stages.items():
190
207
  files = [
@@ -192,14 +209,13 @@ def _stage_for_selected_path(
192
209
  for step in stage.get("stepwiseExecution") or []
193
210
  if isinstance(step, Mapping)
194
211
  ]
195
- path_pattern = rf"(?<![\w./@-]){re.escape(normalised)}(?![\w./@-])"
196
212
  if any(re.search(path_pattern, cell) is not None for cell in files):
197
213
  matched.append(stage_number)
198
- if len(matched) != 1:
214
+ if not matched:
199
215
  raise DesignSurfaceError(
200
- f"selected option path {path!r} is not mapped to a stage exactly once"
216
+ f"selected option path {path!r} is not mapped to a stage"
201
217
  )
202
- return matched[0]
218
+ return matched
203
219
 
204
220
 
205
221
  def detect_design_surfaces(
@@ -226,13 +242,13 @@ def detect_design_surfaces(
226
242
  if not isinstance(row, Mapping):
227
243
  continue
228
244
  path = str(row.get("path") or "")
229
- stage_number = _stage_for_selected_path(path, stages)
230
- for kind, evidence in _matching_rule_evidence(
231
- step=None,
232
- field="files",
233
- value=path,
234
- ):
235
- grouped.setdefault((stage_number, kind), []).append(evidence)
245
+ for stage_number in _stages_for_selected_path(path, stages):
246
+ for kind, evidence in _matching_rule_evidence(
247
+ step=None,
248
+ field="files",
249
+ value=path,
250
+ ):
251
+ grouped.setdefault((stage_number, kind), []).append(evidence)
236
252
  rule_order = {rule.kind: index for index, rule in enumerate(RULES)}
237
253
  return [
238
254
  DesignSurfaceTrigger(stage, kind, tuple(grouped[(stage, kind)]))
@@ -52,6 +52,8 @@ from okstra_ctl.final_report_schema import SchemaError, load_schema, validate as
52
52
  from okstra_ctl.i18n import I18nError, SUPPORTED_LANGS, load_dictionary, make_jinja_global
53
53
  from okstra_ctl.md_table import UNESCAPED_PIPE_RE, escape_pipes
54
54
  from okstra_ctl.models import UnknownModelError, resolve_model_metadata
55
+ from okstra_ctl.schema_excerpt import excerpt_cut_from_version
56
+ from okstra_ctl.seeding import installed_version
55
57
 
56
58
 
57
59
  DEFAULT_TEMPLATE_REL = ("templates", "reports", "final-report.template.md")
@@ -125,6 +127,21 @@ def _yaml_inline_list(values: list[str]) -> str:
125
127
  return "[" + ", ".join(_yaml_scalar(v) for v in values) + "]"
126
128
 
127
129
 
130
+ def _md_quote(value: str | None, width: int = 2) -> str:
131
+ """Re-mark every continuation line of a multi-line blockquote value.
132
+
133
+ The template supplies the first line's `` > ``; lines 2..n arrive at
134
+ column 0, where they end the enclosing list item and drag the bullets
135
+ that follow into one run-on paragraph.
136
+ """
137
+ text = "" if value is None else str(value)
138
+ pad = " " * width
139
+ lines = text.split("\n")
140
+ return "\n".join(
141
+ [lines[0]] + [f"{pad}>{' ' + line if line else ''}" for line in lines[1:]]
142
+ )
143
+
144
+
128
145
  # --- Index / scroll-anchor post-render pass -------------------------------
129
146
  # After Jinja2 renders the body, every report gets a top-of-report index and
130
147
  # clickable scroll anchors. An ID is *defined* when it is the leading token of
@@ -424,6 +441,11 @@ def _build_environment(template_dir: Path) -> Environment:
424
441
  # cannot split a markdown table row. Table-cell interpolations only —
425
442
  # never code blocks / headings / prose, where `\|` would render verbatim.
426
443
  env.filters["mdcell"] = escape_pipes
444
+ # `mdquote` re-marks continuation lines of a blockquote nested in a list
445
+ # item; the fenced siblings use Jinja's builtin `indent` for the same
446
+ # reason. Both exist because only the first line of an interpolation
447
+ # inherits the template's leading indent.
448
+ env.filters["mdquote"] = _md_quote
427
449
  return env
428
450
 
429
451
 
@@ -516,6 +538,47 @@ def find_default_template(start: Path | None = None) -> Path:
516
538
  )
517
539
 
518
540
 
541
+ def _bundle_excerpt_path(data_path: Path) -> Path | None:
542
+ """The task bundle's schema excerpt, found by walking up from *data_path*."""
543
+ for ancestor in data_path.resolve().parents:
544
+ candidate = ancestor / "instruction-set" / "final-report-schema.json"
545
+ if candidate.is_file():
546
+ return candidate
547
+ return None
548
+
549
+
550
+ def _with_excerpt_drift_hint(
551
+ exc: FinalReportRenderError, data_path: Path
552
+ ) -> FinalReportRenderError:
553
+ """Name the version skew behind a schema failure, when that is the cause.
554
+
555
+ A long run straddles its own runtime upgrade: the report-writer authors
556
+ against the excerpt frozen into the bundle at prep time, while the renderer
557
+ validates against the installed schema. Without this the author sees only
558
+ `additional property ... not allowed` for a field the excerpt told it to
559
+ write, and has no way to tell a real mistake from a stale bundle.
560
+ """
561
+ if "schema validation" not in str(exc):
562
+ return exc
563
+ excerpt_path = _bundle_excerpt_path(data_path)
564
+ if excerpt_path is None:
565
+ return exc
566
+ try:
567
+ cut_from = excerpt_cut_from_version(
568
+ json.loads(excerpt_path.read_text(encoding="utf-8"))
569
+ )
570
+ except (OSError, json.JSONDecodeError):
571
+ return exc
572
+ current = installed_version()
573
+ if not cut_from or not current or cut_from == current:
574
+ return exc
575
+ return FinalReportRenderError(
576
+ f"{exc} — the bundle's schema excerpt ({excerpt_path}) was cut from okstra "
577
+ f"{cut_from} but validation ran on {current}; author against the installed "
578
+ "schema, not the excerpt, or re-prepare the bundle."
579
+ )
580
+
581
+
519
582
  def render_to_file(
520
583
  data_path: Path,
521
584
  output_path: Path,
@@ -542,11 +605,14 @@ def render_to_file(
542
605
  # 설치본에서 항상 'could not locate template' 으로 실패한다(OKSTRA_HOME 을
543
606
  # 수동 설정해야 했던 원인). 프로젝트별 override 는 --template 으로 한다.
544
607
  resolved_template = template_path or find_default_template()
545
- rendered = render(
546
- data,
547
- template_path=resolved_template,
548
- report_language=report_language,
549
- )
608
+ try:
609
+ rendered = render(
610
+ data,
611
+ template_path=resolved_template,
612
+ report_language=report_language,
613
+ )
614
+ except FinalReportRenderError as exc:
615
+ raise _with_excerpt_drift_hint(exc, data_path) from exc
550
616
 
551
617
  output_path.parent.mkdir(parents=True, exist_ok=True)
552
618
  tmp = output_path.with_suffix(output_path.suffix + f".tmp.{os.getpid()}")
@@ -1709,7 +1709,9 @@ def _render_lead_prompt_and_snapshot(
1709
1709
  # still has the phase-stripped template + skill structure guide, and
1710
1710
  # validation runs against the full schema regardless.
1711
1711
  try:
1712
- _excerpt = build_schema_excerpt(load_schema(), inp.task_type)
1712
+ _excerpt = build_schema_excerpt(
1713
+ load_schema(), inp.task_type, installed_version()
1714
+ )
1713
1715
  Path(ctx["FINAL_REPORT_SCHEMA_PATH"]).write_text(
1714
1716
  json.dumps(_excerpt, indent=2, ensure_ascii=False) + "\n",
1715
1717
  encoding="utf-8",
@@ -72,7 +72,16 @@ def _conditional_applies(entry: dict, task_type: str) -> bool:
72
72
  return task_type in (enum or [])
73
73
 
74
74
 
75
- def build_schema_excerpt(schema: dict, task_type: str) -> dict:
75
+ EXCERPT_VERSION_KEY = "x-okstraCutFromVersion"
76
+
77
+
78
+ def excerpt_cut_from_version(excerpt: dict) -> str:
79
+ """The okstra version *excerpt* was cut from; empty when unstamped."""
80
+ value = excerpt.get(EXCERPT_VERSION_KEY)
81
+ return value if isinstance(value, str) else ""
82
+
83
+
84
+ def build_schema_excerpt(schema: dict, task_type: str, cut_from_version: str = "") -> dict:
76
85
  """Return a task-type-scoped copy of *schema*.
77
86
 
78
87
  Drops the per-type property blocks that do not belong to *task_type*,
@@ -81,6 +90,11 @@ def build_schema_excerpt(schema: dict, task_type: str) -> dict:
81
90
  def reachable from a kept property or conditional). Top-level metadata
82
91
  and ``required`` are preserved (``required`` never lists per-type
83
92
  blocks, but it is filtered defensively).
93
+
94
+ *cut_from_version* stamps the excerpt with the runtime that produced it.
95
+ Bundle prep and report render can be hours apart and the runtime upgrades
96
+ itself in between, so a mismatch is what turns an opaque "additional
97
+ property … not allowed" into "the bundle excerpt is from an older okstra".
84
98
  """
85
99
  keep_per_type = _TASK_TYPE_PROPERTY.get(task_type)
86
100
  drop_props = _ALL_PER_TYPE_PROPERTIES - ({keep_per_type} if keep_per_type else set())
@@ -119,4 +133,6 @@ def build_schema_excerpt(schema: dict, task_type: str) -> dict:
119
133
  excerpt["allOf"] = all_of
120
134
  if reachable:
121
135
  excerpt["$defs"] = {k: v for k, v in defs.items() if k in reachable}
136
+ if cut_from_version:
137
+ excerpt[EXCERPT_VERSION_KEY] = cut_from_version
122
138
  return excerpt
@@ -0,0 +1,50 @@
1
+ """Heartbeat primitives shared by the live liveness probe and the Phase 7 audit.
2
+
3
+ `claude-worker` appends `- PROGRESS: <stage> <ISO-8601-UTC>` lines to its audit
4
+ sidecar so a silent hang is visible while the run is still recoverable. The
5
+ Phase 7 validator has always parsed those lines post-hoc; `worker_liveness`
6
+ reads them mid-run. Both must agree on what "stale" means, so the line shape and
7
+ the cadence budget live here rather than in either consumer.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from datetime import datetime, timezone
13
+ from pathlib import Path
14
+
15
+ # claude-worker audit 사이드카의 heartbeat 라인 (claude-worker.md "Heartbeat").
16
+ HEARTBEAT_LINE_RE = re.compile(
17
+ r"^-[ \t]*PROGRESS:[ \t]*(?P<stage>\S+)[ \t]+(?P<ts>\S+)[ \t]*$", re.MULTILINE
18
+ )
19
+
20
+ # 계약상 cadence 는 5분. append 직전 측정한 시각과 실제 쓰기 사이 지연을 흡수하는
21
+ # 고정 grace 60초를 더한다.
22
+ HEARTBEAT_MAX_GAP_SECONDS = 5 * 60 + 60
23
+
24
+
25
+ def parse_timestamp(raw: str) -> datetime | None:
26
+ """A heartbeat's ISO-8601 timestamp as an aware datetime, or None."""
27
+ try:
28
+ parsed = datetime.fromisoformat(raw.replace("Z", "+00:00"))
29
+ except ValueError:
30
+ return None
31
+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
32
+
33
+
34
+ def latest_heartbeat(sidecar: Path) -> datetime | None:
35
+ """The newest parseable heartbeat in *sidecar*, or None when it has none.
36
+
37
+ Takes the maximum rather than the last line: a regressing timestamp is the
38
+ Phase 7 validator's finding to report, and treating it as "stale" here would
39
+ kill a worker that is in fact still writing.
40
+ """
41
+ try:
42
+ text = sidecar.read_text(encoding="utf-8")
43
+ except OSError:
44
+ return None
45
+ stamps = [
46
+ parsed
47
+ for match in HEARTBEAT_LINE_RE.finditer(text)
48
+ if (parsed := parse_timestamp(match.group("ts"))) is not None
49
+ ]
50
+ return max(stamps) if stamps else None