okstra 0.232.0 → 0.234.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 (205) hide show
  1. package/README.md +19 -283
  2. package/dist/cli-registry.mjs +14 -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 +55 -5
  49. package/docs/architecture.md +10 -4
  50. package/docs/cli.md +320 -3
  51. package/docs/contributor-change-matrix.md +1 -2
  52. package/docs/project-structure-overview.md +34 -43
  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/business_flow/cli.py +60 -6
  77. package/runtime/python/okstra_ctl/business_flow/contracts.py +12 -1
  78. package/runtime/python/okstra_ctl/business_flow/engine.py +17 -5
  79. package/runtime/python/okstra_ctl/business_flow/history.py +60 -0
  80. package/runtime/python/okstra_ctl/business_flow/source.py +35 -2
  81. package/runtime/python/okstra_ctl/business_flow/store.py +51 -14
  82. package/runtime/python/okstra_ctl/business_flow/sweep.py +124 -0
  83. package/runtime/python/okstra_ctl/code_review_census.py +93 -2
  84. package/runtime/python/okstra_ctl/code_review_prepare.py +381 -0
  85. package/runtime/python/okstra_ctl/code_review_run.py +384 -0
  86. package/runtime/python/okstra_ctl/code_review_scope.py +13 -0
  87. package/runtime/python/okstra_ctl/code_review_supervisor.py +41 -0
  88. package/runtime/python/okstra_ctl/code_review_target.py +140 -15
  89. package/runtime/python/okstra_ctl/coverage_census.py +11 -2
  90. package/runtime/python/okstra_ctl/design_snapshot.py +16 -9
  91. package/runtime/python/okstra_ctl/direct_work.py +45 -3
  92. package/runtime/python/okstra_ctl/dispatch_core.py +31 -15
  93. package/runtime/python/okstra_ctl/dispatch_state.py +9 -2
  94. package/runtime/python/okstra_ctl/domain/role.py +1 -0
  95. package/runtime/python/okstra_ctl/doyouknow/cli.py +9 -9
  96. package/runtime/python/okstra_ctl/doyouknow/config.py +2 -2
  97. package/runtime/python/okstra_ctl/doyouknow/group_view.py +152 -0
  98. package/runtime/python/okstra_ctl/doyouknow/source_contracts.py +4 -3
  99. package/runtime/python/okstra_ctl/doyouknow/source_store.py +2 -2
  100. package/runtime/python/okstra_ctl/doyouknow/sources/business.py +116 -0
  101. package/runtime/python/okstra_ctl/doyouknow/sources/manager.py +48 -9
  102. package/runtime/python/okstra_ctl/doyouknow/sync.py +34 -9
  103. package/runtime/python/okstra_ctl/final_report_schema.py +37 -34
  104. package/runtime/python/okstra_ctl/fixed_text.py +10 -0
  105. package/runtime/python/okstra_ctl/incremental_carry.py +6 -7
  106. package/runtime/python/okstra_ctl/initial_prompt_materialization.py +9 -2
  107. package/runtime/python/okstra_ctl/json_boundary.py +33 -6
  108. package/runtime/python/okstra_ctl/manager_cli.py +122 -1
  109. package/runtime/python/okstra_ctl/manager_journal.py +126 -0
  110. package/runtime/python/okstra_ctl/manager_launch.py +3 -3
  111. package/runtime/python/okstra_ctl/manager_log.py +221 -0
  112. package/runtime/python/okstra_ctl/manager_paths.py +8 -0
  113. package/runtime/python/okstra_ctl/manager_resume.py +59 -0
  114. package/runtime/python/okstra_ctl/manager_split.py +2 -2
  115. package/runtime/python/okstra_ctl/manager_store.py +116 -17
  116. package/runtime/python/okstra_ctl/manager_sync.py +42 -3
  117. package/runtime/python/okstra_ctl/manager_view.py +35 -2
  118. package/runtime/python/okstra_ctl/material.py +2 -0
  119. package/runtime/python/okstra_ctl/model_cli.py +64 -14
  120. package/runtime/python/okstra_ctl/model_defaults.py +22 -0
  121. package/runtime/python/okstra_ctl/model_io/renderers.py +3 -0
  122. package/runtime/python/okstra_ctl/operation_invocation.py +207 -28
  123. package/runtime/python/okstra_ctl/path_hints.py +14 -3
  124. package/runtime/python/okstra_ctl/paths.py +6 -1
  125. package/runtime/python/okstra_ctl/phases/catalog.py +24 -7
  126. package/runtime/python/okstra_ctl/phases/implementation/host-rules.md +3 -3
  127. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-diff-review.md +8 -6
  128. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-self-check.md +1 -1
  129. package/runtime/python/okstra_ctl/phases/implementation_option_selection/profile.md +1 -1
  130. package/runtime/python/okstra_ctl/phases/implementation_option_selection/votes.py +11 -11
  131. package/runtime/python/okstra_ctl/phases/implementation_planning/authoring.py +12 -9
  132. package/runtime/python/okstra_ctl/phases/implementation_planning/host-rules.md +3 -6
  133. package/runtime/python/okstra_ctl/phases/implementation_planning/instructions/plan-body-verification.md +12 -10
  134. package/runtime/python/okstra_ctl/phases/implementation_planning/profile.md +5 -5
  135. package/runtime/python/okstra_ctl/phases/improvement_discovery/lenses.py +12 -0
  136. package/runtime/python/okstra_ctl/phases/improvement_discovery/profile.md +7 -6
  137. package/runtime/python/okstra_ctl/phases/improvement_discovery/resolved_census.py +159 -0
  138. package/runtime/python/okstra_ctl/phases/improvement_discovery/spec.md +5 -2
  139. package/runtime/python/okstra_ctl/phases/improvement_discovery/validation.py +21 -7
  140. package/runtime/python/okstra_ctl/phases/release_handoff/boundary.json +1 -1
  141. package/runtime/python/okstra_ctl/phases/release_handoff/profile.md +4 -1
  142. package/runtime/python/okstra_ctl/plan_verify_cli.py +6 -4
  143. package/runtime/python/okstra_ctl/project_group.py +175 -0
  144. package/runtime/python/okstra_ctl/project_group_cli.py +62 -0
  145. package/runtime/python/okstra_ctl/render.py +28 -2
  146. package/runtime/python/okstra_ctl/report_assembly.py +38 -11
  147. package/runtime/python/okstra_ctl/report_contract.py +26 -0
  148. package/runtime/python/okstra_ctl/report_corrections.py +36 -20
  149. package/runtime/python/okstra_ctl/report_inputs.py +1 -0
  150. package/runtime/python/okstra_ctl/report_language.py +4 -1
  151. package/runtime/python/okstra_ctl/report_narrative.py +179 -7
  152. package/runtime/python/okstra_ctl/report_projections.py +64 -18
  153. package/runtime/python/okstra_ctl/report_synthesis_packet.py +86 -36
  154. package/runtime/python/okstra_ctl/run.py +43 -35
  155. package/runtime/python/okstra_ctl/run_context.py +10 -1
  156. package/runtime/python/okstra_ctl/set_work_status.py +4 -15
  157. package/runtime/python/okstra_ctl/task_list_cli.py +34 -8
  158. package/runtime/python/okstra_ctl/task_query.py +239 -0
  159. package/runtime/python/okstra_ctl/trace_review.py +264 -0
  160. package/runtime/python/okstra_ctl/trace_tasks.py +197 -0
  161. package/runtime/python/okstra_ctl/user_authorization.py +14 -0
  162. package/runtime/python/okstra_ctl/wizard/confirmation.py +7 -3
  163. package/runtime/python/okstra_ctl/wizard/launch.py +52 -0
  164. package/runtime/python/okstra_ctl/wizard/launch_cli.py +39 -0
  165. package/runtime/python/okstra_ctl/wizard/outcome.py +17 -16
  166. package/runtime/python/okstra_ctl/wizard/registry.py +1 -1
  167. package/runtime/python/okstra_ctl/wizard/render.py +8 -0
  168. package/runtime/python/okstra_ctl/wizard/state.py +2 -1
  169. package/runtime/python/okstra_project/state.py +20 -0
  170. package/runtime/python/okstra_token_usage/blocks.py +74 -0
  171. package/runtime/python/okstra_token_usage/cli.py +23 -10
  172. package/runtime/python/okstra_token_usage/collect.py +25 -22
  173. package/runtime/python/okstra_token_usage/policy.py +193 -0
  174. package/runtime/schemas/business-flow-v1.schema.json +3 -0
  175. package/runtime/schemas/doyouknow-config-v1.schema.json +1 -1
  176. package/runtime/schemas/report-synthesis-packet-v1.0.schema.json +1 -1
  177. package/runtime/skills/_fragments/wizard-confirm-step.md +1 -1
  178. package/runtime/skills/_fragments/wizard-preflight.md +1 -1
  179. package/runtime/skills/_fragments/wizard-prompt-loop.md +3 -5
  180. package/runtime/skills/_fragments/wizard-relay-protocol.md +1 -1
  181. package/runtime/skills/_fragments/wizard-render-bundle.md +15 -29
  182. package/runtime/skills/okstra-brief-gen/SKILL.md +7 -7
  183. package/runtime/skills/okstra-brief-gen/references/tracker-recursion.md +1 -1
  184. package/runtime/skills/okstra-code-review/SKILL.md +58 -50
  185. package/runtime/skills/okstra-code-review/references/census-rules.md +6 -6
  186. package/runtime/skills/okstra-code-review/references/review-calibration.md +8 -12
  187. package/runtime/skills/okstra-discussion/SKILL.md +22 -38
  188. package/runtime/skills/okstra-explain-flow/SKILL.md +33 -4
  189. package/runtime/skills/okstra-manager/SKILL.md +24 -0
  190. package/runtime/skills/okstra-memory/SKILL.md +1 -1
  191. package/runtime/skills/okstra-pr-gen/SKILL.md +1 -1
  192. package/runtime/skills/okstra-run/SKILL.md +55 -183
  193. package/runtime/skills/okstra-schedule-gen/SKILL.md +9 -13
  194. package/runtime/skills/okstra-setup/SKILL.md +3 -2
  195. package/runtime/skills/okstra-setup/references/project-config.md +2 -4
  196. package/runtime/skills/okstra-tdd/SKILL.md +187 -0
  197. package/runtime/skills/okstra-user-response/SKILL.md +4 -2
  198. package/runtime/templates/doyouknow/group-view.css +103 -0
  199. package/runtime/templates/doyouknow/group-view.js +317 -0
  200. package/runtime/templates/doyouknow/group-view.template.html +72 -0
  201. package/runtime/templates/manager/view.template.html +4 -0
  202. package/runtime/templates/report-writer-prompt-preamble.md +15 -3
  203. package/runtime/templates/trace/trace.template.md +42 -0
  204. package/runtime/validators/checks/fixtures-02.py +25 -33
  205. package/runtime/validators/validate-run.py +93 -36
@@ -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
 
@@ -0,0 +1,175 @@
1
+ """Project-group registry: the project roots that belong to a named group."""
2
+ from __future__ import annotations
3
+
4
+ from datetime import datetime, timezone
5
+ from pathlib import Path
6
+
7
+ from okstra_project import ResolverError, upsert_project_json
8
+ from okstra_project.dirs import json_lock_path, registry_lock
9
+
10
+ from .json_boundary import JsonBoundaryError, load_owned_object, write_owned_object_atomic
11
+ from .manager_paths import ManagerPathError, _slug_segment
12
+
13
+ ARTIFACT = "project group"
14
+
15
+
16
+ class ProjectGroupError(ValueError):
17
+ """Project-group validation or I/O failure."""
18
+
19
+
20
+ def groups_root(home: Path) -> Path:
21
+ return Path(home) / "project-groups"
22
+
23
+
24
+ def group_path(home: Path, name: str) -> Path:
25
+ try:
26
+ segment = _slug_segment(name, "project-group")
27
+ except ManagerPathError as exc:
28
+ raise ProjectGroupError(str(exc)) from exc
29
+ return groups_root(home) / f"{segment}.json"
30
+
31
+
32
+ def _now_iso() -> str:
33
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
34
+
35
+
36
+ def _read_file(path: Path) -> dict:
37
+ try:
38
+ data = load_owned_object(path, artifact=ARTIFACT)
39
+ except JsonBoundaryError as exc:
40
+ raise ProjectGroupError(str(exc)) from exc
41
+ projects = data.get("projects")
42
+ if not isinstance(data.get("projectGroup"), str) or not isinstance(projects, list) or not all(
43
+ isinstance(row, dict)
44
+ and isinstance(row.get("projectId"), str)
45
+ and isinstance(row.get("projectRoot"), str)
46
+ for row in projects
47
+ ):
48
+ raise ProjectGroupError(f"malformed project group file: {path}")
49
+ return data
50
+
51
+
52
+ def _write_file(path: Path, data: dict) -> None:
53
+ try:
54
+ write_owned_object_atomic(path, data, artifact=ARTIFACT)
55
+ except JsonBoundaryError as exc:
56
+ raise ProjectGroupError(str(exc)) from exc
57
+
58
+
59
+ def _load(path: Path, name: str) -> dict:
60
+ data = _read_file(path)
61
+ # Different names can share one slug, and the file belongs to the first name stored in it.
62
+ if data["projectGroup"] != name:
63
+ raise ProjectGroupError(
64
+ f"project-group {name!r} shares its file with existing group "
65
+ f"{data['projectGroup']!r}: {path}"
66
+ )
67
+ return data
68
+
69
+
70
+ def read_group(home: Path, name: str) -> dict:
71
+ name = name.strip()
72
+ path = group_path(home, name)
73
+ if not path.is_file():
74
+ raise ProjectGroupError(f"unknown project-group: {name}")
75
+ return _load(path, name)
76
+
77
+
78
+ def add_project(
79
+ home: Path, name: str, project_id: str, project_root: Path, *, now: str | None = None
80
+ ) -> dict:
81
+ name = name.strip()
82
+ path = group_path(home, name)
83
+ root = Path(project_root).resolve()
84
+ if not root.is_dir():
85
+ raise ProjectGroupError(f"projectRoot is not a directory: {root}")
86
+ when = now or _now_iso()
87
+ with registry_lock(json_lock_path(path)):
88
+ data = (
89
+ _load(path, name)
90
+ if path.is_file()
91
+ else {"schemaVersion": 1, "projectGroup": name, "createdAt": when, "projects": []}
92
+ )
93
+ entry = next((row for row in data["projects"] if row["projectId"] == project_id), None)
94
+ changed = entry is None or entry.get("projectRoot") != str(root)
95
+ if changed:
96
+ try:
97
+ upsert_project_json(root, project_id, now=when)
98
+ except ResolverError as exc:
99
+ raise ProjectGroupError(str(exc)) from exc
100
+ if entry is None:
101
+ data["projects"].append(
102
+ {"projectId": project_id, "projectRoot": str(root), "linkedAt": when}
103
+ )
104
+ elif changed:
105
+ entry["projectRoot"] = str(root)
106
+ if changed:
107
+ data["projects"].sort(key=lambda row: row["projectId"])
108
+ _write_file(path, data)
109
+ return {
110
+ "ok": True,
111
+ "projectGroup": name,
112
+ "projectId": project_id,
113
+ "projectRoot": str(root),
114
+ "added": entry is None,
115
+ "changed": changed,
116
+ }
117
+
118
+
119
+ def remove_project(home: Path, name: str, project_id: str) -> dict:
120
+ name = name.strip()
121
+ path = group_path(home, name)
122
+ with registry_lock(json_lock_path(path)):
123
+ data = read_group(home, name)
124
+ kept = [row for row in data["projects"] if row["projectId"] != project_id]
125
+ if len(kept) == len(data["projects"]):
126
+ raise ProjectGroupError(f"project {project_id} is not in project-group {name}")
127
+ data["projects"] = kept
128
+ _write_file(path, data)
129
+ return {"ok": True, "projectGroup": name, "projectId": project_id, "removed": True}
130
+
131
+
132
+ def show_group(home: Path, name: str) -> dict:
133
+ data = read_group(home, name)
134
+ return {
135
+ "ok": True,
136
+ "projectGroup": data["projectGroup"],
137
+ "createdAt": str(data.get("createdAt") or ""),
138
+ "projects": [
139
+ {**row, "rootExists": Path(str(row.get("projectRoot") or "")).is_dir()}
140
+ for row in data["projects"]
141
+ ],
142
+ }
143
+
144
+
145
+ def _read_all(home: Path) -> tuple[list[dict], list[str]]:
146
+ groups, errors = [], []
147
+ groups_dir = groups_root(home)
148
+ for path in sorted(groups_dir.glob("*.json")) if groups_dir.is_dir() else []:
149
+ try:
150
+ groups.append(_read_file(path))
151
+ except ProjectGroupError as exc:
152
+ errors.append(f"{path.name}: {exc}")
153
+ return groups, errors
154
+
155
+
156
+ def list_groups(home: Path) -> dict:
157
+ groups, errors = _read_all(home)
158
+ return {
159
+ "ok": not errors,
160
+ "groups": [
161
+ {"projectGroup": data["projectGroup"], "projectCount": len(data["projects"])}
162
+ for data in groups
163
+ ],
164
+ "errors": errors,
165
+ }
166
+
167
+
168
+ def group_project_roots(home: Path) -> tuple[dict[str, tuple[Path, ...]], list[str]]:
169
+ """Every root the groups register for each projectId, and the unreadable group files."""
170
+ groups, errors = _read_all(home)
171
+ roots: dict[str, set[Path]] = {}
172
+ for data in groups:
173
+ for row in data["projects"]:
174
+ roots.setdefault(row["projectId"], set()).add(Path(row["projectRoot"]).resolve())
175
+ return {project_id: tuple(sorted(found)) for project_id, found in roots.items()}, errors
@@ -0,0 +1,62 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ from pathlib import Path
5
+
6
+ from okstra_project.dirs import okstra_home
7
+
8
+ from .fixed_text import emit_result
9
+ from .project_group import (
10
+ ProjectGroupError,
11
+ add_project,
12
+ list_groups,
13
+ remove_project,
14
+ show_group,
15
+ )
16
+
17
+
18
+ def _parser() -> argparse.ArgumentParser:
19
+ parser = argparse.ArgumentParser(
20
+ prog="okstra project-group",
21
+ description="Register which project roots belong to a named project group.",
22
+ )
23
+ commands = parser.add_subparsers(dest="command", required=True)
24
+ for name in ("add", "remove", "show", "list"):
25
+ command = commands.add_parser(name)
26
+ if name != "list":
27
+ command.add_argument("--project-group", required=True)
28
+ if name in ("add", "remove"):
29
+ command.add_argument("--project-id", required=True)
30
+ if name == "add":
31
+ command.add_argument("--project-root", required=True, type=Path)
32
+ output = command.add_mutually_exclusive_group()
33
+ output.add_argument("--json", action="store_true", help="emit JSON (default)")
34
+ output.add_argument("--text", action="store_true", help="emit fixed text fields")
35
+ return parser
36
+
37
+
38
+ def _emit(payload: dict, *, text: bool) -> None:
39
+ emit_result(payload, text=text, title="Okstra project-group")
40
+
41
+
42
+ def main(argv: list[str] | None = None) -> int:
43
+ args = _parser().parse_args(argv)
44
+ home = okstra_home()
45
+ try:
46
+ if args.command == "add":
47
+ result = add_project(home, args.project_group, args.project_id, args.project_root)
48
+ elif args.command == "remove":
49
+ result = remove_project(home, args.project_group, args.project_id)
50
+ elif args.command == "show":
51
+ result = show_group(home, args.project_group)
52
+ else:
53
+ result = list_groups(home)
54
+ except (ProjectGroupError, OSError) as exc:
55
+ _emit({"ok": False, "reason": str(exc)}, text=args.text)
56
+ return 1
57
+ _emit(result, text=args.text)
58
+ return 0 if result["ok"] else 1
59
+
60
+
61
+ if __name__ == "__main__":
62
+ raise SystemExit(main())
@@ -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(
@@ -1,10 +1,36 @@
1
1
  """Single registry for public final-report task contracts."""
2
2
  from __future__ import annotations
3
3
 
4
+ from collections.abc import Mapping
5
+
4
6
 
5
7
  CURRENT_REPORT_SCHEMA_VERSION = "3.0"
6
8
  LATEST_REPORT_SCHEMA_VERSION = "3.0"
7
9
 
10
+ REPORT_AUTHORING_MARKDOWN = "markdown-v1"
11
+ REPORT_AUTHORING_JSON = "json-v1"
12
+ _REPORT_AUTHORING_SUFFIXES = {
13
+ REPORT_AUTHORING_MARKDOWN: ".md",
14
+ REPORT_AUTHORING_JSON: ".json",
15
+ }
16
+ REPORT_AUTHORING_FORMATS = tuple(_REPORT_AUTHORING_SUFFIXES)
17
+
18
+
19
+ def report_authoring_format(manifest: Mapping[str, object]) -> str:
20
+ """Resolve the prepared writer format without reinterpreting legacy runs."""
21
+ value = manifest.get("reportAuthoringFormat", REPORT_AUTHORING_MARKDOWN)
22
+ if not isinstance(value, str) or value not in _REPORT_AUTHORING_SUFFIXES:
23
+ raise ValueError(f"unsupported reportAuthoringFormat: {value!r}")
24
+ if value == REPORT_AUTHORING_JSON and manifest.get("reportContractVersion", "3.0") != "3.0":
25
+ raise ValueError("json-v1 report authoring requires report contract 3.0")
26
+ return value
27
+
28
+
29
+ def report_authoring_suffix(input_format: str) -> str:
30
+ return _REPORT_AUTHORING_SUFFIXES[report_authoring_format({
31
+ "reportAuthoringFormat": input_format,
32
+ })]
33
+
8
34
  PUBLIC_REPORT_TASK_TYPES = (
9
35
  "requirements-discovery",
10
36
  "improvement-discovery",