okstra 0.232.0 → 0.233.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 (183) hide show
  1. package/README.md +19 -283
  2. package/dist/cli-registry.mjs +8 -1
  3. package/dist/cli-registry.mjs.map +1 -1
  4. package/dist/commands/execute/render-bundle.d.mts +6 -1
  5. package/dist/commands/execute/render-bundle.mjs +139 -32
  6. package/dist/commands/execute/render-bundle.mjs.map +1 -1
  7. package/dist/commands/lifecycle/config.mjs +6 -74
  8. package/dist/commands/lifecycle/config.mjs.map +1 -1
  9. package/dist/commands/trace/capacity.d.mts +12 -0
  10. package/dist/commands/trace/capacity.mjs +21 -0
  11. package/dist/commands/trace/capacity.mjs.map +1 -0
  12. package/dist/commands/trace/model.d.mts +89 -0
  13. package/dist/commands/trace/model.mjs +251 -0
  14. package/dist/commands/trace/model.mjs.map +1 -0
  15. package/dist/commands/trace/progression.d.mts +11 -0
  16. package/dist/commands/trace/progression.mjs +194 -0
  17. package/dist/commands/trace/progression.mjs.map +1 -0
  18. package/dist/commands/trace/review.d.mts +7 -0
  19. package/dist/commands/trace/review.mjs +51 -0
  20. package/dist/commands/trace/review.mjs.map +1 -0
  21. package/dist/commands/trace/task-link.d.mts +18 -0
  22. package/dist/commands/trace/task-link.mjs +72 -0
  23. package/dist/commands/trace/task-link.mjs.map +1 -0
  24. package/dist/commands/trace/trace.d.mts +1 -0
  25. package/dist/commands/trace/trace.mjs +293 -0
  26. package/dist/commands/trace/trace.mjs.map +1 -0
  27. package/dist/lib/bounded-file.d.mts +1 -0
  28. package/dist/lib/bounded-file.mjs +36 -0
  29. package/dist/lib/bounded-file.mjs.map +1 -0
  30. package/dist/lib/config-store.d.mts +34 -0
  31. package/dist/lib/config-store.mjs +70 -0
  32. package/dist/lib/config-store.mjs.map +1 -0
  33. package/dist/lib/file-lock.mjs +4 -5
  34. package/dist/lib/file-lock.mjs.map +1 -1
  35. package/dist/lib/input-limit.d.mts +4 -0
  36. package/dist/lib/input-limit.mjs +8 -0
  37. package/dist/lib/input-limit.mjs.map +1 -0
  38. package/dist/lib/memory-auto-register.mjs +2 -17
  39. package/dist/lib/memory-auto-register.mjs.map +1 -1
  40. package/dist/lib/report-language-tag.d.mts +1 -0
  41. package/dist/lib/report-language-tag.mjs +4 -0
  42. package/dist/lib/report-language-tag.mjs.map +1 -0
  43. package/dist/lib/report-language.d.mts +1 -0
  44. package/dist/lib/report-language.mjs +50 -0
  45. package/dist/lib/report-language.mjs.map +1 -0
  46. package/dist/lib/skill-catalog.mjs +3 -0
  47. package/dist/lib/skill-catalog.mjs.map +1 -1
  48. package/docs/architecture/storage-model.md +36 -5
  49. package/docs/architecture.md +10 -4
  50. package/docs/cli.md +279 -2
  51. package/docs/contributor-change-matrix.md +1 -2
  52. package/docs/project-structure-overview.md +31 -41
  53. package/package.json +1 -1
  54. package/runtime/BUILD.json +2 -2
  55. package/runtime/agents/operations/trace-interface-review.json +6 -0
  56. package/runtime/agents/operations/trace-scope-review.json +6 -0
  57. package/runtime/prompts/coding-preflight/authoring-checks.md +1 -1
  58. package/runtime/prompts/coding-preflight/clean-code.md +18 -20
  59. package/runtime/prompts/coding-preflight/overview.md +1 -1
  60. package/runtime/prompts/duties/code-reviewer.json +1 -1
  61. package/runtime/prompts/duties/interface-reviewer.json +32 -0
  62. package/runtime/prompts/host-orchestration/README.md +18 -9
  63. package/runtime/prompts/launch.template.md +3 -2
  64. package/runtime/prompts/lead/context-loader.md +2 -0
  65. package/runtime/prompts/lead/okstra-lead-contract.md +7 -7
  66. package/runtime/prompts/lead/report-writer.md +6 -6
  67. package/runtime/prompts/profiles/_coding-conventions-preflight.md +2 -2
  68. package/runtime/prompts/profiles/_common-contract.md +1 -1
  69. package/runtime/python/okstra_ctl/agent/invocation.py +1 -0
  70. package/runtime/python/okstra_ctl/agent/prompt_cli/cli.py +66 -26
  71. package/runtime/python/okstra_ctl/agent/prompt_cli/corrections.py +23 -8
  72. package/runtime/python/okstra_ctl/agent/prompt_cli/materialize.py +28 -10
  73. package/runtime/python/okstra_ctl/agent/prompt_cli/results.py +8 -11
  74. package/runtime/python/okstra_ctl/agent/standalone.py +12 -0
  75. package/runtime/python/okstra_ctl/analysis_packet.py +22 -11
  76. package/runtime/python/okstra_ctl/code_review_census.py +93 -2
  77. package/runtime/python/okstra_ctl/code_review_prepare.py +381 -0
  78. package/runtime/python/okstra_ctl/code_review_run.py +384 -0
  79. package/runtime/python/okstra_ctl/code_review_scope.py +13 -0
  80. package/runtime/python/okstra_ctl/code_review_supervisor.py +41 -0
  81. package/runtime/python/okstra_ctl/code_review_target.py +140 -15
  82. package/runtime/python/okstra_ctl/coverage_census.py +11 -2
  83. package/runtime/python/okstra_ctl/design_snapshot.py +16 -9
  84. package/runtime/python/okstra_ctl/direct_work.py +45 -3
  85. package/runtime/python/okstra_ctl/dispatch_core.py +31 -15
  86. package/runtime/python/okstra_ctl/dispatch_state.py +9 -2
  87. package/runtime/python/okstra_ctl/domain/role.py +1 -0
  88. package/runtime/python/okstra_ctl/doyouknow/sources/manager.py +48 -9
  89. package/runtime/python/okstra_ctl/final_report_schema.py +37 -34
  90. package/runtime/python/okstra_ctl/incremental_carry.py +6 -7
  91. package/runtime/python/okstra_ctl/initial_prompt_materialization.py +9 -2
  92. package/runtime/python/okstra_ctl/json_boundary.py +33 -6
  93. package/runtime/python/okstra_ctl/manager_cli.py +122 -1
  94. package/runtime/python/okstra_ctl/manager_journal.py +126 -0
  95. package/runtime/python/okstra_ctl/manager_launch.py +3 -3
  96. package/runtime/python/okstra_ctl/manager_log.py +221 -0
  97. package/runtime/python/okstra_ctl/manager_paths.py +8 -0
  98. package/runtime/python/okstra_ctl/manager_resume.py +59 -0
  99. package/runtime/python/okstra_ctl/manager_split.py +2 -2
  100. package/runtime/python/okstra_ctl/manager_store.py +116 -17
  101. package/runtime/python/okstra_ctl/manager_sync.py +42 -3
  102. package/runtime/python/okstra_ctl/manager_view.py +35 -2
  103. package/runtime/python/okstra_ctl/material.py +2 -0
  104. package/runtime/python/okstra_ctl/model_cli.py +64 -14
  105. package/runtime/python/okstra_ctl/model_defaults.py +22 -0
  106. package/runtime/python/okstra_ctl/model_io/renderers.py +3 -0
  107. package/runtime/python/okstra_ctl/operation_invocation.py +207 -28
  108. package/runtime/python/okstra_ctl/path_hints.py +14 -3
  109. package/runtime/python/okstra_ctl/paths.py +6 -1
  110. package/runtime/python/okstra_ctl/phases/catalog.py +24 -7
  111. package/runtime/python/okstra_ctl/phases/implementation/host-rules.md +3 -3
  112. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-diff-review.md +8 -6
  113. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-self-check.md +1 -1
  114. package/runtime/python/okstra_ctl/phases/implementation_option_selection/profile.md +1 -1
  115. package/runtime/python/okstra_ctl/phases/implementation_option_selection/votes.py +11 -11
  116. package/runtime/python/okstra_ctl/phases/implementation_planning/authoring.py +12 -9
  117. package/runtime/python/okstra_ctl/phases/implementation_planning/host-rules.md +3 -6
  118. package/runtime/python/okstra_ctl/phases/implementation_planning/instructions/plan-body-verification.md +12 -10
  119. package/runtime/python/okstra_ctl/phases/implementation_planning/profile.md +5 -5
  120. package/runtime/python/okstra_ctl/phases/improvement_discovery/lenses.py +12 -0
  121. package/runtime/python/okstra_ctl/phases/improvement_discovery/profile.md +7 -6
  122. package/runtime/python/okstra_ctl/phases/improvement_discovery/resolved_census.py +159 -0
  123. package/runtime/python/okstra_ctl/phases/improvement_discovery/spec.md +5 -2
  124. package/runtime/python/okstra_ctl/phases/improvement_discovery/validation.py +21 -7
  125. package/runtime/python/okstra_ctl/phases/release_handoff/boundary.json +1 -1
  126. package/runtime/python/okstra_ctl/phases/release_handoff/profile.md +4 -1
  127. package/runtime/python/okstra_ctl/plan_verify_cli.py +6 -4
  128. package/runtime/python/okstra_ctl/render.py +28 -2
  129. package/runtime/python/okstra_ctl/report_assembly.py +38 -11
  130. package/runtime/python/okstra_ctl/report_contract.py +26 -0
  131. package/runtime/python/okstra_ctl/report_corrections.py +36 -20
  132. package/runtime/python/okstra_ctl/report_inputs.py +1 -0
  133. package/runtime/python/okstra_ctl/report_language.py +4 -1
  134. package/runtime/python/okstra_ctl/report_narrative.py +179 -7
  135. package/runtime/python/okstra_ctl/report_projections.py +64 -18
  136. package/runtime/python/okstra_ctl/report_synthesis_packet.py +86 -36
  137. package/runtime/python/okstra_ctl/run.py +43 -35
  138. package/runtime/python/okstra_ctl/run_context.py +10 -1
  139. package/runtime/python/okstra_ctl/set_work_status.py +4 -15
  140. package/runtime/python/okstra_ctl/task_list_cli.py +34 -8
  141. package/runtime/python/okstra_ctl/task_query.py +239 -0
  142. package/runtime/python/okstra_ctl/trace_review.py +264 -0
  143. package/runtime/python/okstra_ctl/trace_tasks.py +197 -0
  144. package/runtime/python/okstra_ctl/user_authorization.py +14 -0
  145. package/runtime/python/okstra_ctl/wizard/confirmation.py +7 -3
  146. package/runtime/python/okstra_ctl/wizard/launch.py +52 -0
  147. package/runtime/python/okstra_ctl/wizard/launch_cli.py +39 -0
  148. package/runtime/python/okstra_ctl/wizard/outcome.py +17 -16
  149. package/runtime/python/okstra_ctl/wizard/registry.py +1 -1
  150. package/runtime/python/okstra_ctl/wizard/render.py +8 -0
  151. package/runtime/python/okstra_ctl/wizard/state.py +2 -1
  152. package/runtime/python/okstra_project/state.py +20 -0
  153. package/runtime/python/okstra_token_usage/blocks.py +74 -0
  154. package/runtime/python/okstra_token_usage/cli.py +23 -10
  155. package/runtime/python/okstra_token_usage/collect.py +25 -22
  156. package/runtime/python/okstra_token_usage/policy.py +193 -0
  157. package/runtime/schemas/report-synthesis-packet-v1.0.schema.json +1 -1
  158. package/runtime/skills/_fragments/wizard-confirm-step.md +1 -1
  159. package/runtime/skills/_fragments/wizard-preflight.md +1 -1
  160. package/runtime/skills/_fragments/wizard-prompt-loop.md +3 -5
  161. package/runtime/skills/_fragments/wizard-relay-protocol.md +1 -1
  162. package/runtime/skills/_fragments/wizard-render-bundle.md +15 -29
  163. package/runtime/skills/okstra-brief-gen/SKILL.md +7 -7
  164. package/runtime/skills/okstra-brief-gen/references/tracker-recursion.md +1 -1
  165. package/runtime/skills/okstra-code-review/SKILL.md +58 -50
  166. package/runtime/skills/okstra-code-review/references/census-rules.md +6 -6
  167. package/runtime/skills/okstra-code-review/references/review-calibration.md +8 -12
  168. package/runtime/skills/okstra-discussion/SKILL.md +22 -38
  169. package/runtime/skills/okstra-explain-flow/SKILL.md +6 -2
  170. package/runtime/skills/okstra-manager/SKILL.md +24 -0
  171. package/runtime/skills/okstra-memory/SKILL.md +1 -1
  172. package/runtime/skills/okstra-pr-gen/SKILL.md +1 -1
  173. package/runtime/skills/okstra-run/SKILL.md +55 -183
  174. package/runtime/skills/okstra-schedule-gen/SKILL.md +9 -13
  175. package/runtime/skills/okstra-setup/SKILL.md +3 -2
  176. package/runtime/skills/okstra-setup/references/project-config.md +2 -4
  177. package/runtime/skills/okstra-tdd/SKILL.md +187 -0
  178. package/runtime/skills/okstra-user-response/SKILL.md +4 -2
  179. package/runtime/templates/manager/view.template.html +4 -0
  180. package/runtime/templates/report-writer-prompt-preamble.md +15 -3
  181. package/runtime/templates/trace/trace.template.md +42 -0
  182. package/runtime/validators/checks/fixtures-02.py +25 -33
  183. package/runtime/validators/validate-run.py +93 -36
@@ -1,6 +1,8 @@
1
1
  """Improvement discovery lens vocabulary and candidate bounds."""
2
2
  from __future__ import annotations
3
3
 
4
+ from collections.abc import Sequence
5
+
4
6
  LENSES: tuple[str, ...] = (
5
7
  "performance",
6
8
  "security",
@@ -16,6 +18,7 @@ DEFAULT_CANDIDATE_CAP = 8
16
18
  ABSOLUTE_CANDIDATE_CAP = 12
17
19
  MIN_PRIORITY_LENSES = 1
18
20
  MAX_PRIORITY_LENSES = 4
21
+ RESOLVED_LENSES_POLICY = "resolved-lenses-v1"
19
22
 
20
23
  # report-writer is the AUTHOR of the final report; it never produces source
21
24
  # findings. validators reject `report-writer:<id>` entries in Source workers.
@@ -25,3 +28,12 @@ SOURCE_WORKERS: tuple[str, ...] = ("claude", "codex", "antigravity")
25
28
  def is_valid_lens(value: str) -> bool:
26
29
  return value in LENSES
27
30
 
31
+
32
+ def validate_priority_lenses(values: Sequence[str]) -> tuple[str, ...]:
33
+ lenses = tuple(values)
34
+ if not MIN_PRIORITY_LENSES <= len(lenses) <= MAX_PRIORITY_LENSES:
35
+ raise ValueError("resolved lenses must contain one to four lenses")
36
+ if len(set(lenses)) != len(lenses) or any(lens not in LENSES for lens in lenses):
37
+ raise ValueError("resolved lenses must be unique values from the lens whitelist")
38
+ return lenses
39
+
@@ -6,7 +6,7 @@
6
6
  - this phase REQUIRES a codebase-scan brief whose frontmatter contains `scope: codebase`. A brief without that marker is rejected before worker dispatch.
7
7
  - the brief's `priority-lenses` MUST be a non-empty subset (size 1..4) of the lens whitelist defined in `scripts/okstra_ctl/phases/improvement_discovery/lenses.py`. Lenses outside the whitelist are rejected.
8
8
  - the brief's `scan-scope` defines the only paths workers may read for candidate evidence. `out-of-scope` paths MUST be ignored even when the codebase is otherwise reachable.
9
- - the brief's `candidate-cap` (default 8 if absent, absolute cap 12) bounds the number of rows in `## 5.9 Improvement Candidates`.
9
+ - the brief's `candidate-cap` (default 8 if absent, absolute cap 12) bounds `improvementDiscovery.candidates[]` in structured reports and the candidate-table rows in legacy Markdown reports without a data file.
10
10
  - Apply the shared reporter-confirmation precondition as written. For this phase any unresolved `intent-check:` / `conversion-block:` row uses `Blocks=next-phase`.
11
11
  - read `Related Task Graph` before candidate discovery. If a candidate overlaps an existing linked task, preserve the edge in the candidate notes and prefer `related-to` / `follow-up-of` routing over emitting a duplicate standalone task.
12
12
  - Primary focus areas:
@@ -33,6 +33,7 @@
33
33
  - For each open question Lead asks ONE `AskUserQuestion` with a `(Recommended)` answer drawn from a codebase-first inspection. Budget: at most 12 questions in this phase.
34
34
  - Stop conditions (OR): all questions resolved / budget exhausted / user signals proceed.
35
35
  - Lead persists the round at `<RUN_DIR>/state/phase-1.5-grilling.md` with one section per question (question / recommended / user answer) and a closing `Resolved scope` / `Resolved lenses` block. Worker prompts use this resolved block as the authoritative scope and lens definition.
36
+ - In new runs declaring `coverageCensusPolicy: resolved-lenses-v1`, write exactly one `## Resolved lenses` section containing one bare `- <lens>` bullet per selected lens, in resolved order, with one to four distinct whitelist values. Keep explanations in other sections. Before the first analysis prompt is published, `resolved_census.prepare_resolved_lens_census()` freezes those cells and their source fingerprint into the run census and completes the packet. Subsequent prompt calls reuse that census; changing the resolved log or frozen packet is rejected. Do not manually edit either frozen artifact. Runs without this policy retain their saved worklist.
36
37
  - The same log includes `## Primary Pass Assignments` with a `Worker ID | Primary lens` table. It contains every selected analyser exactly once in `workerRoles` order; the lead derives it from the resolved roster and lenses rather than provider catalog order.
37
38
  - After writing the log and before Phase 4 dispatch, the lead injects its **absolute path** into every analyser prompt as the `**Phase 1.5 Grilling Log:** <absolute-path>` anchor header (see `okstra_ctl.worker_prompt_headers.worker_prompt_headers()`). This is the improvement-discovery counterpart to the `**Worktree:**` / `**Verification …:**` anchors that implementation / final-verification inject: workers read the log from this explicit path rather than re-deriving `<RUN_DIR>`. The path is byte-identical across all analysers, so it does not break the dispatch-prompt invariant.
38
39
  - Decision-tree walk (bounded):
@@ -43,11 +44,11 @@
43
44
  - uncertainty and overlap relationships kept explicit for downstream consensus classification
44
45
  - every candidate's `Expected behavior after` is checked against the brief's `## Preserved Behavior` items before the row is written. A candidate whose observable change contradicts a `PB-NNN` item is dropped, or raised as a `## 1. Clarification Items` row — never softened into a vaguer cell. The scan brief's PB set is the upper bound on what this phase may propose changing.
45
46
  - Report assembly instructions:
46
- - current branch — `schemaVersion: 2.0`: author the structured data contract below and let the independent renderers produce the full reading copy and task-specific human HTML.
47
- - v1 legacy branch: when validating or rerendering an existing schema-v1 report, preserve its `## 5.9 Improvement Candidates` table and legacy Markdown contract; do not rewrite that historical data into v2 implicitly.
48
- - the `## 5.9 Improvement Candidates` table populated with rows that obey the 11-column schema from `scripts/okstra_ctl/phases/improvement_discovery/validation.py` (Cand ID `I-NNN`, Lens from whitelist, Title, Scope ⊆ scan-scope, Severity, Effort, Consensus, Source workers `<worker>:<id>` from {claude, codex, antigravity}, Recommended next-phase ∈ {requirements-discovery, implementation-option-selection, error-analysis}, Expected behavior after, Evidence as path:line list). `Expected behavior after` states, in one observable sentence, what becomes different once the candidate is applied — it is the seed of the downstream brief's `EB-NNN` / `EO-NNN`. A candidate you cannot write this cell for is a preference, not a finding: drop it rather than filling the cell with a restatement of the title.
49
- - `Consensus` cells in `## 5.9 Improvement Candidates` use the table enum exactly: `full`, `partial`, `contested`, `worker-unique`. Map convergence's `full-consensus` / `partial-consensus` labels to `full` / `partial` before writing the table.
50
- - Verdict Token — **branch-specific, and the two branches do not share a vocabulary.** On the current v2 branch use the shared analysis enum: `analysis-complete` when every resolved lens was examined, `analysis-partial` when one could not be, `blocked` when the scan itself could not run. `schemas/final-report-v2.0.schema.json` admits only those three for `finalVerdict.verdictToken` — the report's single verdict-token home — so a v2 report carrying `candidates-ready` fails Phase 7. **Finding no candidates is not a verdict**: it is an empty `candidates[]` plus a `lensCoverage[]` row per lens with `status: no-candidate` and its evidence-backed rationale — the verdict stays `analysis-complete`. `candidates-ready` / `no-candidates` belong to the v1 legacy `## 7. Final Verdict` Markdown alone, where `scripts/okstra_ctl/phases/improvement_discovery/validation.py` enforces them. Continuation guidance is owned by `prompts/lead/phase-routing.md`.
47
+ - current branch — `schemaVersion: 3.0`, with structured 2.0 reading compatibility: author the structured data contract below and let the independent renderers produce the full reading copy and task-specific human HTML.
48
+ - legacy Markdown without a companion data file: preserve its `## 5.9 Improvement Candidates` table and legacy contract when validating or rerendering; do not implicitly migrate historical records. Structured reports do not need those numbered headings.
49
+ - `improvementDiscovery.candidates[]` retains 11 logical fields checked by `scripts/okstra_ctl/phases/improvement_discovery/validation.py`: ID `I-NNN`, Lens from whitelist, Title, Scope ⊆ scan-scope, Severity, Effort, Consensus, Source workers `<worker>:<id>` from {claude, codex, antigravity}, Recommended next-phase ∈ {requirements-discovery, implementation-option-selection, error-analysis}, Expected behavior after, and Evidence as path:line list. Legacy Markdown represents these fields as eleven table columns. `Expected behavior after` states, in one observable sentence, what becomes different once the candidate is applied — it is the seed of the downstream brief's `EB-NNN` / `EO-NNN`. A candidate without that observable change is dropped rather than filled with a restatement of its title.
50
+ - `Consensus` values use `full`, `partial`, `contested`, or `worker-unique`. Map convergence's `full-consensus` / `partial-consensus` labels to `full` / `partial` before writing the candidate.
51
+ - Verdict Token — structured 3.0 and 2.0 records use `analysis-complete` when every resolved lens was examined, `analysis-partial` when one could not be, and `blocked` when the scan itself could not run. Finding no candidates uses an empty `candidates[]` plus a `lensCoverage[]` row per lens with `status: no-candidate` and its evidence-backed rationale; the verdict stays `analysis-complete`. `candidates-ready` / `no-candidates` belong only to the legacy `## 7. Final Verdict` Markdown without a data file, where `validation.py` also checks the matching Verdict Card. Continuation guidance is owned by `prompts/lead/phase-routing.md`.
51
52
  - Record each candidate's recommended next phase and scope as facts for the common lead routing policy.
52
53
  - author the shared narrative fields plus `improvementDiscovery.candidates[]`, `improvementDiscovery.lensCoverage[]`, `improvementDiscovery.selectionLimit`, and `improvementDiscovery.userNarrative` in the report narrative. `candidates[]` carries the same 11 logical fields described above; `lensCoverage[]` records either candidate IDs or an evidence-backed no-candidate rationale for every resolved lens. `schemas/final-report-v3.0.schema.json`, `schemas/report-narrative-v3.0.schema.json`, and `scripts/okstra_ctl/phases/improvement_discovery/validation.py` enforce this contract. Phase 7 assembles the final record and derives the reading copy and human HTML.
53
54
  - Clarification request policy (phase-specific addenda — shared policy is in `_common-contract.md`):
@@ -0,0 +1,159 @@
1
+ """Freeze the resolved-lens worklist before publishing an analysis prompt."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import os
6
+ import tempfile
7
+ from pathlib import Path
8
+ from typing import Any, Mapping
9
+
10
+ from ...analysis_packet import replace_analysis_packet_block
11
+ from ...coverage_census import (
12
+ CensusError, census_for_run, census_state_paths, render_census_section,
13
+ )
14
+ from ...json_boundary import load_owned_object, write_owned_object_atomic
15
+ from ...run_context import task_mutex
16
+ from .lenses import RESOLVED_LENSES_POLICY, validate_priority_lenses
17
+
18
+
19
+ def improvement_census_policy_fields(
20
+ task_type: str, recorded_manifest: Mapping[str, Any] | None,
21
+ ) -> dict[str, Any]:
22
+ if recorded_manifest is None:
23
+ return {"coverageCensusPolicy": RESOLVED_LENSES_POLICY} if task_type == "improvement-discovery" else {}
24
+ return (
25
+ {"coverageCensusPolicy": recorded_manifest["coverageCensusPolicy"]}
26
+ if "coverageCensusPolicy" in recorded_manifest else {}
27
+ )
28
+
29
+
30
+ def pending_census_section(run_manifest: str) -> str:
31
+ return (
32
+ "## Coverage Census\n\n"
33
+ "The resolved-lens census is pending Phase 1.5 and will be frozen "
34
+ "before the first analysis prompt is published.\n"
35
+ f"<!-- okstra:resolved-lens-census:{run_manifest}:pending -->"
36
+ )
37
+
38
+
39
+ def prepare_resolved_lens_census(
40
+ project_root: Path, manifest: Mapping[str, Any],
41
+ ) -> None:
42
+ policy = manifest.get("coverageCensusPolicy")
43
+ if policy is None:
44
+ return
45
+ if manifest.get("taskType") != "improvement-discovery" or policy != RESOLVED_LENSES_POLICY:
46
+ raise CensusError(f"unsupported coverage census policy: {policy!r}")
47
+ paths = census_state_paths(project_root, manifest)
48
+ if paths is None:
49
+ raise CensusError("resolved-lens census requires the run state path")
50
+ census_path, _ = paths
51
+ _project_path(project_root, str(census_path), "census")
52
+ task_key = manifest.get("taskKey")
53
+ if not isinstance(task_key, str) or not task_key:
54
+ raise CensusError("resolved-lens census requires a task key")
55
+ with task_mutex(task_key):
56
+ _freeze_census(project_root, manifest, census_path)
57
+
58
+
59
+ def _project_path(root: Path, value: object, label: str) -> Path:
60
+ if not isinstance(value, str) or not value:
61
+ raise CensusError(f"missing {label} path")
62
+ path = (root / value).resolve()
63
+ if not path.is_relative_to(root.resolve()):
64
+ raise CensusError(f"{label} path escapes project root")
65
+ return path
66
+
67
+
68
+ def _resolved_lenses(text: str) -> tuple[str, ...]:
69
+ lines = text.splitlines()
70
+ headings = [index for index, line in enumerate(lines) if line == "## Resolved lenses"]
71
+ if len(headings) != 1:
72
+ raise CensusError("grilling log requires one '## Resolved lenses' section")
73
+ values: list[str] = []
74
+ for line in lines[headings[0] + 1:]:
75
+ if line.startswith("#"):
76
+ break
77
+ if not line.strip():
78
+ continue
79
+ if not line.startswith("- "):
80
+ raise CensusError("Resolved lenses must list one '- <lens>' entry per line")
81
+ values.append(line[2:])
82
+ try:
83
+ return validate_priority_lenses(values)
84
+ except ValueError as exc:
85
+ raise CensusError(str(exc)) from exc
86
+
87
+
88
+ def _digest(value: bytes) -> str:
89
+ return hashlib.sha256(value).hexdigest()
90
+
91
+
92
+ def _freeze_census(root: Path, manifest: Mapping[str, Any], census_path: Path) -> None:
93
+ run_dir = _project_path(root, manifest.get("runDirectoryPath"), "run directory")
94
+ log = _project_path(root, str(run_dir / "state/phase-1.5-grilling.md"), "grilling log")
95
+ try:
96
+ log_bytes = log.read_bytes()
97
+ except OSError as exc:
98
+ raise CensusError(f"cannot read Phase 1.5 grilling log: {log}") from exc
99
+ lenses = _resolved_lenses(log_bytes.decode("utf-8"))
100
+ instruction_set = _project_path(root, manifest.get("instructionSetPath"), "instruction set")
101
+ packet_path = _project_path(root, manifest.get("analysisPacketPath"), "analysis packet")
102
+ census = census_for_run(
103
+ task_type="improvement-discovery",
104
+ profile_text=(instruction_set / "analysis-profile.md").read_text(encoding="utf-8"),
105
+ brief_path=instruction_set / "task-brief.md",
106
+ selected_lenses=lenses,
107
+ )
108
+ if census is None:
109
+ raise CensusError("resolved-lens profile has no census aspects")
110
+ census["scopeSource"] = {
111
+ "path": log.relative_to(root).as_posix(), "digest": _digest(log_bytes),
112
+ "selectedLenses": list(lenses),
113
+ }
114
+ packet = packet_path.read_bytes()
115
+ if census_path.exists():
116
+ saved = load_owned_object(census_path, artifact="resolved-lens census")
117
+ if any(saved.get(key) != value for key, value in census.items()):
118
+ raise CensusError("resolved lenses or frozen census changed; preserve the existing run")
119
+ if _digest(packet) == saved.get("analysisPacketDigest"):
120
+ return
121
+ if _digest(packet) != saved.get("analysisPacketBeforeDigest"):
122
+ raise CensusError("frozen analysis packet changed; preserve the existing run")
123
+ census = saved
124
+ _publish_frozen_census_and_packet(root, manifest, census_path, census, packet_path, packet)
125
+
126
+
127
+ def _publish_frozen_census_and_packet(
128
+ root: Path, manifest: Mapping[str, Any], census_path: Path,
129
+ census: dict[str, Any], packet_path: Path, packet: bytes,
130
+ ) -> None:
131
+ prompt_paths = manifest.get("workerPromptPathByWorkerId")
132
+ if not isinstance(prompt_paths, Mapping):
133
+ raise CensusError("resolved-lens census requires worker prompt paths")
134
+ if any(_project_path(root, value, "worker prompt").exists() for value in prompt_paths.values()):
135
+ raise CensusError("cannot complete a pending census after worker prompt publication")
136
+ pending = pending_census_section(str(manifest.get("runManifestPath") or ""))
137
+ section = render_census_section(census, census_path.relative_to(root).as_posix())
138
+ try:
139
+ completed = replace_analysis_packet_block(packet.decode("utf-8"), pending, section).encode("utf-8")
140
+ except ValueError as exc:
141
+ raise CensusError(str(exc)) from exc
142
+ if census_path.exists():
143
+ if _digest(completed) != census.get("analysisPacketDigest"):
144
+ raise CensusError("pending analysis packet does not match the frozen census")
145
+ else:
146
+ census["analysisPacketBeforeDigest"] = _digest(packet)
147
+ census["analysisPacketDigest"] = _digest(completed)
148
+ write_owned_object_atomic(census_path, census, artifact="resolved-lens census")
149
+ temporary: Path | None = None
150
+ try:
151
+ with tempfile.NamedTemporaryFile(dir=packet_path.parent, delete=False) as handle:
152
+ temporary = Path(handle.name)
153
+ handle.write(completed)
154
+ handle.flush()
155
+ os.fsync(handle.fileno())
156
+ os.replace(temporary, packet_path)
157
+ finally:
158
+ if temporary is not None:
159
+ temporary.unlink(missing_ok=True)
@@ -10,7 +10,9 @@ Common analysis dispatch, convergence, clarification handling, report schemas an
10
10
 
11
11
  `profile.md` directs the lead's bounded scope-and-lens discussion and records its resolved scope, lenses and primary-pass assignments in `state/phase-1.5-grilling.md`. The common worker-prompt policy supplies the explicit log anchor. Every analyser inspects every resolved lens. Candidate rows retain their scope, expected observable change, evidence and source-worker identities.
12
12
 
13
- The run validator calls `validate_improvement_report` with the existing report path, run directory and parsed brief frontmatter. Schema-v2 data uses the shared schema validator followed by candidate checks. Existing schema-v1 Markdown uses the eleven-column candidate table and the matching Verdict Card and Final Verdict rows. The migration preserves these version branches and error messages; it does not add a new schema branch.
13
+ The run validator calls `validate_improvement_report` with the existing report path, run directory and parsed brief frontmatter. Current 3.0 and historical 2.0 structured records select their own shared schema followed by the same candidate checks. Markdown without a companion data file uses the eleven-column candidate table and the matching Verdict Card and Final Verdict rows. Invalid data and unknown or missing data versions fail rather than falling back to Markdown.
14
+
15
+ New runs declare `coverageCensusPolicy: resolved-lenses-v1`. Preparation leaves a run-specific pending census block in the analysis packet. Before an initial analyser prompt is published, `resolved_census.prepare_resolved_lens_census` reads the log's single `## Resolved lenses` section as one bare `- <lens>` bullet per resolved lens. It freezes the one-to-four unique whitelist values, log fingerprint and packet fingerprints under the existing task mutex, then atomically completes the packet with a regenerated section index. The mutex serializes census finalization calls and is released before per-prompt publication locks; it does not cover preparation's entire instruction-set write. The roster and native prompt CLI use this same boundary before provider-specific publication. A partially written packet can be completed from the saved census before any worker prompt exists; changed scope or a missing census after publication cannot replace the frozen worklist. Existing runs without the policy retain their original census. Missing cell verdicts remain advisory.
14
16
 
15
17
  The validator requires the resolved-log headings, but does not prove that each declared inspection or user conversation occurred. Primary-pass rotation and preserved-behavior reconciliation remain profile instructions reviewed during convergence.
16
18
 
@@ -23,7 +25,8 @@ The validator requires the resolved-log headings, but does not prove that each d
23
25
  | ID-3 | The run log contains resolved scope and lens blocks. | `scripts/okstra_ctl/phases/improvement_discovery/validation.py::_check_grilling_log` |
24
26
  | ID-4 | Legacy verdict rows use the legacy vocabulary and match the Verdict Card. | `scripts/okstra_ctl/phases/improvement_discovery/validation.py::_check_final_verdict`, `scripts/okstra_ctl/phases/improvement_discovery/validation.py::_check_verdict_card` |
25
27
  | ID-5 | Codebase briefs use one to four priority lenses from the phase vocabulary. | `validators/validate-brief.py::check_codebase_scope` |
28
+ | ID-6 | New runs freeze one-to-four resolved lens cells before initial analyser publication; retries preserve the cells and reject changed sources. | `scripts/okstra_ctl/phases/improvement_discovery/resolved_census.py::prepare_resolved_lens_census`, `initial_prompt_materialization.py::_materialize_initial_prompts`, `agent/prompt_cli/materialize.py::_materialize_run` |
26
29
 
27
30
  ## Tests
28
31
 
29
- `tests/test_improvement_discovery_validation.py` exercises both existing report branches with real report files and candidate mutations. The shared brief, rendering, doctor, prompt-anchor and catalog tests continue exercising the common callers.
32
+ `tests/report/test_assembly.py` exercises current and historical report validation. `tests/run/test_prepare.py` checks deferred preparation, resolved cell counts, immutable retry, native prompt publication and partial-packet recovery, malformed lens input and legacy policy preservation. Report `lensCoverage` completeness and primary-pass rotation remain instruction-level contracts, not new report gates.
@@ -18,7 +18,8 @@ from .lenses import (
18
18
  )
19
19
  from okstra_ctl.final_report_paths import final_report_data_path
20
20
  from okstra_ctl.final_report_schema import (
21
- load_schema_version,
21
+ SchemaError,
22
+ load_schema_for_data,
22
23
  validate as validate_final_report_data,
23
24
  )
24
25
  from okstra_ctl.md_table import split_pipe_row
@@ -291,7 +292,7 @@ def _check_verdict_card(
291
292
  errors.append("Verdict Card row must byte-match `## 7. Final Verdict` row")
292
293
 
293
294
 
294
- def _v2_candidate_rows(data: dict) -> list[list[str]]:
295
+ def _structured_candidate_rows(data: dict) -> list[list[str]]:
295
296
  candidates = data["improvementDiscovery"]["candidates"]
296
297
  return [
297
298
  [
@@ -311,17 +312,31 @@ def _v2_candidate_rows(data: dict) -> list[list[str]]:
311
312
  ]
312
313
 
313
314
 
314
- def _validate_v2_report(
315
+ def _validate_structured_report(
315
316
  data: dict,
316
317
  run_dir: Path,
317
318
  brief_frontmatter: dict,
318
319
  ) -> ValidationResult:
319
- errors = validate_final_report_data(data, load_schema_version("2.0"))
320
+ try:
321
+ schema = load_schema_for_data(data)
322
+ except SchemaError as exc:
323
+ return ValidationResult(ok=False, errors=[f"invalid report data: {exc}"])
324
+ if validate_final_report_data(data, schema):
325
+ return ValidationResult(
326
+ ok=False,
327
+ errors=["invalid report data: declared schema must pass before candidate validation"],
328
+ )
329
+ if data["header"]["taskType"] != "improvement-discovery":
330
+ return ValidationResult(
331
+ ok=False,
332
+ errors=["invalid report data: header.taskType must be improvement-discovery"],
333
+ )
334
+ errors: list[str] = []
320
335
  _check_grilling_log(run_dir, errors)
321
336
  if errors:
322
337
  return ValidationResult(ok=False, errors=errors)
323
338
 
324
- rows = _v2_candidate_rows(data)
339
+ rows = _structured_candidate_rows(data)
325
340
  _check_candidates_cap(len(rows), brief_frontmatter, errors)
326
341
  _check_candidate_rows(
327
342
  rows,
@@ -347,8 +362,7 @@ def validate_improvement_report(
347
362
  data = load_owned_object(data_path, artifact="improvement report data")
348
363
  except JsonBoundaryError as exc:
349
364
  return ValidationResult(ok=False, errors=[f"invalid report data: {exc}"])
350
- if data.get("schemaVersion") == "2.0":
351
- return _validate_v2_report(data, run_dir, brief_frontmatter)
365
+ return _validate_structured_report(data, run_dir, brief_frontmatter)
352
366
 
353
367
  body = report_path.read_text(encoding="utf-8")
354
368
 
@@ -1,5 +1,5 @@
1
1
  {
2
- "allowed": " - entering this phase only when the cited final-verification report's verdict is release-ready — `Verdict Token` exactly `accepted`, or exactly `conditional-accept` with every Conditional Acceptance Condition row declaring `blocksReleaseHandoff: false` (`okstra_ctl.release_gate.release_handoff_allowed`)\n - asking the user (via `AskUserQuestion` / interactive prompt) which delivery action to take: `local checkout`, `push + PR`, or `skip` (end the run)\n - asking the user to pick a PR base branch from `staging` | `preprod` | `prod` | `main` | `dev` | a user-supplied branch name\n - drafting PR title and PR body **inline as the Okstra lead** (no drafter worker and no delegated dispatch); the lead reviews its own draft with the user before any mutating git / gh command runs\n - read-only git inspection: `git status`, `git diff`, `git log`, `git rev-parse`\n - pushing the current feature branch to its origin remote via `git push -u origin <current-branch>` (the feature branch only — NEVER the base branch)\n - creating a pull request via `gh pr create --base <chosen-base> --head <current-branch>`; if a PR with the same head already exists, surface its URL and skip creation\n - the lead writes the report narrative at the run manifest's `reportNarrativePath` directly (no `Report writer worker` dispatch); `okstra report-finalize` assembles the final report from it",
2
+ "allowed": " - entering this phase only when the cited final-verification report's verdict is release-ready — `Verdict Token` exactly `accepted`, or exactly `conditional-accept` with every Conditional Acceptance Condition row declaring `blocksReleaseHandoff: false` (`okstra_ctl.release_gate.release_handoff_allowed`)\n - asking the user (via `AskUserQuestion` / interactive prompt) which delivery action to take: `local checkout`, `push + PR`, or `skip` (end the run)\n - asking the user to pick a PR base branch from `staging` | `preprod` | `prod` | `main` | `dev` | a user-supplied branch name\n - drafting PR title and PR body **inline as the Okstra lead** (no drafter worker and no delegated dispatch); the lead reviews its own draft with the user before any mutating git / gh command runs\n - read-only git inspection: `git status`, `git diff`, `git log`, `git rev-parse`\n - pushing the current feature branch to its origin remote via `git push -u origin <current-branch>` (the feature branch only — NEVER the base branch)\n - creating a pull request via `gh pr create --base <chosen-base> --head <current-branch>`; if a PR with the same head already exists, surface its URL and skip creation\n - the lead writes the report authoring input at the run manifest's `reportNarrativePath` directly (no `Report writer worker` dispatch), using standard JSON with exact writer-owned schema keys and native values when `reportAuthoringFormat=json-v1`, or the existing Markdown narrative line grammar when that field is absent; follow the complete format and frozen-schema instructions in this phase's Lead-only contract; `okstra report-finalize` assembles the final report from it",
3
3
  "forbidden": [
4
4
  "entering this phase when a cited final-verification verdict is not release-ready — `Verdict Token` `blocked` or any token other than `accepted` / `conditional-accept`, a `conditional-accept` with no Conditional Acceptance Condition row or with any row whose `blocksReleaseHandoff` is not `false` (`okstra_ctl.release_gate.release_handoff_allowed`) — or when no final-verification report is cited",
5
5
  "local commit commands of any kind (`git add`, `git commit`, `git restore --staged`, `git stash`), and any direct `git merge` / `git rebase` / `git rebase --onto` / `git cherry-pick` / `git commit --amend` run by the lead. Runtime exceptions are dependency-ordered rebases by `okstra_ctl.stage_rebase` (which invalidate verification and stop PR delivery), and merge commits on a dedicated multi-predecessor `merge-base` branch. Never merge a moving predecessor or origin branch into a downstream stage to update its base.",
@@ -9,7 +9,10 @@
9
9
  - Lead-only contract (replaces the shared team contract for this phase):
10
10
  - The host-native Okstra lead is the sole agent for this run. No worker dispatch, no teammates, no parallel sub-agents, no convergence loop. Do NOT run `okstra convergence` in any form: prepare already wrote this run's convergence state as "not run — fewer than two analysers", which is the record report assembly reads. **Enforced:** `okstra_ctl.render._initialize_lead_only_convergence` writes it when the run has no analysers, and leaves an existing state alone.
11
11
  - The lead drafts each stage's PR title and PR body **inline** by reading the run brief, that stage's cited final-verification report, `git log --oneline <stage base>..<stage head>`, and `git diff <stage base>..<stage head> --stat`. No drafter worker is dispatched.
12
- - The lead authors the report narrative directly (no `Report writer worker` dispatch) and never writes `final-report-*.data.json`. Write the narrative to the path the run manifest names in `reportNarrativePath`. It carries only the writer-owned fields (`humanSummary`, `summary`, `verdictCard`, `finalVerdict`, `rationale`, `recommendedNextSteps`, `followUpTasks`, and `releaseHandoff` with its `userNarrative`) in the narrative line grammar of `report_narrative.NARRATIVE_GRAMMAR_INSTRUCTIONS`: the first line is `# OKSTRA Report Narrative`, followed only by `- **Field Name**`, `- Item <N>` and `> value` lines, each value indented two spaces deeper than its label. `okstra report-finalize` assembles `data.json` from this narrative plus the approval, activity, team-state and convergence ledgers prepare already created. A missing or unparseable narrative fails the `project-activity` step with `owner=lead`. **Enforced:** `report_inputs._LEAD_AUTHORED_NARRATIVE_TASK_TYPES`, read by `report_assembly.assemble_report`.
12
+ - The lead authors the report input directly (no `Report writer worker` dispatch) and never writes `final-report-*.data.json`. Take the declared `reportAuthoringFormat` and exact `reportNarrativePath` from the `Report authoring format` and `Report writer input` labels in `okstra model-io run-input --run-manifest <current-run-manifest>`; do not infer a format from its extension. Read the explicitly named resource `<instruction-set>/final-report-schema.json` under that same view's `Instruction set` directory for every required nested field, value type and enum. Author the required writer-owned fields `humanSummary`, `summary`, `verdictCard`, `finalVerdict`, `rationale`, `recommendedNextSteps`, `followUpTasks`, and `releaseHandoff` with its `userNarrative`; write `finalVerdict.verdictToken` exactly `not-applicable`. Do not copy the complete schema's machine-owned fields into the input: approval, activity, team-state, convergence, execution and usage values remain with their owners.
13
+ - For `reportAuthoringFormat=json-v1`, write one standard JSON object using exact schema keys and native arrays, objects, numbers, booleans and `null`. Description strings may contain ordinary Markdown, including newlines, tables and code blocks. Do not add a heading, preamble, Markdown fence, duplicate keys, non-standard numeric values, Title Case field labels, `- Item N` / `> value` lines or `_none_` markers. Write prose strings in the run's resolved report language; preserve enum/status values, identifiers, paths and commands exactly. Complete every required nested field from the frozen schema; an empty array or `null` is valid only where that schema permits it.
14
+ - An absent `reportAuthoringFormat` retains `markdown-v1`: follow `report_narrative.NARRATIVE_GRAMMAR_INSTRUCTIONS`, starting with `# OKSTRA Report Narrative` and then only `- **Field Name**`, `- Item <N>` and `> value` lines, each value indented two spaces deeper than its label. Use the existing Title Case labels and `_none_` representation only in this format.
15
+ - `okstra report-finalize` assembles `data.json` from this input plus the approval, activity, team-state and convergence ledgers prepare already created, and derives the reader's Markdown and HTML. A missing or unparseable input fails the `project-activity` step with `owner=lead`. **Enforced:** `report_inputs._LEAD_AUTHORED_NARRATIVE_TASK_TYPES`, read by `report_assembly.assemble_report`.
13
16
  - The shared anti-escalation rule from the common contract still applies: do not start any other lifecycle phase from inside this run.
14
17
  - The shared "authority & permissions assumption" rule from the common contract still applies: assume the user holds every permission needed; do not block on hypothetical approvals.
15
18
  - Pre-handoff entry gate (mandatory — refuse to start if any item fails):
@@ -16,7 +16,7 @@ from pathlib import Path
16
16
  from .report_finalize import resolve_workspace_validator
17
17
 
18
18
  _CLI_EPILOG = r"""Usage:
19
- okstra plan-verify --narrative <report-writer-narrative.md> --state <plan-body-verification.json>
19
+ okstra plan-verify --run-manifest <path> --narrative <reportNarrativePath> --state <plan-body-verification.json>
20
20
  okstra plan-verify --report <final-report-implementation-planning-<seq>.data.json>
21
21
 
22
22
  Recomputes the gate from the convergence-owned state's `planItems[].verdicts`
@@ -59,7 +59,9 @@ def main(argv: list[str] | None = None) -> int:
59
59
  parser.add_argument("--workspace-root", required=True,
60
60
  help=argparse.SUPPRESS)
61
61
  parser.add_argument("--narrative", default="",
62
- help="the report-writer narrative this round scored")
62
+ help="the report writer's declared input this round scored")
63
+ parser.add_argument("--run-manifest", default="",
64
+ help="the run manifest declaring the writer input format")
63
65
  parser.add_argument("--state", default="",
64
66
  help="the convergence-owned plan-body-verification.json")
65
67
  parser.add_argument("--report", default="",
@@ -67,8 +69,8 @@ def main(argv: list[str] | None = None) -> int:
67
69
  args = parser.parse_args(argv)
68
70
 
69
71
  forwarded: list[str] = ["--section", "plan-body"]
70
- for flag in ("narrative", "state", "report"):
71
- value = getattr(args, flag)
72
+ for flag in ("narrative", "state", "report", "run-manifest"):
73
+ value = getattr(args, flag.replace("-", "_"))
72
74
  if value:
73
75
  forwarded += [f"--{flag}", value]
74
76
 
@@ -27,6 +27,7 @@ from collections.abc import Mapping
27
27
  from pathlib import Path
28
28
 
29
29
  from okstra_project.dirs import TASK_MANIFEST_FILENAME
30
+ from okstra_project.state import IMPLEMENTATION_TRACE_FIELDS, implementation_trace_projection
30
31
 
31
32
  # phase 시퀀스 / 기본 next-phase 매핑의 SSOT 는 workflow 모듈이다. 과거
32
33
  # render_task_manifest 가 동일한 리스트/딕셔너리를 로컬에 중복 정의했는데,
@@ -55,7 +56,7 @@ from .paths import task_timeline_file
55
56
  from .json_boundary import JsonBoundaryError, load_owned_object, write_owned_object_atomic
56
57
  from .mcp_servers import load_declarations as load_mcp_declarations
57
58
  from .mcp_servers import render_block as render_mcp_block
58
- from .report_contract import CURRENT_REPORT_SCHEMA_VERSION
59
+ from .report_contract import CURRENT_REPORT_SCHEMA_VERSION, report_authoring_format
59
60
  from .report_language import resolve_report_language
60
61
  from .validation_contract import CURRENT_VALIDATION_CONTRACT_VERSION
61
62
  from .worker_artifacts import (
@@ -973,6 +974,7 @@ def render_task_catalog_discovery(output_path: str, ctx: dict) -> None:
973
974
  "workStatusUpdatedAt": s(manifest, "workStatusUpdatedAt"),
974
975
  "workStatusNote": s(manifest, "workStatusNote"),
975
976
  "latestWorkRecordPath": s(manifest, "latestWorkRecordPath"),
977
+ **implementation_trace_projection(manifest),
976
978
  "updatedAt": s(manifest, "updatedAt"),
977
979
  "currentPhase": (workflow or {}).get("currentPhase", "")
978
980
  if isinstance(workflow, dict)
@@ -1414,6 +1416,13 @@ def _registered_task_brief(existing: dict, ctx: dict) -> str:
1414
1416
 
1415
1417
 
1416
1418
  def render_task_manifest(manifest_path: str, ctx: dict) -> None:
1419
+ from .run_context import task_mutex
1420
+
1421
+ with task_mutex(ctx["TASK_KEY"]):
1422
+ _render_task_manifest_unlocked(manifest_path, ctx)
1423
+
1424
+
1425
+ def _render_task_manifest_unlocked(manifest_path: str, ctx: dict) -> None:
1417
1426
  path = Path(manifest_path)
1418
1427
  existing = {}
1419
1428
  if path.exists():
@@ -1492,6 +1501,7 @@ def render_task_manifest(manifest_path: str, ctx: dict) -> None:
1492
1501
  "workStatusNote": existing.get("workStatusNote", ""),
1493
1502
  "latestWorkRecordPath": existing.get("latestWorkRecordPath", ""),
1494
1503
  "registrationSource": existing.get("registrationSource", ""),
1504
+ **{key: existing[key] for key in IMPLEMENTATION_TRACE_FIELDS if key in existing},
1495
1505
  "taskBriefPath": _registered_task_brief(existing, ctx),
1496
1506
  "recommendedWorkers": reviewers,
1497
1507
  "relatedTasks": related_tasks,
@@ -1770,9 +1780,17 @@ def render_run_manifest(run_manifest_path: str, ctx: dict) -> None:
1770
1780
  if s.strip().isdigit()
1771
1781
  ]
1772
1782
  execution_identity = _execution_identity(ctx)
1783
+ policy_source = existing_run_manifest if run_manifest_exists else {
1784
+ "reportAuthoringFormat": ctx.get("REPORT_AUTHORING_FORMAT", "markdown-v1"),
1785
+ "usageAccountingPolicy": ctx.get("USAGE_ACCOUNTING_POLICY", "strict"),
1786
+ }
1787
+ from okstra_token_usage.policy import usage_accounting_policy
1788
+
1773
1789
  payload = {
1774
1790
  "schemaVersion": execution_identity.get("schemaVersion", "1.0"),
1775
1791
  "reportContractVersion": CURRENT_REPORT_SCHEMA_VERSION,
1792
+ "reportAuthoringFormat": report_authoring_format(policy_source),
1793
+ "usageAccountingPolicy": usage_accounting_policy(policy_source),
1776
1794
  "okstraVersion": ctx.get("OKSTRA_VERSION", ""),
1777
1795
  "projectId": ctx.get("PROJECT_ID", ""),
1778
1796
  "taskGroup": ctx.get("TASK_GROUP", ""),
@@ -1863,7 +1881,9 @@ def render_run_manifest(run_manifest_path: str, ctx: dict) -> None:
1863
1881
  "workerPromptsDirectoryPath": ctx.get("RUN_PROMPTS_RELATIVE_PATH", ""),
1864
1882
  "workerPromptPathByWorkerId": worker_prompt_paths,
1865
1883
  "expectedReportRecordPath": ctx.get("FINAL_REPORT_RECORD_RELATIVE_PATH", ""),
1866
- "reportNarrativePath": ctx.get("REPORT_WRITER_NARRATIVE_RELATIVE_PATH", ""),
1884
+ "reportNarrativePath": existing_run_manifest.get(
1885
+ "reportNarrativePath", ctx.get("REPORT_WRITER_NARRATIVE_RELATIVE_PATH", ""),
1886
+ ),
1867
1887
  "approvalDecisionsPath": ctx.get("APPROVAL_DECISIONS_RELATIVE_PATH", ""),
1868
1888
  "designPreparationPath": ctx.get("DESIGN_PREPARATION_RELATIVE_PATH", ""),
1869
1889
  "planBodyVerificationPath": ctx.get("PLAN_BODY_VERIFICATION_STATE_RELATIVE_PATH", ""),
@@ -1951,6 +1971,12 @@ def render_run_manifest(run_manifest_path: str, ctx: dict) -> None:
1951
1971
  scope_confirmation = _analysis_scope_confirmation_snapshot(ctx)
1952
1972
  if scope_confirmation is not None:
1953
1973
  payload["analysisScopeConfirmation"] = scope_confirmation
1974
+ from .phases.improvement_discovery.resolved_census import improvement_census_policy_fields
1975
+
1976
+ payload.update(improvement_census_policy_fields(
1977
+ ctx.get("TASK_TYPE", ""),
1978
+ existing_run_manifest if run_manifest_exists else None,
1979
+ ))
1954
1980
  if ctx.get("FIX_CYCLE_ID"):
1955
1981
  payload["fixCycleId"] = ctx["FIX_CYCLE_ID"]
1956
1982
  cmux_lead = json.loads(ctx.get("CMUX_LEAD_JSON") or "{}")
@@ -26,7 +26,8 @@ from .report_inputs import (
26
26
  )
27
27
  from .correction_round import correction_convergence_states, correction_round
28
28
  from .json_boundary import JsonBoundaryError, load_owned_object, serialize_owned_object
29
- from .report_narrative import parse_narrative, task_narrative_errors
29
+ from .report_narrative import load_report_narrative, task_narrative_errors
30
+ from .report_contract import report_authoring_format
30
31
  from .report_execution_evidence import (
31
32
  RECORD_DERIVED_TIERS, collect_report_evidence, command_row,
32
33
  )
@@ -153,6 +154,8 @@ def _input_preflight_issues(
153
154
  inputs: Mapping[str, ReportInputPath],
154
155
  schema: Mapping[str, Any],
155
156
  task_type: str,
157
+ project_root: Path,
158
+ manifest: Mapping[str, Any],
156
159
  ) -> tuple[AssemblyIssue, ...]:
157
160
  issues: list[AssemblyIssue] = []
158
161
  for row in inputs.values():
@@ -174,7 +177,7 @@ def _input_preflight_issues(
174
177
  continue
175
178
  try:
176
179
  if row.key == "narrative":
177
- narrative = parse_narrative(row.path.read_text(encoding="utf-8"), schema)
180
+ narrative = load_report_narrative(project_root, manifest, schema, path=row.path)
178
181
  issues.extend(
179
182
  AssemblyIssue(
180
183
  row.owner, str(row.path), error.split(":", 1)[0], error,
@@ -195,11 +198,14 @@ def _input_preflight_issues(
195
198
  return tuple(issues)
196
199
 
197
200
 
198
- def _narrative(row: ReportInputPath, schema: Mapping[str, Any]) -> dict[str, Any]:
201
+ def _narrative(
202
+ row: ReportInputPath, schema: Mapping[str, Any],
203
+ project_root: Path, manifest: Mapping[str, Any],
204
+ ) -> dict[str, Any]:
199
205
  if not row.path.is_file():
200
206
  _fail(row.owner, row.path, "$", "required input is missing")
201
207
  try:
202
- return parse_narrative(row.path.read_text(encoding="utf-8"), schema)
208
+ return load_report_narrative(project_root, manifest, schema, path=row.path)
203
209
  except (OSError, UnicodeError, ValueError) as exc:
204
210
  _fail(row.owner, row.path, "$", exc)
205
211
 
@@ -516,9 +522,20 @@ def _compose(
516
522
  inputs: Mapping[str, ReportInputPath],
517
523
  schema: Mapping[str, Any],
518
524
  ) -> dict[str, Any]:
519
- narrative = _narrative(inputs["narrative"], schema)
525
+ narrative = _narrative(inputs["narrative"], schema, project_root, manifest)
520
526
  ledger = _read_json(inputs["approval-decisions"])
521
527
  team_state = _read_json(inputs["execution-status"])
528
+ from okstra_token_usage.policy import usage_accounting_policy, usage_diagnostics
529
+
530
+ try:
531
+ accounting_policy = usage_accounting_policy(manifest)
532
+ except ValueError as exc:
533
+ _fail("orchestrator", manifest_path, "usageAccountingPolicy", exc)
534
+ usage_missing: list[dict[str, Any]] = []
535
+ if accounting_policy == "advisory":
536
+ usage_errors, usage_missing = usage_diagnostics(team_state)
537
+ if usage_errors:
538
+ _fail("team-state", inputs["execution-status"].path, "usageSummary", "; ".join(usage_errors))
522
539
  convergence = _read_json(inputs["convergence"])
523
540
  if not inputs["agent-activity"].path.is_file():
524
541
  _fail("activity-ledger", inputs["agent-activity"].path, "$", "required input is missing")
@@ -532,7 +549,7 @@ def _compose(
532
549
  _fail("convergence", inputs["convergence"].path, "$", exc)
533
550
  try:
534
551
  execution = project_execution(manifest, team_state)
535
- usage = project_token_usage(team_state)
552
+ usage = project_token_usage(team_state, usage_policy=accounting_policy)
536
553
  except (TypeError, ValueError) as exc:
537
554
  _fail("team-state", inputs["execution-status"].path, "$", exc)
538
555
  data = {"schemaVersion": "3.0", **narrative, **execution}
@@ -566,7 +583,7 @@ def _compose(
566
583
  *round_evidence,
567
584
  ])}
568
585
  data["missingInformation"] = _missing_information(
569
- project_root, manifest, convergence_data["criticUnverified"],
586
+ project_root, manifest, convergence_data["criticUnverified"], usage_missing,
570
587
  )
571
588
  # 스냅샷 복사가 _attach_metadata 보다 먼저다 — frontmatter 가
572
589
  # selectedDirectionRef.snapshotPath 를 읽는다.
@@ -689,14 +706,15 @@ def _attach_discussion(data: dict[str, Any], project_root: Path, manifest: Mappi
689
706
 
690
707
  def _missing_information(
691
708
  project_root: Path, manifest: Mapping[str, Any], critic_unverified: list[dict[str, Any]],
709
+ usage_missing: list[dict[str, Any]],
692
710
  ) -> list[dict[str, Any]]:
693
- """Coverage-census warnings and unjudged critic gaps are the only rows this
694
- field carries under the v3 contract, so they number from `R-001`."""
711
+ """Number observed runtime gaps without asking the writer to invent them."""
695
712
  _project_id, _task_group, task_id = _identity(manifest)
696
713
  ticket_id = task_id or "unknown"
697
714
  state = read_census_state(project_root, manifest)
698
715
  rows = [] if state is None else census_warning_rows(state, ticket_id=ticket_id)
699
716
  rows += [{**row, "ticketId": row["ticketId"] or ticket_id} for row in critic_unverified]
717
+ rows += [{"ticketId": ticket_id, **row} for row in usage_missing]
700
718
  return [{"id": f"R-{index:03d}", **row} for index, row in enumerate(rows, start=1)]
701
719
 
702
720
 
@@ -1004,10 +1022,19 @@ def assemble_report(
1004
1022
  manifest = _read_json(manifest_row)
1005
1023
  if not uses_report_contract_v3(manifest):
1006
1024
  _fail("orchestrator", manifest_path, "reportContractVersion", "requires 3.0")
1025
+ try:
1026
+ authoring_format = report_authoring_format(manifest)
1027
+ except ValueError as exc:
1028
+ _fail("orchestrator", manifest_path, "reportAuthoringFormat", exc)
1007
1029
  schema = load_schema_version("3.0")
1008
1030
  inputs = _input_map(project_root, manifest)
1009
- input_issues = list(_input_preflight_issues(inputs, schema, str(manifest.get("taskType", ""))))
1010
- packet_data_path, _ = report_synthesis_packet_paths(inputs["narrative"].path)
1031
+ try:
1032
+ packet_data_path, _ = report_synthesis_packet_paths(inputs["narrative"].path, authoring_format)
1033
+ except ValueError as exc:
1034
+ _fail("orchestrator", manifest_path, "reportNarrativePath", exc)
1035
+ input_issues = list(_input_preflight_issues(
1036
+ inputs, schema, str(manifest.get("taskType", "")), project_root, manifest,
1037
+ ))
1011
1038
  if packet_data_path.is_file():
1012
1039
  input_issues.extend(
1013
1040
  AssemblyIssue(