okstra 0.231.1 → 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 (265) hide show
  1. package/README.md +19 -271
  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/memory/memory.mjs +9 -55
  10. package/dist/commands/memory/memory.mjs.map +1 -1
  11. package/dist/commands/trace/capacity.d.mts +12 -0
  12. package/dist/commands/trace/capacity.mjs +21 -0
  13. package/dist/commands/trace/capacity.mjs.map +1 -0
  14. package/dist/commands/trace/model.d.mts +89 -0
  15. package/dist/commands/trace/model.mjs +251 -0
  16. package/dist/commands/trace/model.mjs.map +1 -0
  17. package/dist/commands/trace/progression.d.mts +11 -0
  18. package/dist/commands/trace/progression.mjs +194 -0
  19. package/dist/commands/trace/progression.mjs.map +1 -0
  20. package/dist/commands/trace/review.d.mts +7 -0
  21. package/dist/commands/trace/review.mjs +51 -0
  22. package/dist/commands/trace/review.mjs.map +1 -0
  23. package/dist/commands/trace/task-link.d.mts +18 -0
  24. package/dist/commands/trace/task-link.mjs +72 -0
  25. package/dist/commands/trace/task-link.mjs.map +1 -0
  26. package/dist/commands/trace/trace.d.mts +1 -0
  27. package/dist/commands/trace/trace.mjs +293 -0
  28. package/dist/commands/trace/trace.mjs.map +1 -0
  29. package/dist/lib/bounded-file.d.mts +1 -0
  30. package/dist/lib/bounded-file.mjs +36 -0
  31. package/dist/lib/bounded-file.mjs.map +1 -0
  32. package/dist/lib/config-store.d.mts +34 -0
  33. package/dist/lib/config-store.mjs +70 -0
  34. package/dist/lib/config-store.mjs.map +1 -0
  35. package/dist/lib/file-lock.mjs +4 -5
  36. package/dist/lib/file-lock.mjs.map +1 -1
  37. package/dist/lib/input-limit.d.mts +4 -0
  38. package/dist/lib/input-limit.mjs +8 -0
  39. package/dist/lib/input-limit.mjs.map +1 -0
  40. package/dist/lib/memory-auto-register.d.mts +1 -0
  41. package/dist/lib/memory-auto-register.mjs +98 -0
  42. package/dist/lib/memory-auto-register.mjs.map +1 -0
  43. package/dist/lib/memory-entry-contract.d.mts +12 -0
  44. package/dist/lib/memory-entry-contract.mjs +46 -0
  45. package/dist/lib/memory-entry-contract.mjs.map +1 -0
  46. package/dist/lib/python-helper.d.mts +1 -1
  47. package/dist/lib/python-helper.mjs +3 -2
  48. package/dist/lib/python-helper.mjs.map +1 -1
  49. package/dist/lib/record-secrets.d.mts +1 -0
  50. package/dist/lib/record-secrets.mjs +28 -0
  51. package/dist/lib/record-secrets.mjs.map +1 -0
  52. package/dist/lib/report-language-tag.d.mts +1 -0
  53. package/dist/lib/report-language-tag.mjs +4 -0
  54. package/dist/lib/report-language-tag.mjs.map +1 -0
  55. package/dist/lib/report-language.d.mts +1 -0
  56. package/dist/lib/report-language.mjs +50 -0
  57. package/dist/lib/report-language.mjs.map +1 -0
  58. package/dist/lib/skill-catalog.mjs +3 -0
  59. package/dist/lib/skill-catalog.mjs.map +1 -1
  60. package/dist/lib/types.d.mts +2 -1
  61. package/docs/architecture/storage-model.md +163 -5
  62. package/docs/architecture.md +17 -4
  63. package/docs/cli.md +511 -0
  64. package/docs/contributor-change-matrix.md +1 -2
  65. package/docs/project-structure-overview.md +33 -42
  66. package/package.json +1 -1
  67. package/runtime/BUILD.json +2 -2
  68. package/runtime/agents/common.json +8 -8
  69. package/runtime/agents/operations/trace-interface-review.json +6 -0
  70. package/runtime/agents/operations/trace-scope-review.json +6 -0
  71. package/runtime/agents/roles/verifier.json +2 -4
  72. package/runtime/bin/okstra-provider-exec.py +10 -4
  73. package/runtime/prompts/coding-preflight/architectures/hexagonal.md +23 -30
  74. package/runtime/prompts/coding-preflight/authoring-checks.md +17 -0
  75. package/runtime/prompts/coding-preflight/clean-code.md +88 -286
  76. package/runtime/prompts/coding-preflight/frameworks/node-server.md +2 -3
  77. package/runtime/prompts/coding-preflight/languages/java.md +3 -5
  78. package/runtime/prompts/coding-preflight/languages/javascript-typescript.md +5 -12
  79. package/runtime/prompts/coding-preflight/languages/kotlin.md +2 -4
  80. package/runtime/prompts/coding-preflight/languages/python.md +2 -7
  81. package/runtime/prompts/coding-preflight/languages/rust.md +2 -8
  82. package/runtime/prompts/coding-preflight/languages/sql.md +2 -4
  83. package/runtime/prompts/coding-preflight/overview.md +25 -38
  84. package/runtime/prompts/coding-preflight/review-rules.json +30 -0
  85. package/runtime/prompts/duties/code-reviewer.json +15 -18
  86. package/runtime/prompts/duties/implementation-verifier.json +1 -0
  87. package/runtime/prompts/duties/interface-reviewer.json +32 -0
  88. package/runtime/prompts/host-orchestration/README.md +18 -9
  89. package/runtime/prompts/launch.template.md +3 -2
  90. package/runtime/prompts/lead/context-loader.md +2 -0
  91. package/runtime/prompts/lead/okstra-lead-contract.md +7 -7
  92. package/runtime/prompts/lead/report-writer.md +6 -6
  93. package/runtime/prompts/profiles/_coding-conventions-preflight.md +41 -6
  94. package/runtime/prompts/profiles/_common-contract.md +1 -1
  95. package/runtime/python/okstra_ctl/agent/invocation.py +122 -36
  96. package/runtime/python/okstra_ctl/agent/prompt_cli/cli.py +72 -26
  97. package/runtime/python/okstra_ctl/agent/prompt_cli/corrections.py +23 -8
  98. package/runtime/python/okstra_ctl/agent/prompt_cli/materialize.py +58 -14
  99. package/runtime/python/okstra_ctl/agent/prompt_cli/results.py +8 -11
  100. package/runtime/python/okstra_ctl/agent/standalone.py +15 -0
  101. package/runtime/python/okstra_ctl/analysis_packet.py +24 -30
  102. package/runtime/python/okstra_ctl/attempt_evidence.py +10 -0
  103. package/runtime/python/okstra_ctl/code_review_census.py +162 -7
  104. package/runtime/python/okstra_ctl/code_review_coverage.py +4 -274
  105. package/runtime/python/okstra_ctl/code_review_integrity.py +154 -0
  106. package/runtime/python/okstra_ctl/code_review_invocation.py +212 -0
  107. package/runtime/python/okstra_ctl/code_review_prepare.py +381 -0
  108. package/runtime/python/okstra_ctl/code_review_run.py +384 -0
  109. package/runtime/python/okstra_ctl/code_review_scope.py +49 -9
  110. package/runtime/python/okstra_ctl/code_review_supervisor.py +41 -0
  111. package/runtime/python/okstra_ctl/code_review_target.py +212 -13
  112. package/runtime/python/okstra_ctl/consumers.py +12 -9
  113. package/runtime/python/okstra_ctl/coverage_census.py +11 -2
  114. package/runtime/python/okstra_ctl/design_review.py +207 -0
  115. package/runtime/python/okstra_ctl/design_review_evidence.py +297 -0
  116. package/runtime/python/okstra_ctl/design_snapshot.py +16 -9
  117. package/runtime/python/okstra_ctl/direct_work.py +45 -3
  118. package/runtime/python/okstra_ctl/dispatch_core.py +31 -15
  119. package/runtime/python/okstra_ctl/dispatch_state.py +9 -2
  120. package/runtime/python/okstra_ctl/doctor.py +8 -25
  121. package/runtime/python/okstra_ctl/domain/role.py +1 -0
  122. package/runtime/python/okstra_ctl/doyouknow/__init__.py +9 -0
  123. package/runtime/python/okstra_ctl/doyouknow/cli.py +91 -0
  124. package/runtime/python/okstra_ctl/doyouknow/config.py +58 -0
  125. package/runtime/python/okstra_ctl/doyouknow/contracts.py +184 -0
  126. package/runtime/python/okstra_ctl/doyouknow/identity.py +22 -0
  127. package/runtime/python/okstra_ctl/doyouknow/paths.py +22 -0
  128. package/runtime/python/okstra_ctl/doyouknow/pending.py +72 -0
  129. package/runtime/python/okstra_ctl/doyouknow/registration.py +260 -0
  130. package/runtime/python/okstra_ctl/doyouknow/source_contracts.py +128 -0
  131. package/runtime/python/okstra_ctl/doyouknow/source_store.py +172 -0
  132. package/runtime/python/okstra_ctl/doyouknow/sources/io.py +36 -0
  133. package/runtime/python/okstra_ctl/doyouknow/sources/manager.py +300 -0
  134. package/runtime/python/okstra_ctl/doyouknow/sources/memory.py +179 -0
  135. package/runtime/python/okstra_ctl/doyouknow/sources/task.py +95 -0
  136. package/runtime/python/okstra_ctl/doyouknow/store.py +260 -0
  137. package/runtime/python/okstra_ctl/doyouknow/sync.py +58 -0
  138. package/runtime/python/okstra_ctl/execution_mutation_audit.py +18 -2
  139. package/runtime/python/okstra_ctl/file_size_cap.py +3 -4
  140. package/runtime/python/okstra_ctl/final_report_schema.py +37 -34
  141. package/runtime/python/okstra_ctl/incremental_carry.py +6 -7
  142. package/runtime/python/okstra_ctl/initial_prompt_materialization.py +9 -2
  143. package/runtime/python/okstra_ctl/json_boundary.py +51 -5
  144. package/runtime/python/okstra_ctl/jsonl.py +21 -0
  145. package/runtime/python/okstra_ctl/manager_cli.py +148 -1
  146. package/runtime/python/okstra_ctl/manager_journal.py +126 -0
  147. package/runtime/python/okstra_ctl/manager_launch.py +3 -3
  148. package/runtime/python/okstra_ctl/manager_log.py +221 -0
  149. package/runtime/python/okstra_ctl/manager_paths.py +8 -0
  150. package/runtime/python/okstra_ctl/manager_registration.py +29 -0
  151. package/runtime/python/okstra_ctl/manager_resume.py +59 -0
  152. package/runtime/python/okstra_ctl/manager_split.py +2 -2
  153. package/runtime/python/okstra_ctl/manager_store.py +116 -17
  154. package/runtime/python/okstra_ctl/manager_sync.py +45 -25
  155. package/runtime/python/okstra_ctl/manager_view.py +35 -2
  156. package/runtime/python/okstra_ctl/material.py +2 -0
  157. package/runtime/python/okstra_ctl/model_cli.py +64 -14
  158. package/runtime/python/okstra_ctl/model_defaults.py +22 -0
  159. package/runtime/python/okstra_ctl/model_io/renderers.py +16 -2
  160. package/runtime/python/okstra_ctl/model_io_cli.py +7 -1
  161. package/runtime/python/okstra_ctl/operation_invocation.py +207 -28
  162. package/runtime/python/okstra_ctl/path_hints.py +14 -3
  163. package/runtime/python/okstra_ctl/paths.py +6 -1
  164. package/runtime/python/okstra_ctl/phases/catalog.py +24 -7
  165. package/runtime/python/okstra_ctl/phases/final_verification/validation.py +20 -0
  166. package/runtime/python/okstra_ctl/phases/implementation/host-rules.md +3 -3
  167. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-deliverable.md +10 -0
  168. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-diff-review.md +23 -8
  169. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-self-check.md +6 -4
  170. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-verifier.md +38 -10
  171. package/runtime/python/okstra_ctl/phases/implementation/report_assets/implementation.template.html +13 -0
  172. package/runtime/python/okstra_ctl/phases/implementation/spec.md +25 -0
  173. package/runtime/python/okstra_ctl/phases/implementation/validation.py +6 -0
  174. package/runtime/python/okstra_ctl/phases/implementation_option_selection/profile.md +1 -1
  175. package/runtime/python/okstra_ctl/phases/implementation_option_selection/votes.py +11 -11
  176. package/runtime/python/okstra_ctl/phases/implementation_planning/authoring.py +16 -9
  177. package/runtime/python/okstra_ctl/phases/implementation_planning/host-rules.md +3 -6
  178. package/runtime/python/okstra_ctl/phases/implementation_planning/instructions/plan-body-verification.md +12 -10
  179. package/runtime/python/okstra_ctl/phases/implementation_planning/profile.md +6 -6
  180. package/runtime/python/okstra_ctl/phases/improvement_discovery/lenses.py +12 -0
  181. package/runtime/python/okstra_ctl/phases/improvement_discovery/profile.md +7 -6
  182. package/runtime/python/okstra_ctl/phases/improvement_discovery/resolved_census.py +159 -0
  183. package/runtime/python/okstra_ctl/phases/improvement_discovery/spec.md +5 -2
  184. package/runtime/python/okstra_ctl/phases/improvement_discovery/validation.py +21 -7
  185. package/runtime/python/okstra_ctl/phases/release_handoff/boundary.json +1 -1
  186. package/runtime/python/okstra_ctl/phases/release_handoff/profile.md +4 -1
  187. package/runtime/python/okstra_ctl/plan_verify_cli.py +6 -4
  188. package/runtime/python/okstra_ctl/render.py +28 -2
  189. package/runtime/python/okstra_ctl/report_assembly.py +53 -11
  190. package/runtime/python/okstra_ctl/report_contract.py +26 -0
  191. package/runtime/python/okstra_ctl/report_corrections.py +36 -20
  192. package/runtime/python/okstra_ctl/report_inputs.py +1 -0
  193. package/runtime/python/okstra_ctl/report_language.py +4 -1
  194. package/runtime/python/okstra_ctl/report_narrative.py +182 -7
  195. package/runtime/python/okstra_ctl/report_projections.py +64 -18
  196. package/runtime/python/okstra_ctl/report_synthesis_packet.py +97 -38
  197. package/runtime/python/okstra_ctl/review_policy.py +359 -0
  198. package/runtime/python/okstra_ctl/review_verdicts.py +291 -0
  199. package/runtime/python/okstra_ctl/run.py +67 -36
  200. package/runtime/python/okstra_ctl/run_context.py +10 -1
  201. package/runtime/python/okstra_ctl/set_work_status.py +4 -15
  202. package/runtime/python/okstra_ctl/stage_done.py +11 -0
  203. package/runtime/python/okstra_ctl/standalone_review_audit.py +28 -0
  204. package/runtime/python/okstra_ctl/task_list_cli.py +34 -8
  205. package/runtime/python/okstra_ctl/task_query.py +239 -0
  206. package/runtime/python/okstra_ctl/trace_review.py +264 -0
  207. package/runtime/python/okstra_ctl/trace_tasks.py +197 -0
  208. package/runtime/python/okstra_ctl/user_authorization.py +14 -0
  209. package/runtime/python/okstra_ctl/verification_generation.py +23 -1
  210. package/runtime/python/okstra_ctl/verification_input_types.py +15 -1
  211. package/runtime/python/okstra_ctl/verification_inputs.py +28 -6
  212. package/runtime/python/okstra_ctl/verification_invocation.py +7 -1
  213. package/runtime/python/okstra_ctl/verification_target.py +2 -0
  214. package/runtime/python/okstra_ctl/wizard/confirmation.py +7 -3
  215. package/runtime/python/okstra_ctl/wizard/launch.py +52 -0
  216. package/runtime/python/okstra_ctl/wizard/launch_cli.py +39 -0
  217. package/runtime/python/okstra_ctl/wizard/outcome.py +17 -16
  218. package/runtime/python/okstra_ctl/wizard/registry.py +1 -1
  219. package/runtime/python/okstra_ctl/wizard/render.py +8 -0
  220. package/runtime/python/okstra_ctl/wizard/state.py +2 -1
  221. package/runtime/python/okstra_ctl/worker_prompt_headers.py +24 -9
  222. package/runtime/python/okstra_ctl/worker_runner.py +66 -10
  223. package/runtime/python/okstra_ctl/write_policy.py +34 -1
  224. package/runtime/python/okstra_project/__init__.py +2 -0
  225. package/runtime/python/okstra_project/dirs.py +18 -0
  226. package/runtime/python/okstra_project/state.py +45 -20
  227. package/runtime/python/okstra_token_usage/blocks.py +74 -0
  228. package/runtime/python/okstra_token_usage/cli.py +23 -10
  229. package/runtime/python/okstra_token_usage/collect.py +25 -22
  230. package/runtime/python/okstra_token_usage/policy.py +193 -0
  231. package/runtime/schemas/doyouknow-config-v1.schema.json +20 -0
  232. package/runtime/schemas/doyouknow-v1.schema.json +65 -0
  233. package/runtime/schemas/final-report-v2.0.schema.json +157 -0
  234. package/runtime/schemas/final-report-v3.0.schema.json +157 -0
  235. package/runtime/schemas/memory-entry-contract-v1.json +11 -0
  236. package/runtime/schemas/record-secret-patterns.json +41 -0
  237. package/runtime/schemas/report-synthesis-packet-v1.0.schema.json +1 -1
  238. package/runtime/skills/_fragments/wizard-confirm-step.md +1 -1
  239. package/runtime/skills/_fragments/wizard-preflight.md +1 -1
  240. package/runtime/skills/_fragments/wizard-prompt-loop.md +3 -5
  241. package/runtime/skills/_fragments/wizard-relay-protocol.md +1 -1
  242. package/runtime/skills/_fragments/wizard-render-bundle.md +15 -29
  243. package/runtime/skills/okstra-brief-gen/SKILL.md +7 -7
  244. package/runtime/skills/okstra-brief-gen/references/tracker-recursion.md +1 -1
  245. package/runtime/skills/okstra-code-review/SKILL.md +92 -136
  246. package/runtime/skills/okstra-code-review/references/census-rules.md +29 -105
  247. package/runtime/skills/okstra-code-review/references/review-calibration.md +37 -61
  248. package/runtime/skills/okstra-discussion/SKILL.md +22 -38
  249. package/runtime/skills/okstra-explain-flow/SKILL.md +6 -2
  250. package/runtime/skills/okstra-manager/SKILL.md +31 -0
  251. package/runtime/skills/okstra-memory/SKILL.md +8 -1
  252. package/runtime/skills/okstra-pr-gen/SKILL.md +1 -1
  253. package/runtime/skills/okstra-run/SKILL.md +55 -183
  254. package/runtime/skills/okstra-schedule-gen/SKILL.md +9 -13
  255. package/runtime/skills/okstra-setup/SKILL.md +3 -2
  256. package/runtime/skills/okstra-setup/references/project-config.md +2 -4
  257. package/runtime/skills/okstra-tdd/SKILL.md +187 -0
  258. package/runtime/skills/okstra-user-response/SKILL.md +4 -2
  259. package/runtime/templates/implementation-worker-preamble.md +4 -9
  260. package/runtime/templates/manager/view.template.html +4 -0
  261. package/runtime/templates/report-writer-prompt-preamble.md +15 -3
  262. package/runtime/templates/trace/trace.template.md +42 -0
  263. package/runtime/templates/worker-prompt-preamble.md +4 -12
  264. package/runtime/validators/checks/fixtures-02.py +25 -33
  265. package/runtime/validators/validate-run.py +107 -38
@@ -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",
@@ -26,8 +26,8 @@ from .json_boundary import JsonBoundaryError, load_owned_object
26
26
  from .report_markdown import humanise
27
27
  from .report_narrative import (
28
28
  NarrativeContractError,
29
- parse_narrative_structure,
30
- render_narrative,
29
+ parse_report_narrative,
30
+ render_report_narrative,
31
31
  validate_writer_owned,
32
32
  writer_owned_path_defect,
33
33
  writer_owned_schema,
@@ -125,8 +125,11 @@ def normalise_field_path(path: str) -> str:
125
125
  return _INDEX_RE.sub("[]", path)
126
126
 
127
127
 
128
- def humanise_field_path(tokens: Sequence[str | int]) -> str:
129
- """스키마 키 경로를 작성자가 쓰는 라벨 경로로: `Ranked Options` -> `Item 2`."""
128
+ def format_writer_field_path(tokens: Sequence[str | int], *, input_format: str = "markdown-v1") -> str:
129
+ """Format a field path as exact JSON keys/indexes or humanised Markdown labels."""
130
+ if input_format == "json-v1":
131
+ path = "".join(f"[{token}]" if isinstance(token, int) else f".{token}" for token in tokens)
132
+ return f"`{path.lstrip('.')}`"
130
133
  parts = [
131
134
  f"`Item {token + 1}`" if isinstance(token, int) else f"`{humanise(token)}`"
132
135
  for token in tokens
@@ -196,6 +199,7 @@ def check_corrections(
196
199
  block_rules: Sequence[str] = (),
197
200
  semantic_validator: Callable[[dict[str, Any]], Sequence[str]] | None = None,
198
201
  rewrite_results: Mapping[str, Any] | None = None,
202
+ input_format: str = "markdown-v1",
199
203
  ) -> CorrectionsCheck:
200
204
  """원장을 기준 서사에 대조한다. 설계 §4.2 의 1~6단계.
201
205
 
@@ -220,7 +224,8 @@ def check_corrections(
220
224
  ledger_dict["baseNarrativeSha256"] = digest
221
225
  corrections, parsed, defects = _parse_corrections(ledger_dict)
222
226
  try:
223
- data, _base_defects = parse_narrative_structure(base_narrative, schema)
227
+ data = parse_report_narrative(base_narrative, schema, input_format=input_format,
228
+ structure_only=True)
224
229
  except NarrativeContractError as exc:
225
230
  defects.append(_defect("ledger", str(ledger_dict.get("baseNarrativePath") or "-"),
226
231
  f"base narrative does not parse: {exc}"))
@@ -236,7 +241,7 @@ def check_corrections(
236
241
  derived = _recount_planning_steps(scratch, corrections, rewrites)
237
242
  corrections = (*corrections, *derived)
238
243
  ledger_dict["corrections"] = list(corrections)
239
- constraints = {str(item["id"]): _constraints_for(str(item["path"]), block_rules, schema)
244
+ constraints = {str(item["id"]): _constraints_for(str(item["path"]), block_rules, schema, input_format)
240
245
  for item in rewrites}
241
246
  errors = validate_writer_owned(scratch, schema)
242
247
  if semantic_validator is not None:
@@ -435,13 +440,14 @@ def _complete_rewrites(
435
440
 
436
441
  def _constraints_for(
437
442
  path: str, block_rules: Sequence[str], schema: Mapping[str, Any],
443
+ input_format: str,
438
444
  ) -> tuple[str, ...]:
439
- """가장 가까운 필드의 제약. 공통 필드도 검증에 쓰는 스키마에서 추출한다."""
445
+ """Describe the nearest field in the writer's declared authoring format."""
440
446
  normalised = normalise_field_path(path)
441
447
  root_key = str(parse_field_path(path)[0])
442
448
  rules = block_rules
443
449
  if not any(rule.startswith(f"`{root_key}`: ") for rule in rules):
444
- rules = task_block_rules(writer_owned_schema(schema), root_key)
450
+ rules = task_block_rules(writer_owned_schema(schema), root_key, authoring_format=input_format)
445
451
  candidates = [normalised]
446
452
  while "." in candidates[-1]:
447
453
  candidates.append(candidates[-1].rsplit(".", 1)[0])
@@ -456,7 +462,7 @@ def _constraints_for(
456
462
 
457
463
 
458
464
  def render_applied_narrative(
459
- check: CorrectionsCheck, schema: Mapping[str, Any],
465
+ check: CorrectionsCheck, schema: Mapping[str, Any], *, input_format: str = "markdown-v1",
460
466
  ) -> str:
461
467
  """확정 값으로 구성된 원장을 적용한 서사 본문.
462
468
 
@@ -476,7 +482,7 @@ def render_applied_narrative(
476
482
  "or use only replace, remove, add and move entries",
477
483
  )]
478
484
  )
479
- return render_narrative(check.scratch, schema)
485
+ return render_report_narrative(check.scratch, schema, input_format=input_format)
480
486
 
481
487
 
482
488
  def body_owned_section_conflicts(body: str) -> list[str]:
@@ -485,7 +491,9 @@ def body_owned_section_conflicts(body: str) -> list[str]:
485
491
  return [section for section in OKSTRA_OWNED_SECTIONS if section in present]
486
492
 
487
493
 
488
- def _scalar_text(value: Any) -> str:
494
+ def _scalar_text(value: Any, *, input_format: str = "markdown-v1") -> str:
495
+ if input_format == "json-v1":
496
+ return "`" + json.dumps(value, ensure_ascii=False) + "`"
489
497
  if isinstance(value, str):
490
498
  if "\n" in value:
491
499
  lines = value.split("\n")
@@ -502,6 +510,7 @@ def _scalar_text(value: Any) -> str:
502
510
 
503
511
  def render_corrections_section(
504
512
  check: CorrectionsCheck, *, base_narrative_rel: str, corrections_rel: str,
513
+ input_format: str = "markdown-v1",
505
514
  ) -> list[str]:
506
515
  """프롬프트의 `## Corrections` 절. 검증을 통과한 원장만 렌더한다."""
507
516
  lines = [
@@ -519,17 +528,19 @@ def render_corrections_section(
519
528
  path = str(item.get("path"))
520
529
  kind = str(item.get("kind"))
521
530
  try:
522
- label = humanise_field_path(parse_field_path(path))
531
+ label = format_writer_field_path(parse_field_path(path), input_format=input_format)
523
532
  except ValueError:
524
533
  label = f"`{path}`"
525
- head = f"- {correction_id} `{kind}` — {label} (`{path}`): "
534
+ target = label if input_format == "json-v1" else f"{label} (`{path}`)"
535
+ head = f"- {correction_id} `{kind}` — {target}: "
526
536
  if kind in {"replace", "add"}:
527
537
  current = (
528
- f"current {_scalar_text(item['current'])}, " if "current" in item else ""
538
+ f"current {_scalar_text(item['current'], input_format=input_format)}, " if "current" in item else ""
529
539
  )
530
- action = f"{current}write exactly {_scalar_text(item.get('replacement'))}."
540
+ action = f"{current}write exactly {_scalar_text(item.get('replacement'), input_format=input_format)}."
531
541
  elif kind == "remove":
532
- action = "remove this item or field entirely; renumber the remaining `- Item N` rows 1..N."
542
+ action = ("remove this array entry or object field entirely." if input_format == "json-v1"
543
+ else "remove this item or field entirely; renumber the remaining `- Item N` rows 1..N.")
533
544
  elif kind == "move":
534
545
  action = f"move the unchanged value from `{item.get('fromPath')}`."
535
546
  else:
@@ -549,20 +560,25 @@ def render_corrections_section(
549
560
  "",
550
561
  "Outside the correction paths, preserve every sentence, score, evidence path, "
551
562
  "and verdict. Follow the schema constraints when a correction describes an "
552
- "incompatible shape. Preserve the blockquote indentation: each value line "
553
- "sits two spaces deeper than its own `- **Label**` line.",
563
+ "incompatible shape. " + (
564
+ "Keep the exact JSON keys, array indexes and native JSON value types."
565
+ if input_format == "json-v1" else
566
+ "Preserve the blockquote indentation: each value line sits two spaces deeper "
567
+ "than its own `- **Label**` line."
568
+ ),
554
569
  ])
555
570
  return lines
556
571
 
557
572
 
558
- def render_output_section() -> list[str]:
573
+ def render_output_section(*, input_format: str = "markdown-v1") -> list[str]:
559
574
  """프롬프트의 `## Output` 절 — 세 산출물을 okstra 가 열거한다."""
560
575
  return [
561
576
  "## Output",
562
577
  "",
563
578
  "Write all three artifacts before returning.",
564
579
  "",
565
- "1. The report narrative Markdown at `**Result Path:**`.",
580
+ ("1. The report writer JSON object at `**Result Path:**`." if input_format == "json-v1"
581
+ else "1. The report narrative Markdown at `**Result Path:**`."),
566
582
  "2. The pointer record at `**Worker Result Path:**`.",
567
583
  "3. The reading audit at `**Audit sidecar path:**`.",
568
584
  ]
@@ -6,6 +6,7 @@ from pathlib import Path
6
6
  from typing import Any, Mapping
7
7
 
8
8
  from .qa_commands import QA_VERIFIER_AUDIENCE_BY_TASK_TYPE
9
+ from .report_contract import REPORT_AUTHORING_FORMATS, report_authoring_format
9
10
  from .verification_invocation import verification_generation_required
10
11
 
11
12
 
@@ -1,4 +1,7 @@
1
- """Report-language resolution — the one place the precedence lives.
1
+ """Report-language resolution for Python execution paths.
2
+
3
+ The independent TypeScript trace command uses src/lib/report-language.mts;
4
+ tests-js/trace.test.mjs checks that both resolvers follow the same precedence.
2
5
 
3
6
  Prepare calls this once and freezes the answer as `reportLanguage` in the run
4
7
  manifest. Both report-writer dispatch paths stamp that manifest value as the
@@ -1,7 +1,8 @@
1
- """보고서 작성자 전담 Markdown 서사의 손실 없는 읽기·쓰기 계약."""
1
+ """보고서 작성자 전담 입력의 선언된 형식과 소유권·값 검증 계약."""
2
2
  from __future__ import annotations
3
3
 
4
4
  import json
5
+ import math
5
6
  import re
6
7
  from copy import deepcopy
7
8
  from pathlib import Path
@@ -9,11 +10,15 @@ from typing import Any, Mapping
9
10
 
10
11
  from .final_report_schema import load_schema_version, validate
11
12
  from .report_markdown import SchemaIndex, humanise, label_key
12
- from .json_boundary import load_owned_object
13
+ from .json_boundary import external_worker_json_source, load_external_json, load_owned_object
14
+ from .report_contract import REPORT_AUTHORING_FORMATS, report_authoring_format
13
15
 
14
16
 
15
17
  TITLE = "# OKSTRA Report Narrative"
16
18
  EMPTY_MARKER = "_none_"
19
+ WRITER_INPUT_MAX_BYTES = 2_000_000
20
+ WRITER_INPUT_MAX_DEPTH = 32
21
+ WRITER_INPUT_MAX_PATH_CHARS = WRITER_INPUT_MAX_BYTES * WRITER_INPUT_MAX_DEPTH
17
22
  _FIELD_RE = re.compile(r"^(?P<indent> *)- \*\*(?P<label>.+)\*\*$")
18
23
  _ITEM_RE = re.compile(r"^(?P<indent> *)- Item (?P<position>[1-9]\d*)$")
19
24
  _VALUE_RE = re.compile(r"^(?P<indent> *)> ?(?P<value>.*)$")
@@ -21,15 +26,170 @@ _NESTED_FORBIDDEN = frozenset(
21
26
  {
22
27
  "implementationPlanning.designPreparation",
23
28
  "implementationPlanning.planBodyVerification",
29
+ "implementationPlanning.stages.designSurfaceCoverage",
24
30
  # Report assembly derives these from the verification execution records.
25
31
  "implementation.verifierResults.executionEvidence",
32
+ "implementation.verifierResults.designReview",
26
33
  "finalVerification.readonlyCommandLog.executionEvidence",
27
34
  }
28
35
  )
29
36
 
30
37
 
31
38
  class NarrativeContractError(ValueError):
32
- """서사 입력이 보고서 작성자 소유권이나 Markdown 문법을 위반했다."""
39
+ """서사 입력이 보고서 작성자 소유권이나 선언된 형식을 위반했다."""
40
+
41
+
42
+ def _json_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
43
+ result: dict[str, Any] = {}
44
+ for key, value in pairs:
45
+ if key in result:
46
+ raise NarrativeContractError(f"owner=report-writer duplicate JSON key: {key}")
47
+ result[key] = value
48
+ return result
49
+
50
+
51
+ def _json_writer_data(value: Any, *, structure_only: bool, schema: Mapping[str, Any]) -> dict[str, Any]:
52
+ if not isinstance(value, dict):
53
+ raise NarrativeContractError("owner=report-writer top-level JSON value must be an object")
54
+ defects: list[str] = []
55
+ allowed = _allowed_top_level()
56
+ path_chars = 0
57
+
58
+ def inspect(node: Any, path: str, depth: int) -> None:
59
+ nonlocal path_chars
60
+ if depth > WRITER_INPUT_MAX_DEPTH:
61
+ raise NarrativeContractError(
62
+ f"owner=report-writer JSON nesting exceeds {WRITER_INPUT_MAX_DEPTH} levels"
63
+ )
64
+ path_chars += len(path)
65
+ if path_chars > WRITER_INPUT_MAX_PATH_CHARS:
66
+ raise NarrativeContractError(
67
+ "owner=report-writer JSON field path traversal exceeds "
68
+ f"{WRITER_INPUT_MAX_PATH_CHARS} characters"
69
+ )
70
+ if isinstance(node, dict):
71
+ for key, child in node.items():
72
+ child_path = f"{path}.{key}" if path else key
73
+ defect = writer_owned_path_defect(child_path, allowed_top_level=allowed)
74
+ if defect:
75
+ defects.append(f"owner=report-writer path={child_path} {defect}")
76
+ else:
77
+ inspect(child, child_path, depth + 1)
78
+ elif isinstance(node, list):
79
+ for index, child in enumerate(node):
80
+ inspect(child, f"{path}[{index}]", depth + 1)
81
+ elif isinstance(node, float) and not math.isfinite(node):
82
+ defects.append(f"owner=report-writer path={path} non-standard JSON numeric value")
83
+
84
+ try:
85
+ inspect(value, "", 0)
86
+ if not structure_only:
87
+ defects.extend(f"owner=report-writer {error}" for error in validate_writer_owned(value, schema))
88
+ except RecursionError as exc:
89
+ raise NarrativeContractError("owner=report-writer JSON nesting exceeds supported depth") from exc
90
+ if defects:
91
+ raise NarrativeContractError("; ".join(defects))
92
+ return value
93
+
94
+
95
+ def _check_json_text_size(text: str) -> None:
96
+ if len(text) > WRITER_INPUT_MAX_BYTES or len(text.encode("utf-8")) > WRITER_INPUT_MAX_BYTES:
97
+ raise NarrativeContractError(
98
+ f"owner=report-writer input exceeds {WRITER_INPUT_MAX_BYTES} bytes"
99
+ )
100
+
101
+
102
+ def parse_report_narrative(
103
+ text: str, schema: Mapping[str, Any], *, input_format: str = "markdown-v1",
104
+ structure_only: bool = False,
105
+ ) -> dict[str, Any]:
106
+ """Normalize declared writer input; runtime file reads use load_report_narrative."""
107
+ if input_format == "markdown-v1":
108
+ return parse_narrative_structure(text, schema)[0] if structure_only else parse_narrative(text, schema)
109
+ if input_format != "json-v1":
110
+ raise NarrativeContractError(f"unknown reportAuthoringFormat: {input_format!r}")
111
+ _check_json_text_size(text)
112
+ try:
113
+ value = json.loads(text, object_pairs_hook=_json_object)
114
+ except json.JSONDecodeError as exc:
115
+ raise NarrativeContractError(f"owner=report-writer invalid JSON: {exc}") from exc
116
+ except RecursionError as exc:
117
+ raise NarrativeContractError("owner=report-writer JSON nesting exceeds supported depth") from exc
118
+ return _json_writer_data(value, structure_only=structure_only, schema=schema)
119
+
120
+
121
+ def load_report_narrative(
122
+ project_root: Path, manifest: Mapping[str, Any], schema: Mapping[str, Any], *,
123
+ path: Path | None = None, structure_only: bool = False,
124
+ allow_preserved_attempt: bool = False,
125
+ ) -> dict[str, Any]:
126
+ """Read declared input, or an explicitly allowed preserved attempt in its lane."""
127
+ from .report_inputs import report_narrative_path
128
+
129
+ input_format = report_authoring_format(manifest)
130
+ declared_path = report_narrative_path(project_root, manifest)
131
+ source_path = path if path is not None else declared_path
132
+ if input_format == "markdown-v1":
133
+ return parse_report_narrative(
134
+ source_path.read_text(encoding="utf-8"), schema, structure_only=structure_only,
135
+ )
136
+ if not allow_preserved_attempt and source_path.resolve() != declared_path.resolve():
137
+ raise NarrativeContractError("narrative path does not match reportNarrativePath")
138
+ source = external_worker_json_source(
139
+ source_path, trusted_root=project_root, lane_root=declared_path.parent,
140
+ )
141
+ try:
142
+ value = load_external_json(
143
+ source, artifact="report writer input", object_pairs_hook=_json_object,
144
+ max_bytes=WRITER_INPUT_MAX_BYTES,
145
+ )
146
+ except RecursionError as exc:
147
+ raise NarrativeContractError("owner=report-writer JSON nesting exceeds supported depth") from exc
148
+ return _json_writer_data(value, structure_only=structure_only, schema=schema)
149
+
150
+
151
+ def load_writer_input(
152
+ path: Path, *, run_manifest: Path | None = None, structure_only: bool = False,
153
+ ) -> dict[str, Any]:
154
+ """Read a CLI writer input using captured run authority or legacy Markdown."""
155
+ schema = load_schema_version("3.0")
156
+ if run_manifest is None:
157
+ return parse_report_narrative(
158
+ path.read_text(encoding="utf-8"), schema, structure_only=structure_only,
159
+ )
160
+ from .convergence import validated_run_authority
161
+
162
+ authority = validated_run_authority(run_manifest)
163
+ return load_report_narrative(
164
+ authority.project_root, authority.payload, schema, path=path,
165
+ structure_only=structure_only,
166
+ )
167
+
168
+
169
+ def render_report_narrative(
170
+ data: Mapping[str, Any], schema: Mapping[str, Any], *, input_format: str = "markdown-v1",
171
+ ) -> str:
172
+ """Encode corrected writer data in the run's captured format."""
173
+ if input_format == "markdown-v1":
174
+ return render_narrative(data, schema)
175
+ if input_format not in REPORT_AUTHORING_FORMATS:
176
+ raise NarrativeContractError(f"unknown reportAuthoringFormat: {input_format!r}")
177
+ _json_writer_data(dict(data), structure_only=True, schema=schema)
178
+ text = json.dumps(data, ensure_ascii=False, indent=2, allow_nan=False) + "\n"
179
+ _check_json_text_size(text)
180
+ return text
181
+
182
+
183
+ def report_narrative_structure_defect(
184
+ project_root: Path, manifest: Mapping[str, Any], *, path: Path | None = None,
185
+ ) -> str | None:
186
+ """Return syntax or ownership failures while allowing correctable value defects."""
187
+ try:
188
+ load_report_narrative(project_root, manifest, load_schema_version("3.0"),
189
+ path=path, structure_only=True)
190
+ except (OSError, ValueError) as exc:
191
+ return str(exc)
192
+ return None
33
193
 
34
194
 
35
195
  # 작성자에게 도달해야 하는 줄 문법 — 합성 패킷의 Authoring Contract 가 이것을
@@ -53,6 +213,16 @@ NARRATIVE_GRAMMAR_INSTRUCTIONS: tuple[str, ...] = (
53
213
  "refuses the file otherwise and the run publishes no report.",
54
214
  )
55
215
 
216
+ JSON_NARRATIVE_INSTRUCTIONS: tuple[str, ...] = (
217
+ "Write one standard JSON object using the schema's exact JSON field names. "
218
+ "Do not add Markdown fences, headings, a preamble, duplicate keys, or non-standard numeric values.",
219
+ "Use native JSON arrays, objects, numbers, booleans and null; do not use humanised "
220
+ "field labels, `- Item N` rows, blockquote value lines, or `_none_`. Description "
221
+ "strings may contain ordinary Markdown, including tables, newlines and code blocks.",
222
+ "Author only writer-owned fields allowed by the supplied schema. Machine-owned "
223
+ "approval, execution, usage, convergence and verification data are provided by their owners.",
224
+ )
225
+
56
226
 
57
227
  def narrative_structure_defect(markdown: str) -> str | None:
58
228
  """줄 문법 위반 메시지, 없으면 None — 수집 시점의 산출물 검사용.
@@ -119,7 +289,7 @@ def allowed_top_level_fields() -> frozenset[str]:
119
289
  # 깨진다. 앞의 둘은 `_NESTED_FORBIDDEN` 에서 파생시켜 두 목록이 갈라지지
120
290
  # 않게 한다.
121
291
  _MACHINE_OWNED_NESTED = frozenset(
122
- {path.rsplit(".", 1)[-1] for path in _NESTED_FORBIDDEN} | {"designSurfaceCoverage"}
292
+ path.rsplit(".", 1)[-1] for path in _NESTED_FORBIDDEN
123
293
  )
124
294
 
125
295
 
@@ -211,7 +381,9 @@ def task_narrative_errors(
211
381
  return list(dict.fromkeys(errors))
212
382
 
213
383
 
214
- def writer_owned_path_defect(path: str) -> str | None:
384
+ def writer_owned_path_defect(
385
+ path: str, *, allowed_top_level: frozenset[str] | None = None,
386
+ ) -> str | None:
215
387
  """이 필드 경로에 작성자가 쓸 수 없는 이유, 쓸 수 있으면 None.
216
388
 
217
389
  경로는 검증기 문법(`a.b[1].c`)이다. 최상위 이름은 서사 스키마의 허용목록에
@@ -220,8 +392,9 @@ def writer_owned_path_defect(path: str) -> str | None:
220
392
  """
221
393
  dotted = _field_path(path)
222
394
  top = dotted.split(".", 1)[0]
223
- if top not in _allowed_top_level():
224
- owned = ", ".join(f"`{humanise(key)}`" for key in sorted(_allowed_top_level()))
395
+ allowed = _allowed_top_level() if allowed_top_level is None else allowed_top_level
396
+ if top not in allowed:
397
+ owned = ", ".join(f"`{humanise(key)}`" for key in sorted(allowed))
225
398
  return (
226
399
  f"`{top}` is not a writer-owned top-level field; writer-owned: {owned}"
227
400
  )
@@ -244,6 +417,8 @@ def writer_owned_data(data: Mapping[str, Any]) -> dict[str, Any]:
244
417
  if key in _allowed_top_level()
245
418
  }
246
419
  planning = owned.get("implementationPlanning")
420
+ for row in (owned.get("implementation") or {}).get("verifierResults", []):
421
+ row.pop("designReview", None)
247
422
  if isinstance(planning, dict):
248
423
  planning.pop("designPreparation", None)
249
424
  planning.pop("planBodyVerification", None)
@@ -1,7 +1,14 @@
1
1
  """역할별 실행 입력을 최종 리포트 조각으로 바꾸는 순수 투영."""
2
2
  from __future__ import annotations
3
3
 
4
- from okstra_token_usage.blocks import accounting_workers
4
+ from okstra_token_usage.blocks import (
5
+ cli_usage_required,
6
+ report_usage_workers as _report_workers,
7
+ usage_is_incomplete,
8
+ usage_is_measured_zero,
9
+ usage_participants,
10
+ )
11
+ from okstra_token_usage.policy import usage_accounting_policy
5
12
 
6
13
  import json
7
14
  from typing import Any, Mapping
@@ -33,22 +40,6 @@ _STATUS = {
33
40
  }
34
41
 
35
42
 
36
- def _report_workers(team_state: Mapping[str, Any]) -> list[dict]:
37
- """리드 자신의 워커 항목을 뺀 워커 행.
38
-
39
- team-state 는 리드를 `workerId: lead` 워커로도 적는다(agent 없음, 상태
40
- `dispatched`). 리드 행은 `lead`·`leadUsage` 에서 따로 만들므로 이 항목을
41
- 표에 올리면 "Codex · lead · unknown · 미실행" 행이 하나 더 생긴다.
42
- """
43
- return [
44
- row for row in accounting_workers(team_state)
45
- if "lead" not in {
46
- str(row.get("workerId") or "").strip().lower(),
47
- str(row.get("role") or "").strip().lower(),
48
- }
49
- ]
50
-
51
-
52
43
  def _text(value: object, fallback: str) -> str:
53
44
  text = str(value or "").strip()
54
45
  return text or fallback
@@ -211,10 +202,65 @@ def _worker_details(team_state: Mapping[str, Any]) -> list[dict[str, Any]]:
211
202
  return result
212
203
 
213
204
 
214
- def project_token_usage(team_state: Mapping[str, Any]) -> dict[str, Any]:
205
+ def _complete_usage_total(
206
+ blocks: list[Mapping[str, Any]], key: str, *, default: int | None = None,
207
+ ) -> int | float | None:
208
+ values = []
209
+ cli = key.startswith("cli")
210
+ for block in blocks:
211
+ if usage_is_incomplete(block, cli=cli):
212
+ return None
213
+ value = block.get(key, default)
214
+ if value is None and usage_is_measured_zero(block, cli=cli):
215
+ value = 0
216
+ if value is None:
217
+ return None
218
+ values.append(value)
219
+ return sum(values)
220
+
221
+
222
+ def _advisory_usage_summary(team_state: Mapping[str, Any]) -> dict[str, Any]:
223
+ """Project missing participants without changing the collector's counters."""
224
+ lead = team_state.get("leadUsage") or {}
225
+ rows = usage_participants(team_state)
226
+ workers = [row.get("usage") or {} for row in rows]
227
+ def combine(left: int | float | None, right: int | float | None) -> int | float | None:
228
+ return None if left is None or right is None else left + right
229
+
230
+ summary = {}
231
+ for suffix, key, default in (
232
+ ("TotalTokens", "totalTokens", None),
233
+ ("CacheReadTokens", "cacheReadTokens", 0),
234
+ ("BillableEquivalentTokens", "billableEquivalentTokens", None),
235
+ ):
236
+ lead_value = _complete_usage_total([lead], key, default=default)
237
+ worker_value = _complete_usage_total(workers, key, default=default)
238
+ summary.update({f"lead{suffix}": lead_value, f"worker{suffix}": worker_value,
239
+ f"grand{suffix}": combine(lead_value, worker_value)})
240
+ lead_cost_key = "estimatedCostUsd"
241
+ if lead.get(lead_cost_key) is None and "cliEstimatedCostUsd" in lead:
242
+ lead_cost_key = "cliEstimatedCostUsd"
243
+ lead_cost = _complete_usage_total([lead], lead_cost_key)
244
+ # A native CLI block has no Claude-side charge; its provider charge has its own row.
245
+ host_blocks = [block for block in workers if not (
246
+ str(block.get("source", "")).endswith("-cli") and "estimatedCostUsd" not in block
247
+ )]
248
+ cli_blocks = [row.get("usage") or {} for row in rows if cli_usage_required(row)]
249
+ worker_cost = _complete_usage_total(host_blocks, "estimatedCostUsd")
250
+ cli_cost = _complete_usage_total(cli_blocks, "cliEstimatedCostUsd")
251
+ costs = {
252
+ "lead": lead_cost, "claudeWorkers": worker_cost, "cliWorkers": cli_cost,
253
+ }
254
+ summary["estimatedCostUsd"] = {key: None if value is None else round(value, 4) for key, value in costs.items()}
255
+ return summary
256
+
257
+
258
+ def project_token_usage(team_state: Mapping[str, Any], *, usage_policy: str = "strict") -> dict[str, Any]:
215
259
  """팀 상태의 사용량 합계를 리포트 표 구조로 반환한다."""
216
260
  summary = team_state.get("usageSummary")
217
261
  summary = summary if isinstance(summary, Mapping) else {}
262
+ if usage_accounting_policy({"usageAccountingPolicy": usage_policy}) == "advisory":
263
+ summary = _advisory_usage_summary(team_state)
218
264
  costs = summary.get("estimatedCostUsd")
219
265
  costs = costs if isinstance(costs, Mapping) else {}
220
266
  lead_cost = costs.get("lead")