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
@@ -7,6 +7,7 @@ import sys
7
7
  from pathlib import Path
8
8
 
9
9
  from .collect import collect
10
+ from .policy import usage_accounting_policy, usage_diagnostics
10
11
  from .report import (
11
12
  SubstituteRefusedError,
12
13
  populate_token_cells,
@@ -93,6 +94,11 @@ def main() -> int:
93
94
 
94
95
  updated = collect(args.team_state, args.project_root,
95
96
  incremental=not args.no_cache)
97
+ advisory = usage_accounting_policy(updated) == "advisory"
98
+ if advisory:
99
+ _errors, missing = usage_diagnostics(updated)
100
+ for row in missing:
101
+ print(f"token-usage advisory: {row['item']} — {row['risk']}", file=sys.stderr)
96
102
 
97
103
  if args.write:
98
104
  args.team_state.write_text(
@@ -106,22 +112,22 @@ def main() -> int:
106
112
  s = updated.get("usageSummary") or {}
107
113
  cost = s.get("estimatedCostUsd") or {}
108
114
  print(
109
- f"raw: lead={s.get('leadTotalTokens', 0):,} "
110
- f"workers={s.get('workerTotalTokens', 0):,} "
111
- f"grand={s.get('grandTotalTokens', 0):,}",
115
+ f"raw: lead={_display(s.get('leadTotalTokens'), ',')} "
116
+ f"workers={_display(s.get('workerTotalTokens'), ',')} "
117
+ f"grand={_display(s.get('grandTotalTokens'), ',')}",
112
118
  file=sys.stderr,
113
119
  )
114
120
  print(
115
- f"billable-equiv: lead={s.get('leadBillableEquivalentTokens', 0):,} "
116
- f"workers={s.get('workerBillableEquivalentTokens', 0):,} "
117
- f"grand={s.get('grandBillableEquivalentTokens', 0):,}",
121
+ f"billable-equiv: lead={_display(s.get('leadBillableEquivalentTokens'), ',')} "
122
+ f"workers={_display(s.get('workerBillableEquivalentTokens'), ',')} "
123
+ f"grand={_display(s.get('grandBillableEquivalentTokens'), ',')}",
118
124
  file=sys.stderr,
119
125
  )
120
126
  print(
121
- f"cost USD: lead=${cost.get('lead', 0):.2f} "
122
- f"claude-workers=${cost.get('claudeWorkers', 0):.2f} "
123
- f"cli-workers=${cost.get('cliWorkers', 0):.2f} "
124
- f"grand=${cost.get('grandTotal', 0):.2f}",
127
+ f"cost USD: lead=${_display(cost.get('lead'), '.2f')} "
128
+ f"claude-workers=${_display(cost.get('claudeWorkers'), '.2f')} "
129
+ f"cli-workers=${_display(cost.get('cliWorkers'), '.2f')} "
130
+ f"grand=${_display(cost.get('grandTotal'), '.2f')}",
125
131
  file=sys.stderr,
126
132
  )
127
133
  print(
@@ -131,6 +137,9 @@ def main() -> int:
131
137
  )
132
138
 
133
139
  if args.substitute_data is not None:
140
+ if advisory:
141
+ print("token-usage advisory: published report preserved; recollection is stored only in team-state.", file=sys.stderr)
142
+ return 0
134
143
  try:
135
144
  cells_changed = populate_token_cells(
136
145
  args.substitute_data,
@@ -151,5 +160,9 @@ def main() -> int:
151
160
  return 0
152
161
 
153
162
 
163
+ def _display(value: object, spec: str) -> str:
164
+ return format(value, spec) if isinstance(value, (int, float)) else "unavailable"
165
+
166
+
154
167
  if __name__ == "__main__":
155
168
  sys.exit(main())
@@ -9,7 +9,13 @@ from pathlib import Path
9
9
  from typing import Any
10
10
  from okstra_project.dirs import OKSTRA_RELATIVE
11
11
 
12
- from .blocks import accounting_workers, na_block, usage_block
12
+ from .blocks import (
13
+ SESSION_JSONL_PROVIDERS as _SESSION_JSONL_PROVIDERS,
14
+ accounting_workers,
15
+ cli_assignment_provider as _cli_assignment_provider,
16
+ na_block,
17
+ usage_block,
18
+ )
13
19
  from .claude import (
14
20
  claude_code_status_total,
15
21
  claude_session_totals,
@@ -38,6 +44,7 @@ from .grok import (
38
44
  )
39
45
  from .paths import claude_project_dir, find_session_jsonl, utc_now
40
46
  from .pricing import antigravity_cost_usd, provider_billable_equivalent, provider_cost_usd
47
+ from .policy import manifest_for_usage, usage_accounting_policy, usage_diagnostics
41
48
  from okstra_ctl.usage_identity import (
42
49
  unrostered_usage_workers,
43
50
  usage_dispatch_records,
@@ -602,26 +609,6 @@ def _codex_worker_windows(project_root: Path, state: dict) -> dict[str, list[tup
602
609
  return windows
603
610
 
604
611
 
605
- # Claude 의 트랜스크립트는 세션 jsonl 이고, 그것은 이 모듈의 Claude 경로가
606
- # 읽는다. 별도의 CLI 트랜스크립트가 없으므로 CLI 경로에 태우면 매번
607
- # `no transcript was found` 가 붙는다 — 세션을 찾아 토큰을 붙인 행에도.
608
- _SESSION_JSONL_PROVIDERS = frozenset({"claude"})
609
-
610
-
611
- def _cli_assignment_provider(worker: dict) -> str:
612
- worker_id = str(worker.get("workerId") or "").strip()
613
- explicit_provider = str(worker.get("provider") or "").strip()
614
- provider = explicit_provider or str(worker.get("agent") or "").strip()
615
- if provider in _SESSION_JSONL_PROVIDERS:
616
- return ""
617
- runner = str(worker.get("runner") or "").strip()
618
- if runner and runner != "cli-wrapper":
619
- return ""
620
- if not explicit_provider and worker_id == "report-writer":
621
- provider = "codex"
622
- return provider if provider in provider_wrappers() else ""
623
-
624
-
625
612
  def _cli_sessions_for_windows(
626
613
  provider: str,
627
614
  project_root: Path,
@@ -1139,6 +1126,9 @@ def _attach_cli_usage(block: dict, cli: dict) -> None:
1139
1126
  "cliSessionPaths",
1140
1127
  "cliNote",
1141
1128
  "cliExecutionStatus",
1129
+ "requestedSessionIds",
1130
+ "missingSessionIds",
1131
+ "unattributedCliSessionPaths",
1142
1132
  ):
1143
1133
  if key in cli:
1144
1134
  block[key] = cli[key]
@@ -1723,16 +1713,29 @@ def collect(
1723
1713
  project_root: Path | None = None,
1724
1714
  *,
1725
1715
  incremental: bool = True,
1716
+ manifest: dict | None = None,
1726
1717
  ) -> dict:
1727
1718
  from okstra_ctl.application.collect_usage import collect_usage
1728
1719
  from okstra_ctl.ports.usage_accounting import UsageRequest
1729
1720
  from okstra_ctl.registry.host_registry import default_host_registry
1730
1721
 
1731
1722
  state = json.loads(team_state_path.read_text())
1723
+ run_manifest = manifest if manifest is not None else manifest_for_usage(team_state_path, state=state)
1724
+ if not run_manifest and "usageAccountingPolicy" in state:
1725
+ raise ValueError(f"run manifest not found for {team_state_path}")
1726
+ policy = usage_accounting_policy(run_manifest)
1727
+ if "usageAccountingPolicy" in state and state["usageAccountingPolicy"] != policy:
1728
+ raise ValueError("team-state usageAccountingPolicy does not match its run manifest")
1732
1729
  cwd = project_root or _infer_project_root(team_state_path, state)
1733
1730
  adapter = default_host_registry().resolve(str(state.get("leadRuntime") or ""))
1734
1731
  request = UsageRequest(team_state_path, cwd, incremental)
1735
- return collect_usage(request, adapter.usage_accounting()).payload
1732
+ updated = collect_usage(request, adapter.usage_accounting()).payload
1733
+ if policy == "advisory":
1734
+ updated["usageAccountingPolicy"] = policy
1735
+ errors, _missing = usage_diagnostics(updated)
1736
+ if errors:
1737
+ raise ValueError("; ".join(errors))
1738
+ return updated
1736
1739
 
1737
1740
 
1738
1741
  def _infer_project_root(team_state_path: Path, state: dict) -> Path:
@@ -0,0 +1,193 @@
1
+ """Usage policy and diagnostics shared by collection and report validation."""
2
+ from __future__ import annotations
3
+
4
+ import warnings
5
+ from collections.abc import Mapping
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from okstra_ctl.json_boundary import JsonBoundaryError, load_owned_object
10
+
11
+ from .blocks import (
12
+ cli_usage_required,
13
+ finite_non_negative,
14
+ usage_is_measured_zero,
15
+ usage_participants,
16
+ )
17
+
18
+
19
+ def usage_accounting_policy(manifest: Mapping[str, Any]) -> str:
20
+ policy = manifest.get("usageAccountingPolicy", "strict")
21
+ if policy not in ("strict", "advisory"):
22
+ raise ValueError(f"unknown usageAccountingPolicy: {policy!r}")
23
+ return policy
24
+
25
+
26
+ def _usage_path(raw: str, project_root: object, team_state_path: Path) -> Path | None:
27
+ candidate = Path(raw)
28
+ if not candidate.parts:
29
+ return None
30
+ if candidate.is_absolute():
31
+ return candidate.resolve()
32
+ if isinstance(project_root, str) and Path(project_root).is_absolute():
33
+ return (Path(project_root) / candidate).resolve()
34
+ if candidate.parts[0] in ("state", "manifests"):
35
+ return (team_state_path.parent.parent / candidate).resolve()
36
+ artifact_home = next((parent for parent in team_state_path.parents if parent.name == ".okstra"), None)
37
+ if artifact_home is not None and candidate.parts[0] == ".okstra":
38
+ return (artifact_home.parent / candidate).resolve()
39
+ return None
40
+
41
+
42
+ def manifest_for_usage(team_state_path: Path, *, state: Mapping[str, Any] | None = None) -> Mapping[str, Any]:
43
+ """Resolve the run by its recorded team-state path, including legacy names."""
44
+ manifests = team_state_path.parent.parent / "manifests"
45
+ recorded_manifest = (state or {}).get("runManifestPath")
46
+ if isinstance(recorded_manifest, str) and recorded_manifest.strip():
47
+ path = _usage_path(recorded_manifest, (state or {}).get("projectRoot"), team_state_path)
48
+ if path is None or path.parent != manifests.resolve():
49
+ raise ValueError(f"run manifest is outside the team-state run: {recorded_manifest}")
50
+ manifest = load_owned_object(path, artifact="run manifest")
51
+ recorded = manifest.get("teamStatePath")
52
+ if not isinstance(recorded, str) or not recorded.strip() or _usage_path(
53
+ recorded, manifest.get("projectRoot"), team_state_path,
54
+ ) != team_state_path.resolve():
55
+ raise ValueError(f"run manifest does not reference {team_state_path}")
56
+ return manifest
57
+ matches = []
58
+ paths = sorted(manifests.glob("run-manifest-*.json"))
59
+ if (manifests / "run.json").is_file():
60
+ paths.append(manifests / "run.json")
61
+ for path in paths:
62
+ try:
63
+ manifest = load_owned_object(path, artifact="run manifest")
64
+ except JsonBoundaryError as exc:
65
+ expected = "run-manifest-" + team_state_path.name.removeprefix("team-state-")
66
+ if path.name == expected:
67
+ raise
68
+ warnings.warn(f"Unreadable manifest skipped while resolving usage policy: {exc}", RuntimeWarning)
69
+ continue
70
+ recorded = manifest.get("teamStatePath")
71
+ if not isinstance(recorded, str) or not recorded.strip():
72
+ continue
73
+ if _usage_path(recorded, manifest.get("projectRoot"), team_state_path) == team_state_path.resolve():
74
+ matches.append(manifest)
75
+ if len(matches) > 1:
76
+ raise ValueError(f"multiple run manifests reference {team_state_path}")
77
+ if matches:
78
+ return matches[0]
79
+ return {}
80
+
81
+
82
+ def usage_diagnostics(team_state: Mapping[str, Any]) -> tuple[list[str], list[dict[str, str]]]:
83
+ """Separate observed absence from malformed or ambiguous accounting."""
84
+ errors = []
85
+ for key in ("workers", "additionalWorkerUsage"):
86
+ if key not in team_state:
87
+ continue
88
+ rows = team_state[key]
89
+ if not isinstance(rows, list):
90
+ errors.append(f"team-state.{key} must be a list.")
91
+ continue
92
+ for index, row in enumerate(rows):
93
+ if not isinstance(row, Mapping):
94
+ errors.append(f"team-state.{key}[{index}] must be an object.")
95
+ if errors:
96
+ return errors, []
97
+ summary = team_state.get("usageSummary")
98
+ errors = _summary_errors(summary)
99
+ missing: list[dict[str, str]] = []
100
+ lead_usage = team_state.get("leadUsage")
101
+ entries = [("leadUsage", lead_usage, cli_usage_required({"usage": lead_usage}))]
102
+ entries.extend(
103
+ (f"worker {worker.get('role') or worker.get('workerId') or '<unknown>'}", worker.get("usage"),
104
+ cli_usage_required(worker))
105
+ for worker in usage_participants(team_state)
106
+ )
107
+ if isinstance(summary, Mapping) and isinstance(summary.get("unattributedWorkerUsage"), Mapping):
108
+ entries.append(("unattributed worker usage", summary["unattributedWorkerUsage"], False))
109
+ for target, usage, needs_cli in entries:
110
+ invalid, absent = _classify_usage(target, usage, needs_cli)
111
+ errors.extend(invalid)
112
+ missing.extend(absent)
113
+ return errors, missing
114
+
115
+
116
+ def _summary_errors(summary: object) -> list[str]:
117
+ errors = []
118
+ if (not isinstance(summary, Mapping) or not isinstance(summary.get("collectedAt"), str)
119
+ or not summary["collectedAt"].strip()):
120
+ errors.append("team-state.usageSummary.collectedAt is missing — usage collection was skipped.")
121
+ if not isinstance(summary, Mapping):
122
+ return errors
123
+ for key in ("leadTotalTokens", "workerTotalTokens", "grandTotalTokens",
124
+ "leadCacheReadTokens", "workerCacheReadTokens", "grandCacheReadTokens",
125
+ "leadBillableEquivalentTokens", "workerBillableEquivalentTokens", "grandBillableEquivalentTokens"):
126
+ value = summary.get(key)
127
+ if value is not None and not finite_non_negative(value):
128
+ errors.append(f"usageSummary.{key} must be null or a finite non-negative number.")
129
+ costs = summary.get("estimatedCostUsd")
130
+ if isinstance(costs, Mapping):
131
+ for key in ("lead", "claudeWorkers", "cliWorkers", "grandTotal"):
132
+ if costs.get(key) is not None and not finite_non_negative(costs[key]):
133
+ errors.append(f"usageSummary.estimatedCostUsd.{key} must be null or a finite non-negative number.")
134
+ elif "estimatedCostUsd" in summary:
135
+ errors.append("usageSummary.estimatedCostUsd must be an object.")
136
+ if summary.get("unattributedTeamSessions") or summary.get("unattributedWorkerUsage"):
137
+ errors.append("team-state usage attribution is ambiguous for unassigned worker sessions.")
138
+ return errors
139
+
140
+
141
+ def _classify_usage(target: str, usage: object, needs_cli: bool) -> tuple[list[str], list[dict[str, str]]]:
142
+ errors = []
143
+ missing = []
144
+ if (not isinstance(usage, Mapping) or not isinstance(usage.get("source"), str)
145
+ or not usage["source"].strip()):
146
+ return [f"{target}: usage source is missing or malformed."], missing
147
+ if not isinstance(usage.get("collectedAt"), str) or not usage["collectedAt"].strip():
148
+ return [f"{target}: usage collectedAt is missing."], missing
149
+ if any(key in usage and (not isinstance(usage[key], str) or not usage[key].strip()) for key in ("note", "cliNote")):
150
+ return [f"{target}: usage notes must be non-empty strings."], missing
151
+ if usage.get("attribution") == "ambiguous" or usage.get("unattributedCliSessionPaths"):
152
+ return [f"{target}: CLI session attribution is ambiguous."], missing
153
+ unavailable = usage["source"] == "unavailable"
154
+ for key in ("totalTokens", "cliTotalTokens", "estimatedCostUsd", "cliEstimatedCostUsd", "billableEquivalentTokens", "cacheReadTokens"):
155
+ value = usage.get(key)
156
+ if value is None and (key != "totalTokens" or unavailable):
157
+ continue
158
+ if not finite_non_negative(value):
159
+ errors.append(f"{target}: {key} must be a finite non-negative number.")
160
+ session_ids = usage.get("missingSessionIds", [])
161
+ if not isinstance(session_ids, list) or any(not isinstance(item, str) or not item.strip() for item in session_ids):
162
+ errors.append(f"{target}: missingSessionIds must be an array of non-empty session IDs.")
163
+ if errors:
164
+ return errors, missing
165
+
166
+ def absent(item: str, reason: str) -> None:
167
+ missing.append({"item": item, "risk": reason, "owner": "Okstra lead", "source": "token-usage"})
168
+
169
+ if unavailable:
170
+ note = usage.get("note")
171
+ if not isinstance(note, str) or not note.strip():
172
+ errors.append(f"{target}: unavailable usage has no recorded reason.")
173
+ else:
174
+ absent(target, note + (f" Missing session IDs: {', '.join(session_ids)}." if session_ids else ""))
175
+ return errors, missing
176
+ if session_ids:
177
+ absent(f"{target} sessions", f"Session usage is partial; no transcript was found for session IDs: {', '.join(session_ids)}.")
178
+ if needs_cli and usage.get("cliTotalTokens") is None:
179
+ note = usage.get("cliNote")
180
+ if not isinstance(note, str) or not note.strip():
181
+ errors.append(f"{target}: missing CLI usage has no recorded reason.")
182
+ else:
183
+ absent(f"{target} CLI usage", note)
184
+ host_cost_applies = not usage["source"].endswith("-cli") or "estimatedCostUsd" in usage
185
+ measured_zero = usage_is_measured_zero(usage)
186
+ if host_cost_applies and usage.get("estimatedCostUsd") is None and not measured_zero:
187
+ absent(f"{target} billing cost", "Billing cost is unavailable for the recorded host usage/model.")
188
+ if (needs_cli and usage.get("cliTotalTokens") is not None and usage.get("cliEstimatedCostUsd") is None
189
+ and not usage_is_measured_zero(usage, cli=True)):
190
+ absent(f"{target} CLI billing cost", usage.get("cliNote") or "CLI billing cost is unavailable for the recorded usage/model.")
191
+ if not measured_zero and usage.get("billableEquivalentTokens") is None:
192
+ absent(f"{target} billable token equivalent", "Billable token equivalence is unavailable for the recorded usage/model.")
193
+ return errors, missing
@@ -749,6 +749,9 @@
749
749
  "host_runtime": {
750
750
  "type": "string",
751
751
  "minLength": 1
752
+ },
753
+ "project_group": {
754
+ "type": "string"
752
755
  }
753
756
  }
754
757
  },
@@ -7,7 +7,7 @@
7
7
  "schemaVersion": {"type": "integer", "const": 1},
8
8
  "autoRegister": {"type": "boolean"},
9
9
  "scope": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/text"}]},
10
- "sources": {"type": "array", "uniqueItems": true, "items": {"enum": ["memory", "manager", "task"]}},
10
+ "sources": {"type": "array", "uniqueItems": true, "items": {"enum": ["memory", "manager", "task", "business"]}},
11
11
  "includeProjects": {"$ref": "#/$defs/names"},
12
12
  "excludeProjects": {"$ref": "#/$defs/names"},
13
13
  "includeGroups": {"$ref": "#/$defs/names"},
@@ -41,7 +41,7 @@
41
41
  "minLength": 1
42
42
  },
43
43
  "format": {
44
- "const": "report-narrative-v3.0"
44
+ "enum": ["report-narrative-v3.0", "json-v1"]
45
45
  },
46
46
  "sourcePolicy": {
47
47
  "const": "read-only-synthesis-packet"
@@ -1,6 +1,6 @@
1
1
  ## Step 4: The confirm step's question text is the selection summary
2
2
 
3
- When `next.step == "confirm"`, the prompt's `label` already carries the full selection summary (`선택 확인:` followed by one line per resolved input — task-type, task-key, brief, base-ref, worktree, every role slot, directive, related-tasks, clarification, stage, …) and ends with the question. Render that `label` **verbatim, every line, as the question text** of the `confirm` picker (Proceed / Edit / Abort) — the same way you render any other pick step's label. Do not re-author it as a table, do not summarise it into prose, do not drop a line because its value is `(none)`: the user confirms what is on screen, and a line you left out is a setting they never saw (observed: a lead's own table omitted `directive`, `base-ref` and `brief`). Render the picker **as the final output of that turn** — emit nothing after the picker call.
3
+ When `next.step == "confirm"`, the prompt's `label` already carries the full selection summary (`선택 확인:` followed by one line per resolved input — task-type, task-key, brief, base-ref, worktree, every role slot, directive, related-tasks, clarification, stage, …) and ends with the question. Render that `label` **verbatim, every line, as the question text** of the `confirm` picker (Proceed / Edit / Abort) — the same way you render any other pick step's label. Do not re-author it as a table, do not summarise it into prose, do not drop a line because its value is `(none)`: the user confirms what is on screen, and a line you left out is a setting they never saw. Render the picker **as the final output of that turn** — emit nothing after the picker call.
4
4
 
5
5
  `okstra wizard confirmation --state-file <path>` returns the same block as `{ok: true, text: ...}` for a text-only host or when the user asks to see the summary again; it is not a substitute for the label.
6
6
 
@@ -12,7 +12,7 @@ Run one shell-command tool call (Shell invocation rule from the top of this file
12
12
  okstra preflight --runtime <host-runtime>
13
13
  ```
14
14
 
15
- Read the fixed text lines. If the first line is `Okstra preflight: failed`, show `Runtime readiness` and every repeated `Readiness check`, `Readiness check status`, and `Readiness check action`, then stop before Step 2. Show `Reason` and `Recovery` for every failure. Do not relabel a host login, license, daemon, trust, or other readiness failure as missing Okstra setup. If the call fails with `unknown command: preflight`, the `okstra` binary on PATH predates this skill — tell the user to update it (`npm i -g okstra@latest`), then stop (`/okstra-setup` does not update the binary). Do **not** try to invoke `npx -y okstra@latest ...` as a fallback — `npx` is not on the literal-token allow-list and will force a confirmation prompt on every wizard call afterward. Every subsequent `okstra <subcmd>` call self-bootstraps its Python path, so never `export PYTHONPATH=...`.
15
+ Read the fixed text lines. If the first line is `Okstra preflight: failed`, show `Runtime readiness` and every repeated `Readiness check`, `Readiness check status`, and `Readiness check action`, then stop before Step 2. Show `Reason` and `Recovery` for every failure. Do not relabel a host login, license, daemon, trust, or other readiness failure as missing Okstra setup. If the call fails with `unknown command: preflight`, the `okstra` binary on PATH predates this skill — tell the user to update it (`npm i -g okstra@latest`), then stop (`/okstra-setup` does not update the binary). Do **not** try to invoke `npx -y okstra@latest ...` as a fallback — every later wizard call still invokes the stale `okstra` on PATH, so an `npx` call does not recover the run. Every subsequent `okstra <subcmd>` call self-bootstraps its Python path, so never `export PYTHONPATH=...`.
16
16
 
17
17
  On `Okstra preflight: ready`, require `Runtime readiness: ready` before Step 2. These checks come from the selected host adapter and are independent of worker-provider choices. Any other readiness value is unrecognized runtime output: show it and stop before Step 2 instead of guessing that the host is ready.
18
18
 
@@ -8,15 +8,13 @@ Repeat until `next.kind == "done"` (or `"aborted"` — terminal cancel, see "How
8
8
  ```
9
9
  If the answer contains spaces or shell metacharacters, wrap it in double quotes around the literal string only — never inside `"$VAR"`.
10
10
 
11
- **MANDATORY: empty answers must pass `--answer ""` explicitly.** If the user's reply is the empty string, the call MUST still include the flag with an empty literal value:
11
+ Pass `--answer` even when the user's reply is empty:
12
12
  ```bash
13
13
  okstra wizard step --state-file /var/folders/.../okstra-wizard.AbCd.json --answer ""
14
14
  ```
15
- Omitting `--answer` entirely is forbidden. The wizard does not read a missing `--answer` flag as "submit empty": without `--answer` or `--no-submit`, `wizard step` returns `ok: false` naming `--answer` and exits 2, and the step is not submitted. Submitting `--answer ""` is the only way to advance past an intentionally-blank step (e.g. "use phase default").
15
+ Without `--answer` or `--no-submit`, `wizard step` returns `ok: false` naming `--answer`, exits 2 and submits nothing, so `--answer ""` is the only way past an intentionally blank step (e.g. "use phase default"). If the literal answer contains `"`, escape each occurrence as `\"` inside the double-quoted argument.
16
16
 
17
- **Escaping rule**: if the literal answer contains `"`, escape each occurrence as `\"` inside the double-quoted argument. Empty values must still be `--answer ""` — the flag itself is mandatory, even when the value is empty.
18
-
19
- **Enforced:** `tests-js/wizard.test.mjs` pins `parseFlags` on the empty literal (`--answer=` parses to the empty string, a value beginning with `--` is kept) and on the `--no-submit` peek that is the only sanctioned way to see the current prompt without submitting; the Node wrapper (`src/commands/execute/wizard.mts`) is what forwards them to Python.
17
+ **Not enforced:** no test pins the empty-literal parsing or the `--no-submit` peek; the Node wrapper (`src/commands/execute/wizard.mts`) forwards both flags to Python.
20
18
  3. **Handle result**:
21
19
  - `ok: true` → echo `result.echo` to the user on one short line, then loop with `result.next`.
22
20
  - `ok: false` → show `result.error` to the user verbatim, then loop with `result.current` (re-prompt the same step). If `result.current` is `null`, do not loop — the current step cannot render (e.g. corrupt Stage Map); surface the error and stop so the user fixes the plan.
@@ -35,6 +35,6 @@ Submit the answer shape required by `interaction.answerProtocol`; do not add nor
35
35
 
36
36
  The final `confirm` step is a normal `pick` step with three options — `Proceed` / `Edit` / `Abort`(abort) — and is rendered the same way (no special handling). `Edit` rewinds to any earlier step (including `base-ref`); `Abort` terminally cancels the wizard. The branch/worktree decision the run will actually use (for `implementation`, the **stage worktree** — not the task-key directory) is folded into the Step 4 confirmation summary block as a `worktree` line, so there is no separate branch-confirm prompt.
37
37
 
38
- Never invent additional questions. **Never drop, hide, merge, reorder, or truncate** a `pick` / `pick_group` option — relay every `options[]` entry, including the flagged recommendation. Do not collapse a multi-option pick into a "recommended + Enter directly / Other" shortlist. The wizard's arrays are the complete authoritative choice sets, regardless of the current host UI's usual option limit. The run-prompt recommendation rule (1–2 recommendations + Enter directly) shapes the **option set** only for prompts this skill authors itself, never for wizard-provided options — you may not add, drop, or reorder a wizard option to produce a shortlist. It does not excuse you from recommending: before relaying a wizard step whose answer turns on something readable (the carried report, the sidecar the user already wrote, the prior Stage Map), read it, put what you found in the question body, and name which of the wizard's own options you recommend and why. Relaying a step with no context and no recommendation hands the whole question back to the user — see the lifecycle core contract "Asking the user (BLOCKING)".
38
+ Never invent additional questions. Relay every `pick` / `pick_group` option the wizard sends, in order, including the flagged recommendation: the wizard's arrays are the complete choice set whatever the host UI's usual option limit, and the run-prompt recommendation rule (1–2 recommendations + Enter directly) applies only to prompts this skill authors itself. It does not excuse you from recommending: before relaying a wizard step whose answer turns on something readable (the carried report, the sidecar the user already wrote, the prior Stage Map), read it, put what you found in the question body, and name which of the wizard's own options you recommend and why. Relaying a step with no context and no recommendation hands the whole question back to the user — see the lifecycle core contract "Asking the user (BLOCKING)".
39
39
 
40
40
  **One recommendation, shown in one place, and it is option 1.** Wizard labels carry no recommendation marker of their own. The option carrying `recommended: true` is what this run computed, and the wizard already placed it first — except on model-selection steps (`role-models:*`, `role-model:*`), which keep provider display order, so the flagged model may sit anywhere in the list. Append ` (추천)` to that option's label when you render it, and to no other. A checkbox step (`multi: true`) may flag several leading options: they are the recommended set, rendered the same way. Your prose recommendation names one of the flagged options. If you believe a different option is right, do not quietly recommend it in prose while the flagged one still reads as recommended on screen: say you disagree, name both, and let the user pick. When no option carries the flag, the run computed nothing for this step — recommend one from what you read and mark that one, and do not present the first option as a default just because it is first. **Enforced:** `scripts/okstra_ctl/wizard/state.py` `Prompt.__post_init__` refuses a step whose free-input option is not last, whose single-select recommendation is not exactly one option, whose recommendation is not placed first on a single-select step or is not the leading run on a checkbox step (both position checks are skipped on `role-models:*` / `role-model:*` steps), or that marks the free-input / abort escape as a recommendation.
@@ -6,51 +6,35 @@ When `next.kind == "done"`, fetch the public wizard outcome:
6
6
  okstra wizard outcome --state-file /var/folders/.../okstra-wizard.AbCd.json
7
7
  ```
8
8
 
9
- Output: `{ok: true, outcome: {renderArgv: ["--lead-runtime", "...", ...], renderArgs: {...}, orchestration: {chainStages: "..."}, persistActions: [...], confirmationText: "..."}}`.
9
+ Output: `{ok: true, outcome: {renderArgv: ["--lead-runtime", "...", ...], renderArgs: {...}, orchestration: {chainStages: "...", hostRulesPath: "..."}, persistActions: [...], confirmationText: "..."}}`.
10
10
 
11
- `renderArgv` is the canonical ordered `okstra render-bundle` argument list. Pass its tokens verbatim and in order. Repeated `--role-count` and `--role-model` flags are intentional. `renderArgs` is a compatibility and inspection view only; do not reconstruct an invocation from it. `orchestration` holds signals this skill acts on itself — never pass its entries to `render-bundle`.
11
+ Use the outcome to inspect the confirmed scope and `orchestration.chainStages`. `renderArgv` and `renderArgs` remain compatibility and inspection views; do not copy their tokens into a command. Bundle preparation reads the confirmed state file directly and preserves empty values and repeated role/model flags in code. `orchestration` holds signals this skill acts on itself — never pass its entries to `render-bundle`.
12
12
 
13
- `userAuthorization`, when present, preserves the confirmation prompt actually emitted by this wizard and the relayed `proceed` response. Its `--user-authorization-json` token carries that record into the run manifest; preserve it unchanged. Do not synthesize a receipt for older confirmed states. The record documents task scope; it does not grant host execution privileges.
13
+ Before the first `render-bundle` invocation, read `outcome.orchestration.hostRulesPath` verbatim when it is non-empty. The wizard selects and checks this absolute runtime path; it contains the selected task's waiver, recovery, and chaining rules needed even when preparation fails. An empty string means this task declares no host rules. Use the emitted path rather than constructing one from the task type.
14
14
 
15
- Before retrying a worker in an existing run, inspect its last invocation attempt: await running work; append an attempt only after `failed-no-mutation` within the retry budget. Preserve every other terminal attempt. `okstra team dispatch` routes the legacy declaration-only implementer failure to a separate same-model evidence-recovery invocation; collect its result before independent verification. Other terminal failures need `okstra agent-prompt materialize` with a new `--invocation-id`, distinct `--prompt`/`--result` paths, and unchanged assignment/model for a bounded correction. Do not restart completed implementation or request renewed approval for unchanged scope. Enforcement: `dispatch_core._next_attempt` and `execution_manifest._validate_next_attempt`.
16
-
17
- Run every `outcome.persistActions[]` entry BEFORE `render-bundle`. The only supported action is:
15
+ After successful preparation, use the frozen `instruction-set/host-orchestration-rules.md` identified by the rendered launch prompt for resumed work and stage chaining. Read that frozen copy within the run as the launch prompt requires: reading the canonical file before preparation does not satisfy the implementation session read gate. An already prepared legacy run without the new outcome field keeps its existing skill and prepared-instruction contract. If a fresh outcome omits `hostRulesPath` or its non-empty path cannot be read, stop and report a runtime/skill version mismatch; do not infer waiver or recovery rules.
18
16
 
19
- ```json
20
- {"command":"config.set","key":"pr-template-path","scope":"project|global","value":"<path>"}
21
- ```
17
+ `userAuthorization`, when present, preserves the confirmation prompt actually emitted by this wizard and the relayed `proceed` response. Preparation carries that record into the run manifest unchanged. Do not synthesize a receipt for older confirmed states. The record documents task scope; it does not grant host execution privileges.
22
18
 
23
- Execute the matching command for `scope`:
24
-
25
- ```bash
26
- okstra config set pr-template-path "<value>" --scope project
27
- okstra config set pr-template-path "<value>" --scope global
28
- ```
19
+ Before retrying a worker in an existing run, inspect its last invocation attempt: await running work; append an attempt only after `failed-no-mutation` within the retry budget. Preserve every other terminal attempt. `okstra team dispatch` routes the legacy declaration-only implementer failure to a separate same-model evidence-recovery invocation; collect its result before independent verification. Other terminal failures need `okstra agent-prompt materialize` with a new `--invocation-id`, distinct `--prompt`/`--result` paths, and unchanged assignment/model for a bounded correction. Do not restart completed implementation or request renewed approval for unchanged scope. Enforcement: `dispatch_core._next_attempt` and `execution_manifest._validate_next_attempt`.
29
20
 
30
- If an action has an unknown `command`, `key`, or `scope`, stop and report the wizard output instead of inventing a command.
21
+ `render-bundle --wizard-state-file` applies the confirmed PR-template save action before preparing the bundle. Do not execute `outcome.persistActions[]` separately. An unknown action, missing save authorization, or changed save scope stops preparation before settings are written. If an older confirmation did not record the save scope, reopen that confirmation rather than inventing a receipt. A settings write failure stops preparation; a later preparation failure reports that the successful settings write remains saved.
31
22
 
32
23
  Before rendering the next phase's bundle — and between worker rounds within a phase (reverify/critic/gapverify batches), after you have collected that round's results and token usage and before you dispatch the next round — close the panes of the dispatches that finished in the prior round so they do not accumulate: `okstra team reclaim --project-root <projectRoot> --run-manifest <RUN_MANIFEST_PATH>` closes them, records `phase-batch-cleanup panes=<n>` with the number it closed, and prints that `PROGRESS:` line last — emit it as printed and do not call `okstra lead-progress append` for it. The command reads each dispatch's recorded status, so an in-progress worker keeps its pane whichever moment you call it. It closes only the panes okstra opened and recorded — a pane the harness opened for its own teammate carries no recorded id and is not okstra's to close. After collecting results and token usage, apply the selected adapter's `shutdown_workers` operation only to confirmed-complete workers; preserve in-flight workers and the lead. A `cli-wrapper` run holds no pane at all and `team reclaim` refuses it, so record the checkpoint there with `okstra lead-progress append … --phase phase-batch-cleanup --field panes=0`.
33
24
 
34
25
  Before you ask the user for any approval, clarification, or decision after workers have been dispatched, run `okstra team reclaim … --gate` first: it closes the finished panes and prints `PROGRESS: phase-gate-cleanup panes=<n>` for you to emit, without recording a batch cleanup. Then apply the selected adapter's `shutdown_workers` operation to confirmed-complete workers after collecting their results and token usage; preserve in-flight workers and the lead. This keeps a user gate from being shown while finished worker panes remain; in-progress dispatches keep their panes. Then follow `prompts/lead/okstra-lead-contract.md` "User confirmation before an approval blocker": read cited plan items, worker findings, and files before asking, and ask in the user's language with each option's outcome.
35
26
 
36
- Build the `okstra render-bundle` invocation from `outcome.renderArgv`, passing every token verbatim and in order (including empty strings — they are intentional `use phase default` markers).
27
+ Prepare the bundle with the same literal absolute state-file path used by the wizard. Do not append scope inputs such as task type, role/model, directive, or lead runtime; the command rejects mixing those inputs with `--wizard-state-file`.
37
28
 
38
29
  Before invoking it, follow the active host relay's execution-permission guidance. For Codex, read "Permission before bundle preparation" in the relay already selected at preflight: bundle preparation can write protected Git metadata while creating a branch and worktree, even with `--render-only`. Apply this guidance to the first invocation and each subsequent phase or stage preparation.
39
30
 
40
- Analysis sidetracks therefore forward wizard-owned tokens such as `--analysis-target "<value>"` and `--evidence-inputs "<value>"` when they are present. These are examples of the verbatim token rule, not a separate hard-coded argument list.
41
-
42
- Step 3's empty-answer and escaping rules apply verbatim: every flag in `renderArgv` whose following value is the empty string MUST still be passed explicitly (e.g. `--related-tasks ""`, `--directive ""`) — the wizard's intent is always "flag present with empty value", even where prepare's default happens to be the same empty value.
43
-
44
- `renderArgv` already contains exactly one `--lead-runtime <host-runtime>` pair. Do not add or replace it. Do not enumerate a fixed provider list in this skill because the wizard and role model pool own the ordered tokens.
31
+ The only preparation additions are `--summary-only`, a stage in the confirmed implementation chain, and the existing separately user-confirmed `--tdd-bypass` / `--qa-waiver` exceptions under their host orchestration rules. Never infer an exception grant from the original wizard confirmation.
45
32
 
46
33
  ```bash
47
- okstra render-bundle --summary-only \
48
- <outcome.renderArgv token 1> \
49
- <outcome.renderArgv token 2> \
50
- <each remaining outcome.renderArgv token in order>
34
+ okstra render-bundle --wizard-state-file /var/folders/.../okstra-wizard.AbCd.json --summary-only
51
35
  ```
52
36
 
53
- `render-bundle` auto-supplies `--workspace-root` and forces `--render-only`. Stdout prints `okstra task root:`, `okstra instruction-set:`, `okstra run manifest:`, and other preparation status. `--summary-only` omits the lead prompt body from stdout; Step 6 reads the verified saved prompt from the manifest path. Parse the labelled lines for `TASK_ROOT`, `INSTRUCTION_SET_PATH`, and `RUN_MANIFEST_PATH`. Also watch for an optional `okstra concurrent-run stages:` label line — present only when a concurrent run is detected (see "Concurrent-run detection branch" below).
37
+ `render-bundle` auto-supplies `--workspace-root` and forces `--render-only`. Stdout prints `okstra task root:`, `okstra instruction-set:`, `okstra run manifest:`, and other preparation status. `--summary-only` omits the lead prompt body from stdout; Step 6 reads the verified saved prompt from the manifest path. Parse the labelled lines for `TASK_ROOT`, `INSTRUCTION_SET_PATH`, and `RUN_MANIFEST_PATH`. Also watch for an optional `okstra concurrent-run stages:` label line — present only when a concurrent run is detected (see "Concurrent-run detection branch" in the selected host rules).
54
38
 
55
39
  Before acting as the lead, read `resources.leadPromptMetadataPath` from the run
56
40
  manifest and execute the host-native specification-link gate:
@@ -69,6 +53,8 @@ it does not claim that the host exposed or attested the delivered prompt bytes.
69
53
 
70
54
  The python function underneath allocates the run sequence number and writes `run-context-*.json` under the per-task lock (`~/.okstra/.locks/<task-key>.lock`), then writes `run-inputs-*.json` + all manifests + discovery files outside that lock, and registers the run in `~/.okstra/recent.jsonl` with status `prepared` under the central `~/.okstra/.lock` (a registration failure is reported on stderr and does not fail prepare).
71
55
 
72
- **Not enforced:** `tests-js/wizard.test.mjs` pins the argv the wizard produces (`orderedRenderArgv` preserves the Python role selection bytes and repeated role order), not the argv you pass. Prepare's parser defaults most flags to `""` (e.g. `--directive`), so a dropped empty value is indistinguishable from its default and nothing rejects it — passing every token verbatim is on you.
56
+ Enforcement: `wizard.launch.load_confirmed_launch` validates the confirmed snapshot and save receipt; `render-bundle.prepareRenderBundle` preserves ordered inputs and rejects scope overrides before writes. `tests/wizard/test_launch.py` and `tests-js/render-bundle.test.mjs` cover these contracts. Host execution permission remains a separate host decision.
57
+
58
+ After successful preparation of a single run, delete the literal state-file path. For an implementation chain with multiple stages, keep it until preparation of the last confirmed stage succeeds. Do not delete it after a failed preparation. Invoke `command rm` with the literal path (e.g. `command rm /var/folders/.../okstra-wizard.AbCd.json`), not a shell variable. `command` keeps an interactive `rm` alias from blocking cleanup. The preparation code never deletes this file.
73
59
 
74
- You can delete the literal state-file path after this point — its job is done. Invoke `command rm` with the literal path (e.g. `command rm /var/folders/.../okstra-wizard.AbCd.json`), not a shell variable. `command` is what keeps a `rm='rm -i'` alias from turning this into a confirmation prompt nobody is there to answer.
60
+ If the file disappears before a remaining stage is prepared, stop that chain and report the completed and remaining stages. Reopen the wizard for the remaining scope; do not rebuild its inputs or approval receipt from a previous run. Already prepared runs resume from their run manifest without this file. After an interrupted or uncertain preparation, inspect the task's existing runs before retrying: this command does not promise exactly-once preparation.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: okstra-brief-gen
3
- description: Use when the user wants to generate a task brief file for okstra from a requirements document, an existing markdown file, an issue-tracker ticket (Linear / Jira / GitHub / Notion), a link URL, conversation context, or short user input. Produces the markdown brief consumed by `okstra-run` Step 5 (task-brief). Trigger words include "okstra brief", "make a brief", "generate a brief", "make a brief from requirements", "make an okstra input", "write a task brief", "brief from this ticket", "brief from this link".
3
+ description: Use when the user wants to generate a task brief file for okstra from a requirements document, an existing markdown file, an issue-tracker ticket (Linear / Jira / GitHub / Notion), a link URL, conversation context, or short user input. Produces the markdown brief consumed by `okstra-run` Step 5 (task-brief).
4
4
  disable-model-invocation: true
5
5
  ---
6
6
 
@@ -155,7 +155,7 @@ Use the current host's native single-select mapping with every listed option in
155
155
  ### Capture contract (binds every sub-flow below)
156
156
 
157
157
  `Source Material` is the one section a later phase can fall back to when a
158
- derived section reads wrong, so it carries the source whole. Three rules hold
158
+ derived section reads wrong, so it carries the source whole. Four rules hold
159
159
  for every variant and every source type below.
160
160
 
161
161
  1. **Capture in full.** Length is never a reason to excerpt, summarize, or
@@ -1031,7 +1031,7 @@ If the list is non-empty, run **one** `prompt_user`:
1031
1031
 
1032
1032
  When 6.5b answered "Yes — collect now", **read
1033
1033
  `references/reporter-confirmations.md` next to this SKILL.md and follow it**:
1034
- it defines the ≤ 4-question batching, the 12-question cap with
1034
+ it defines host-limited batching, the 12-question cap with
1035
1035
  `conversion-block:`-first priority, the `## Reporter Confirmations` RC-N
1036
1036
  record shape with `[CONFIRMED <date> → RC-N]` row markers and
1037
1037
  `> confirmed-by-reporter:` blockquote lines, and the final
@@ -1041,7 +1041,8 @@ record shape with `[CONFIRMED <date> → RC-N]` row markers and
1041
1041
  Step 6.5 ends here. The brief now has either zero pending reporter-only
1042
1042
  rows (`complete` / `partial` with remainder in the same file) or an
1043
1043
  explicit `skipped` signal that downstream phases consume per the
1044
- "Brief consumption" addendum in `_common-contract.md`.
1044
+ "Brief handoff contract" in `_common-contract.md` and each phase profile's
1045
+ "Brief consumption" addendum.
1045
1046
 
1046
1047
  ## Step 6.6: Self-validate before hand-off
1047
1048
 
@@ -1121,9 +1122,8 @@ Before printing the hand-off block, check whether
1121
1122
  file is the one document every task in the group shares — why the group
1122
1123
  exists, how its result is measured (with the denominator named), group-wide
1123
1124
  constraints, ticket relations — and no single brief can recover it
1124
- (observed: a 15-brief group whose reason, "the origin keeps going down under
1125
- attack traffic", appeared in none of them, so option selection measured a
1126
- per-page ratio instead of origin load). If the file is absent, ask once via
1125
+ (without it, the group's shared reason appears in no brief and option
1126
+ selection measures the wrong quantity). If the file is absent, ask once via
1127
1127
  `prompt_user`:
1128
1128
 
1129
1129
  - `Create the group context skeleton now (Recommended for a new task-group)`
@@ -53,7 +53,7 @@ brief's frontmatter `ticket-id` + `source-type`. Reseed precedence:
53
53
 
54
54
  1. On-disk frontmatter (`ticket-id` ≠ "") populates visited entries as
55
55
  `<source-type>:<ticket-id>` — these win.
56
- 2. Step 2c collision policy (`Skip` / `Append timestamp` / `Overwrite`) applies
56
+ 2. Step 2c collision policy (`Skip` / `Append suffix` / `Overwrite`) applies
57
57
  to any node whose path is already taken.
58
58
  3. The fresh in-memory walk fills any gaps for tickets not yet on disk.
59
59