okstra 0.232.0 → 0.233.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/README.md +19 -283
  2. package/dist/cli-registry.mjs +8 -1
  3. package/dist/cli-registry.mjs.map +1 -1
  4. package/dist/commands/execute/render-bundle.d.mts +6 -1
  5. package/dist/commands/execute/render-bundle.mjs +139 -32
  6. package/dist/commands/execute/render-bundle.mjs.map +1 -1
  7. package/dist/commands/lifecycle/config.mjs +6 -74
  8. package/dist/commands/lifecycle/config.mjs.map +1 -1
  9. package/dist/commands/trace/capacity.d.mts +12 -0
  10. package/dist/commands/trace/capacity.mjs +21 -0
  11. package/dist/commands/trace/capacity.mjs.map +1 -0
  12. package/dist/commands/trace/model.d.mts +89 -0
  13. package/dist/commands/trace/model.mjs +251 -0
  14. package/dist/commands/trace/model.mjs.map +1 -0
  15. package/dist/commands/trace/progression.d.mts +11 -0
  16. package/dist/commands/trace/progression.mjs +194 -0
  17. package/dist/commands/trace/progression.mjs.map +1 -0
  18. package/dist/commands/trace/review.d.mts +7 -0
  19. package/dist/commands/trace/review.mjs +51 -0
  20. package/dist/commands/trace/review.mjs.map +1 -0
  21. package/dist/commands/trace/task-link.d.mts +18 -0
  22. package/dist/commands/trace/task-link.mjs +72 -0
  23. package/dist/commands/trace/task-link.mjs.map +1 -0
  24. package/dist/commands/trace/trace.d.mts +1 -0
  25. package/dist/commands/trace/trace.mjs +293 -0
  26. package/dist/commands/trace/trace.mjs.map +1 -0
  27. package/dist/lib/bounded-file.d.mts +1 -0
  28. package/dist/lib/bounded-file.mjs +36 -0
  29. package/dist/lib/bounded-file.mjs.map +1 -0
  30. package/dist/lib/config-store.d.mts +34 -0
  31. package/dist/lib/config-store.mjs +70 -0
  32. package/dist/lib/config-store.mjs.map +1 -0
  33. package/dist/lib/file-lock.mjs +4 -5
  34. package/dist/lib/file-lock.mjs.map +1 -1
  35. package/dist/lib/input-limit.d.mts +4 -0
  36. package/dist/lib/input-limit.mjs +8 -0
  37. package/dist/lib/input-limit.mjs.map +1 -0
  38. package/dist/lib/memory-auto-register.mjs +2 -17
  39. package/dist/lib/memory-auto-register.mjs.map +1 -1
  40. package/dist/lib/report-language-tag.d.mts +1 -0
  41. package/dist/lib/report-language-tag.mjs +4 -0
  42. package/dist/lib/report-language-tag.mjs.map +1 -0
  43. package/dist/lib/report-language.d.mts +1 -0
  44. package/dist/lib/report-language.mjs +50 -0
  45. package/dist/lib/report-language.mjs.map +1 -0
  46. package/dist/lib/skill-catalog.mjs +3 -0
  47. package/dist/lib/skill-catalog.mjs.map +1 -1
  48. package/docs/architecture/storage-model.md +36 -5
  49. package/docs/architecture.md +10 -4
  50. package/docs/cli.md +279 -2
  51. package/docs/contributor-change-matrix.md +1 -2
  52. package/docs/project-structure-overview.md +31 -41
  53. package/package.json +1 -1
  54. package/runtime/BUILD.json +2 -2
  55. package/runtime/agents/operations/trace-interface-review.json +6 -0
  56. package/runtime/agents/operations/trace-scope-review.json +6 -0
  57. package/runtime/prompts/coding-preflight/authoring-checks.md +1 -1
  58. package/runtime/prompts/coding-preflight/clean-code.md +18 -20
  59. package/runtime/prompts/coding-preflight/overview.md +1 -1
  60. package/runtime/prompts/duties/code-reviewer.json +1 -1
  61. package/runtime/prompts/duties/interface-reviewer.json +32 -0
  62. package/runtime/prompts/host-orchestration/README.md +18 -9
  63. package/runtime/prompts/launch.template.md +3 -2
  64. package/runtime/prompts/lead/context-loader.md +2 -0
  65. package/runtime/prompts/lead/okstra-lead-contract.md +7 -7
  66. package/runtime/prompts/lead/report-writer.md +6 -6
  67. package/runtime/prompts/profiles/_coding-conventions-preflight.md +2 -2
  68. package/runtime/prompts/profiles/_common-contract.md +1 -1
  69. package/runtime/python/okstra_ctl/agent/invocation.py +1 -0
  70. package/runtime/python/okstra_ctl/agent/prompt_cli/cli.py +66 -26
  71. package/runtime/python/okstra_ctl/agent/prompt_cli/corrections.py +23 -8
  72. package/runtime/python/okstra_ctl/agent/prompt_cli/materialize.py +28 -10
  73. package/runtime/python/okstra_ctl/agent/prompt_cli/results.py +8 -11
  74. package/runtime/python/okstra_ctl/agent/standalone.py +12 -0
  75. package/runtime/python/okstra_ctl/analysis_packet.py +22 -11
  76. package/runtime/python/okstra_ctl/code_review_census.py +93 -2
  77. package/runtime/python/okstra_ctl/code_review_prepare.py +381 -0
  78. package/runtime/python/okstra_ctl/code_review_run.py +384 -0
  79. package/runtime/python/okstra_ctl/code_review_scope.py +13 -0
  80. package/runtime/python/okstra_ctl/code_review_supervisor.py +41 -0
  81. package/runtime/python/okstra_ctl/code_review_target.py +140 -15
  82. package/runtime/python/okstra_ctl/coverage_census.py +11 -2
  83. package/runtime/python/okstra_ctl/design_snapshot.py +16 -9
  84. package/runtime/python/okstra_ctl/direct_work.py +45 -3
  85. package/runtime/python/okstra_ctl/dispatch_core.py +31 -15
  86. package/runtime/python/okstra_ctl/dispatch_state.py +9 -2
  87. package/runtime/python/okstra_ctl/domain/role.py +1 -0
  88. package/runtime/python/okstra_ctl/doyouknow/sources/manager.py +48 -9
  89. package/runtime/python/okstra_ctl/final_report_schema.py +37 -34
  90. package/runtime/python/okstra_ctl/incremental_carry.py +6 -7
  91. package/runtime/python/okstra_ctl/initial_prompt_materialization.py +9 -2
  92. package/runtime/python/okstra_ctl/json_boundary.py +33 -6
  93. package/runtime/python/okstra_ctl/manager_cli.py +122 -1
  94. package/runtime/python/okstra_ctl/manager_journal.py +126 -0
  95. package/runtime/python/okstra_ctl/manager_launch.py +3 -3
  96. package/runtime/python/okstra_ctl/manager_log.py +221 -0
  97. package/runtime/python/okstra_ctl/manager_paths.py +8 -0
  98. package/runtime/python/okstra_ctl/manager_resume.py +59 -0
  99. package/runtime/python/okstra_ctl/manager_split.py +2 -2
  100. package/runtime/python/okstra_ctl/manager_store.py +116 -17
  101. package/runtime/python/okstra_ctl/manager_sync.py +42 -3
  102. package/runtime/python/okstra_ctl/manager_view.py +35 -2
  103. package/runtime/python/okstra_ctl/material.py +2 -0
  104. package/runtime/python/okstra_ctl/model_cli.py +64 -14
  105. package/runtime/python/okstra_ctl/model_defaults.py +22 -0
  106. package/runtime/python/okstra_ctl/model_io/renderers.py +3 -0
  107. package/runtime/python/okstra_ctl/operation_invocation.py +207 -28
  108. package/runtime/python/okstra_ctl/path_hints.py +14 -3
  109. package/runtime/python/okstra_ctl/paths.py +6 -1
  110. package/runtime/python/okstra_ctl/phases/catalog.py +24 -7
  111. package/runtime/python/okstra_ctl/phases/implementation/host-rules.md +3 -3
  112. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-diff-review.md +8 -6
  113. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-self-check.md +1 -1
  114. package/runtime/python/okstra_ctl/phases/implementation_option_selection/profile.md +1 -1
  115. package/runtime/python/okstra_ctl/phases/implementation_option_selection/votes.py +11 -11
  116. package/runtime/python/okstra_ctl/phases/implementation_planning/authoring.py +12 -9
  117. package/runtime/python/okstra_ctl/phases/implementation_planning/host-rules.md +3 -6
  118. package/runtime/python/okstra_ctl/phases/implementation_planning/instructions/plan-body-verification.md +12 -10
  119. package/runtime/python/okstra_ctl/phases/implementation_planning/profile.md +5 -5
  120. package/runtime/python/okstra_ctl/phases/improvement_discovery/lenses.py +12 -0
  121. package/runtime/python/okstra_ctl/phases/improvement_discovery/profile.md +7 -6
  122. package/runtime/python/okstra_ctl/phases/improvement_discovery/resolved_census.py +159 -0
  123. package/runtime/python/okstra_ctl/phases/improvement_discovery/spec.md +5 -2
  124. package/runtime/python/okstra_ctl/phases/improvement_discovery/validation.py +21 -7
  125. package/runtime/python/okstra_ctl/phases/release_handoff/boundary.json +1 -1
  126. package/runtime/python/okstra_ctl/phases/release_handoff/profile.md +4 -1
  127. package/runtime/python/okstra_ctl/plan_verify_cli.py +6 -4
  128. package/runtime/python/okstra_ctl/render.py +28 -2
  129. package/runtime/python/okstra_ctl/report_assembly.py +38 -11
  130. package/runtime/python/okstra_ctl/report_contract.py +26 -0
  131. package/runtime/python/okstra_ctl/report_corrections.py +36 -20
  132. package/runtime/python/okstra_ctl/report_inputs.py +1 -0
  133. package/runtime/python/okstra_ctl/report_language.py +4 -1
  134. package/runtime/python/okstra_ctl/report_narrative.py +179 -7
  135. package/runtime/python/okstra_ctl/report_projections.py +64 -18
  136. package/runtime/python/okstra_ctl/report_synthesis_packet.py +86 -36
  137. package/runtime/python/okstra_ctl/run.py +43 -35
  138. package/runtime/python/okstra_ctl/run_context.py +10 -1
  139. package/runtime/python/okstra_ctl/set_work_status.py +4 -15
  140. package/runtime/python/okstra_ctl/task_list_cli.py +34 -8
  141. package/runtime/python/okstra_ctl/task_query.py +239 -0
  142. package/runtime/python/okstra_ctl/trace_review.py +264 -0
  143. package/runtime/python/okstra_ctl/trace_tasks.py +197 -0
  144. package/runtime/python/okstra_ctl/user_authorization.py +14 -0
  145. package/runtime/python/okstra_ctl/wizard/confirmation.py +7 -3
  146. package/runtime/python/okstra_ctl/wizard/launch.py +52 -0
  147. package/runtime/python/okstra_ctl/wizard/launch_cli.py +39 -0
  148. package/runtime/python/okstra_ctl/wizard/outcome.py +17 -16
  149. package/runtime/python/okstra_ctl/wizard/registry.py +1 -1
  150. package/runtime/python/okstra_ctl/wizard/render.py +8 -0
  151. package/runtime/python/okstra_ctl/wizard/state.py +2 -1
  152. package/runtime/python/okstra_project/state.py +20 -0
  153. package/runtime/python/okstra_token_usage/blocks.py +74 -0
  154. package/runtime/python/okstra_token_usage/cli.py +23 -10
  155. package/runtime/python/okstra_token_usage/collect.py +25 -22
  156. package/runtime/python/okstra_token_usage/policy.py +193 -0
  157. package/runtime/schemas/report-synthesis-packet-v1.0.schema.json +1 -1
  158. package/runtime/skills/_fragments/wizard-confirm-step.md +1 -1
  159. package/runtime/skills/_fragments/wizard-preflight.md +1 -1
  160. package/runtime/skills/_fragments/wizard-prompt-loop.md +3 -5
  161. package/runtime/skills/_fragments/wizard-relay-protocol.md +1 -1
  162. package/runtime/skills/_fragments/wizard-render-bundle.md +15 -29
  163. package/runtime/skills/okstra-brief-gen/SKILL.md +7 -7
  164. package/runtime/skills/okstra-brief-gen/references/tracker-recursion.md +1 -1
  165. package/runtime/skills/okstra-code-review/SKILL.md +58 -50
  166. package/runtime/skills/okstra-code-review/references/census-rules.md +6 -6
  167. package/runtime/skills/okstra-code-review/references/review-calibration.md +8 -12
  168. package/runtime/skills/okstra-discussion/SKILL.md +22 -38
  169. package/runtime/skills/okstra-explain-flow/SKILL.md +6 -2
  170. package/runtime/skills/okstra-manager/SKILL.md +24 -0
  171. package/runtime/skills/okstra-memory/SKILL.md +1 -1
  172. package/runtime/skills/okstra-pr-gen/SKILL.md +1 -1
  173. package/runtime/skills/okstra-run/SKILL.md +55 -183
  174. package/runtime/skills/okstra-schedule-gen/SKILL.md +9 -13
  175. package/runtime/skills/okstra-setup/SKILL.md +3 -2
  176. package/runtime/skills/okstra-setup/references/project-config.md +2 -4
  177. package/runtime/skills/okstra-tdd/SKILL.md +187 -0
  178. package/runtime/skills/okstra-user-response/SKILL.md +4 -2
  179. package/runtime/templates/manager/view.template.html +4 -0
  180. package/runtime/templates/report-writer-prompt-preamble.md +15 -3
  181. package/runtime/templates/trace/trace.template.md +42 -0
  182. package/runtime/validators/checks/fixtures-02.py +25 -33
  183. package/runtime/validators/validate-run.py +93 -36
@@ -1,6 +1,7 @@
1
1
  """Read project-local okstra state into manager-owned snapshots."""
2
2
  from __future__ import annotations
3
3
 
4
+ import sys
4
5
  from datetime import datetime
5
6
  from pathlib import Path
6
7
 
@@ -11,8 +12,14 @@ from . import next_phase
11
12
  from .next_phase import STATUS_BLOCKED, STATUS_TERMINAL
12
13
  from .phases.discussion.overview import discussion_overview
13
14
  from .phases.discussion.store import DiscussionStore
14
- from .manager_paths import children_json_path, projects_json_path, snapshots_json_path, task_manifest_path
15
- from .manager_store import _now_iso, _read_json, _read_json_default, _write_json
15
+ from .manager_paths import (
16
+ children_json_path,
17
+ events_jsonl_path,
18
+ projects_json_path,
19
+ snapshots_json_path,
20
+ task_manifest_path,
21
+ )
22
+ from .manager_store import ManagerError, _now_iso, _read_json, _read_json_default, _write_json, record_event
16
23
 
17
24
 
18
25
  def _project_map(home: Path, manager_id: str) -> dict[str, dict]:
@@ -92,8 +99,34 @@ def _snapshot_child(project_root: Path, child: dict) -> dict:
92
99
  }
93
100
 
94
101
 
102
+ def _previous_buckets(path: Path) -> dict[str, str]:
103
+ try:
104
+ previous = _read_json_default(path, {})
105
+ except ManagerError:
106
+ print(f"okstra manager: previous snapshot is damaged; this sync replaces it and reports its "
107
+ f"children with from=null: {path}", file=sys.stderr)
108
+ previous = {}
109
+ return {
110
+ str(row.get("taskKey") or ""): summary_bucket(row)
111
+ for row in _list_field(previous, "children")
112
+ if isinstance(row, dict)
113
+ }
114
+
115
+
116
+ def _bucket_transitions(before: dict[str, str], rows: list[dict]) -> list[dict]:
117
+ transitions = []
118
+ for row in rows:
119
+ task_key = str(row.get("taskKey") or "")
120
+ bucket = summary_bucket(row)
121
+ if before.get(task_key) != bucket:
122
+ transitions.append({"taskKey": task_key, "from": before.get(task_key), "to": bucket})
123
+ return transitions
124
+
125
+
95
126
  def sync_task(home: Path, manager_id: str, task_group: str, task_id: str, *, now: str | None = None) -> dict:
96
127
  _read_json(task_manifest_path(home, manager_id, task_group, task_id))
128
+ snapshot_path = snapshots_json_path(home, manager_id, task_group, task_id)
129
+ before = _previous_buckets(snapshot_path)
97
130
  children = _read_json_default(children_json_path(home, manager_id, task_group, task_id), {"children": []})
98
131
  projects = _project_map(home, manager_id)
99
132
  rows = []
@@ -116,7 +149,13 @@ def sync_task(home: Path, manager_id: str, task_group: str, task_id: str, *, now
116
149
  "syncedAt": now or _now_iso(),
117
150
  "children": rows,
118
151
  }
119
- _write_json(snapshots_json_path(home, manager_id, task_group, task_id), payload)
152
+ _write_json(snapshot_path, payload)
153
+ transitions = _bucket_transitions(before, rows)
154
+ if transitions:
155
+ record_event(
156
+ events_jsonl_path(home, manager_id, task_group, task_id),
157
+ {"event": "task-synced", "createdAt": payload["syncedAt"], "transitions": transitions},
158
+ )
120
159
  return payload
121
160
 
122
161
 
@@ -1,7 +1,7 @@
1
1
  """manager 상태를 한 장짜리 HTML 로 그린다.
2
2
 
3
3
  manager 가 이미 저장한 파일(projects / task manifest / children / snapshots /
4
- directives / events)만 읽는다. 하위 프로젝트는 읽지 않는다 — 최신 상태가 필요하면
4
+ directives / events / journal)만 읽는다. 하위 프로젝트는 읽지 않는다 — 최신 상태가 필요하면
5
5
  먼저 `okstra manager task sync` 를 돌리고, 페이지는 각 task 의 마지막 sync 시각을
6
6
  보여 준다.
7
7
  """
@@ -15,6 +15,7 @@ from pathlib import Path
15
15
 
16
16
  from okstra_ctl.jsonl import read_jsonl
17
17
 
18
+ from .manager_log import MANAGER_EVENT, merge_activity
18
19
  from .manager_paths import directives_jsonl_path, events_jsonl_path, view_html_path
19
20
  from .manager_store import ManagerError, list_projects, list_tasks, load_manager
20
21
  from .manager_sync import status_task
@@ -192,17 +193,48 @@ def _directive_list(directives: list[dict]) -> str:
192
193
  return f'<ul class="plain">{items}</ul>'
193
194
 
194
195
 
196
+ def _event_detail(row: dict) -> str:
197
+ if row.get("event") == "task-synced":
198
+ return f" · child tasks changed: {len(row.get('transitions') or [])}"
199
+ if row.get("event") == "task-assigned":
200
+ return " · changed: " + _e(", ".join(sorted(row.get("changes") or {})))
201
+ return ""
202
+
203
+
195
204
  def _event_list(events: list[dict]) -> str:
196
205
  if not events:
197
206
  return '<p class="empty">No events.</p>'
198
207
  items = "".join(
199
208
  f"<li><code>{_e(row.get('createdAt'))}</code> {_e(row.get('event'))}"
200
- f"{' · ' + _e(row.get('taskKey')) if row.get('taskKey') else ''}</li>"
209
+ f"{' · ' + _e(row.get('taskKey')) if row.get('taskKey') else ''}{_event_detail(row)}</li>"
201
210
  for row in events
202
211
  )
203
212
  return f'<ul class="plain">{items}</ul>'
204
213
 
205
214
 
215
+ def _followup_list(entries: list[dict]) -> str:
216
+ if not entries:
217
+ return '<p class="empty">No open follow-ups.</p>'
218
+ items = "".join(
219
+ f"<li><code>{_e(entry['createdAt'])}</code> {_e(entry['row'].get('body'))}"
220
+ f"{' · ' + _e(entry['taskGroup'] + ' / ' + entry['taskId']) if entry['taskId'] else ''}"
221
+ f" <span class=\"meta\">{_e(entry['row'].get('id'))}</span></li>"
222
+ for entry in entries
223
+ )
224
+ return f'<ul class="plain">{items}</ul>'
225
+
226
+
227
+ def _activity_section(home: Path, manager_id: str) -> str:
228
+ """Open follow-ups oldest first, then manager-level events newest first."""
229
+ activity = merge_activity(home, manager_id)
230
+ followups = activity.open_followups_oldest_first()
231
+ events = [entry["row"] for entry in activity.entries if entry["origin"] == MANAGER_EVENT]
232
+ return (
233
+ f"<h3>Open follow-ups ({len(followups)})</h3>{_followup_list(followups)}"
234
+ f"<details><summary>Manager events ({len(events)})</summary>{_event_list(events)}</details>"
235
+ )
236
+
237
+
206
238
  def _task_panel(home: Path, manager_id: str, task: dict, status: dict, roots: dict[str, str]) -> str:
207
239
  group, task_id = task["taskGroup"], task["taskId"]
208
240
  synced_at = status["lastSnapshot"].get("syncedAt") or ""
@@ -265,6 +297,7 @@ def render_view(home: Path, manager_id: str, *, now: str | None = None) -> str:
265
297
  "TITLE": _e(f"Okstra manager · {manager.get('managerId') or manager_id}"),
266
298
  "META": meta,
267
299
  "SUMMARY": _summary_tiles(totals),
300
+ "ACTIVITY": _activity_section(home, manager_id),
268
301
  "PROJECTS": _projects_table(projects),
269
302
  "TASKS": "".join(panels) or '<p class="empty">No manager tasks.</p>',
270
303
  }
@@ -90,6 +90,8 @@ def direct_work_context(project_root: Path, task_key: str, related: list[str]) -
90
90
  f"- Summary: {' '.join(record['summary'].split())[:400]}",
91
91
  f"- Record: `{record_path}`", "",
92
92
  ])
93
+ if record.get("implementationTracePath"):
94
+ blocks.extend([f"- Implementation trace: `{record['implementationTracePath']}`", ""])
93
95
  if not blocks:
94
96
  return ""
95
97
  return "\n".join(["## Direct Work Context", "", *blocks])
@@ -66,26 +66,56 @@ def set_model_default(
66
66
  f"model {ref!r} cannot default role {canonical}: "
67
67
  f"{availability.reason}"
68
68
  )
69
- path = _config_path(scope, cwd)
70
- payload = _read_json(path)
71
- defaults = dict(payload.get("modelDefaults") or {})
72
- defaults[canonical] = list(refs)
73
- payload["modelDefaults"] = defaults
74
- _write_json_atomic(path, payload)
69
+ _update_config_section(scope, cwd, "modelDefaults", canonical, refs)
75
70
  return 0
76
71
 
77
72
 
78
73
  def unset_model_default(*, role: str, scope: str, cwd: Path) -> int:
79
- canonical = normalize_role(role)
80
- path = _config_path(scope, cwd)
81
- payload = _read_json(path)
82
- defaults = dict(payload.get("modelDefaults") or {})
83
- defaults.pop(canonical, None)
84
- payload["modelDefaults"] = defaults
85
- _write_json_atomic(path, payload)
74
+ _update_config_section(scope, cwd, "modelDefaults", normalize_role(role), None)
75
+ return 0
76
+
77
+
78
+ def set_operation_models(*, operation: str, refs: tuple[str, ...], scope: str, cwd: Path) -> int:
79
+ from .operation_invocation import operation_contract_root, resolve_operation_models
80
+
81
+ pool, _adapter = _pool_and_host("claude-code")
82
+ resolve_operation_models(operation, refs, contract_root=operation_contract_root(), pool=pool)
83
+ _update_config_section(scope, cwd, "operationModels", operation, refs)
84
+ return 0
85
+
86
+
87
+ def unset_operation_models(*, operation: str, scope: str, cwd: Path) -> int:
88
+ _update_config_section(scope, cwd, "operationModels", operation, None)
86
89
  return 0
87
90
 
88
91
 
92
+ def _update_config_section(
93
+ scope: str, cwd: Path, key: str, name: str, refs: tuple[str, ...] | None,
94
+ ) -> None:
95
+ """Set (`refs`) or remove (`None`) one entry of a model-list section.
96
+
97
+ The whole read-modify-write holds the config file's registry lock, so two
98
+ commands changing different entries cannot drop each other's change.
99
+ """
100
+ from okstra_project.dirs import json_lock_path, registry_lock
101
+
102
+ from .model_defaults import ModelDefaultError, parse_model_lists
103
+
104
+ path = _config_path(scope, cwd)
105
+ with registry_lock(json_lock_path(path)):
106
+ payload = _read_json(path)
107
+ try:
108
+ section = {entry: list(values) for entry, values in parse_model_lists(payload, key, path).items()}
109
+ except ModelDefaultError as exc:
110
+ raise ModelCliError(str(exc)) from exc
111
+ if refs is None:
112
+ section.pop(name, None)
113
+ else:
114
+ section[name] = list(refs)
115
+ payload[key] = section
116
+ _write_json_atomic(path, payload)
117
+
118
+
89
119
  def model_diagnostics(
90
120
  *,
91
121
  host_runtime: str = "claude-code",
@@ -238,10 +268,12 @@ _CLI_EPILOG = r"""Usage:
238
268
  okstra model list [--role <role>] [--host <host>] [--json]
239
269
  okstra model default set <role> <modelRef[,modelRef...]> --scope project|global [--cwd <dir>]
240
270
  okstra model default unset <role> --scope project|global [--cwd <dir>]
271
+ okstra model operation set <operation> <modelRef[,modelRef...]> --scope project|global [--cwd <dir>]
272
+ okstra model operation unset <operation> --scope project|global [--cwd <dir>]
241
273
 
242
274
  Listing and default writes never send an inference call.
243
275
  """
244
- _CLI_DESCRIPTION = "List catalog models and manage role defaults."
276
+ _CLI_DESCRIPTION = "List catalog models and manage role and operation model defaults."
245
277
 
246
278
 
247
279
  def main(argv: list[str] | None = None) -> int:
@@ -266,12 +298,30 @@ def main(argv: list[str] | None = None) -> int:
266
298
  unsetter.add_argument("role")
267
299
  unsetter.add_argument("--scope", choices=("project", "global"), required=True)
268
300
  unsetter.add_argument("--cwd", default=".")
301
+ operation = sub.add_parser("operation")
302
+ operation_sub = operation.add_subparsers(dest="operation_command", required=True)
303
+ operation_set = operation_sub.add_parser("set")
304
+ operation_set.add_argument("operation")
305
+ operation_set.add_argument("refs")
306
+ operation_set.add_argument("--scope", choices=("project", "global"), required=True)
307
+ operation_set.add_argument("--cwd", default=".")
308
+ operation_unset = operation_sub.add_parser("unset")
309
+ operation_unset.add_argument("operation")
310
+ operation_unset.add_argument("--scope", choices=("project", "global"), required=True)
311
+ operation_unset.add_argument("--cwd", default=".")
269
312
  args = parser.parse_args(argv)
270
313
  try:
271
314
  if args.command == "list":
272
315
  return list_models(
273
316
  role=args.role, host_runtime=args.host, as_json=args.json
274
317
  )
318
+ if args.command == "operation":
319
+ if args.operation_command == "set":
320
+ refs = tuple(part for part in args.refs.split(",") if part)
321
+ return set_operation_models(
322
+ operation=args.operation, refs=refs, scope=args.scope, cwd=Path(args.cwd)
323
+ )
324
+ return unset_operation_models(operation=args.operation, scope=args.scope, cwd=Path(args.cwd))
275
325
  if args.default_command == "set":
276
326
  refs = tuple(part for part in args.refs.split(",") if part)
277
327
  return set_model_default(
@@ -44,3 +44,25 @@ def default_scope(role: str, scopes: ModelDefaultScopes) -> str | None:
44
44
  if role in values:
45
45
  return scope_name
46
46
  return None
47
+
48
+
49
+ def parse_model_lists(payload: object, key: str, source: object) -> dict[str, tuple[str, ...]]:
50
+ """Read a config section mapping names to non-empty model-ref lists.
51
+
52
+ `modelDefaults` (role → refs) and `operationModels` (operation → refs)
53
+ share this shape; `source` names the file in error messages.
54
+ """
55
+ raw = payload.get(key, {}) if isinstance(payload, Mapping) else {}
56
+ if not isinstance(raw, Mapping):
57
+ raise ModelDefaultError(f"{key} must be an object: {source}")
58
+ lists: dict[str, tuple[str, ...]] = {}
59
+ for name, refs in raw.items():
60
+ if (
61
+ not isinstance(name, str)
62
+ or not isinstance(refs, list)
63
+ or not refs
64
+ or not all(isinstance(ref, str) and ref for ref in refs)
65
+ ):
66
+ raise ModelDefaultError(f"{key} entries must be non-empty string arrays: {source}")
67
+ lists[name] = tuple(refs)
68
+ return lists
@@ -23,6 +23,7 @@ from ..ports.verification_inputs import VerificationInputStore
23
23
  from ..review_policy import render_review_policy, review_policy_context
24
24
  from ..phases.catalog import PhaseAssetError, profile_markdown
25
25
  from ..recap import assemble_group_recap, assemble_recap
26
+ from ..report_contract import report_authoring_format
26
27
  from ..role_requirements import RoleProfileError, load_role_profile
27
28
  from ..timeline_runs import current_run_facts
28
29
  from .lines import (
@@ -214,6 +215,7 @@ def render_run_input(run_manifest: Path) -> str:
214
215
  + _line("Task type", run.get("taskType"))
215
216
  + _line("Run ID", run.get("runDateTimeSegment"))
216
217
  + _line("Work category", run.get("workCategory"))
218
+ + _line("Report authoring format", report_authoring_format(run))
217
219
  + _line("Lead runtime", run.get("leadRuntime"))
218
220
  + _line("Lead adapter name", adapter.get("name"))
219
221
  + _line("Lead dispatch mode", adapter.get("dispatchMode"))
@@ -229,6 +231,7 @@ def render_run_input(run_manifest: Path) -> str:
229
231
  + _worker_prompt_lines(run)
230
232
  + _line("Worker results directory", run.get("workerResultsDirectoryPath"))
231
233
  + _line("Expected report", run.get("expectedReportRecordPath"))
234
+ + _line("Report writer input", run.get("reportNarrativePath"))
232
235
  + _line("Expected status", run.get("expectedStatusPath"))
233
236
  + _line("Validator", run.get("validatorScriptPath"))
234
237
  + _line("Resume command", run.get("resumeCommandPath"))
@@ -17,7 +17,7 @@ from .contract_graph import (
17
17
  ContractGraphValidator,
18
18
  ContractSelection,
19
19
  )
20
- from .model_pool import ModelPool
20
+ from .model_pool import ModelPool, ResolvedModel
21
21
 
22
22
 
23
23
  class OperationPreparationError(ValueError):
@@ -37,20 +37,8 @@ class OperationSlot:
37
37
  display_name: str
38
38
 
39
39
 
40
- def resolve_operation_slots(
41
- operation_id: str,
42
- *,
43
- contract_root: Path,
44
- pool: ModelPool,
45
- count: int | None = None,
46
- ) -> Sequence[OperationSlot]:
47
- """작업 계약이 요구하는 칸과 각 칸의 모델.
48
-
49
- 모델은 런과 같은 기본값 사슬에서 고른다. 서로 다른 모델 참조를 요구한
50
- 수만큼 채우지 못하면 여기서 멈춘다 — 같은 모델을 반복하거나 워커 수를
51
- 몰래 줄이면 그 작업이 요구한 교차검증이 조용히 사라진다. `count` 는
52
- 호출자가 계약 상한 안에서 명시적으로 고른 수다.
53
- """
40
+ def _operation_contract(operation_id: str, contract_root: Path) -> tuple[str, str, int]:
41
+ """The operation's duty, role and worker ceiling."""
54
42
  graph_root = ContractGraphRoot.from_base(contract_root)
55
43
  try:
56
44
  graph = ContractGraphValidator().validate(
@@ -65,31 +53,222 @@ def resolve_operation_slots(
65
53
  f"unknown operation: {operation_id} (known: {known})"
66
54
  )
67
55
  duty_id = str(operation.payload["dutyId"])
56
+ return duty_id, graph.duties[duty_id].role_id, int(operation.payload["count"])
57
+
58
+
59
+ def operation_ceiling(operation_id: str, *, contract_root: Path) -> int:
60
+ """The most workers the operation contract allows."""
61
+ return _operation_contract(operation_id, contract_root)[2]
62
+
63
+
64
+ def resolve_operation_slots(
65
+ operation_id: str,
66
+ *,
67
+ contract_root: Path,
68
+ pool: ModelPool,
69
+ count: int | None = None,
70
+ deprioritized_provider: str | None = None,
71
+ ) -> Sequence[OperationSlot]:
72
+ """작업 계약이 요구하는 칸과 각 칸의 모델.
73
+
74
+ 모델은 런과 같은 기본값 사슬에서 고른다. 서로 다른 모델 참조를 요구한
75
+ 수만큼 채우지 못하면 여기서 멈춘다 — 같은 모델을 반복하거나 워커 수를
76
+ 몰래 줄이면 그 작업이 요구한 교차검증이 조용히 사라진다. `count` 는
77
+ 호출자가 계약 상한 안에서 명시적으로 고른 수다. `deprioritized_provider`
78
+ 의 모델은 다른 공급자의 후보 뒤로 미룬다(같은 공급자 안의 순서는 유지).
79
+ """
80
+ duty_id, role_id, ceiling = _operation_contract(operation_id, contract_root)
68
81
  # 계약의 수는 상한이다. 더 적게 여는 것은 호출자가 명시할 때만이다.
69
- ceiling = int(operation.payload["count"])
70
82
  if count is None:
71
83
  count = ceiling
72
84
  elif not 1 <= count <= ceiling:
73
85
  raise OperationPreparationError(
74
86
  f"operation {operation_id!r} takes a count from 1 to {ceiling}, got {count}"
75
87
  )
76
- role_id = graph.duties[duty_id].role_id
77
88
 
78
89
  candidates = pool.default_candidates(role_id)
90
+ if deprioritized_provider is not None:
91
+ candidates = tuple(sorted(candidates, key=lambda model: model.provider_id == deprioritized_provider))
79
92
  if len(candidates) < count:
80
93
  raise OperationPreparationError(
81
94
  f"operation {operation_id!r} requires {count} distinct models for role "
82
95
  f"{role_id!r}, available {len(candidates)}"
83
96
  )
84
- slots = []
85
- for ordinal, model in enumerate(candidates[:count], start=1):
86
- slots.append(OperationSlot(
87
- operation_id=operation_id,
88
- duty_id=duty_id,
89
- role_id=role_id,
90
- ordinal=ordinal,
91
- model_ref=str(model.model_ref),
92
- provider_id=model.provider_id,
97
+ return _numbered_slots(operation_id, duty_id, role_id, candidates[:count])
98
+
99
+
100
+ def _numbered_slots(
101
+ operation_id: str, duty_id: str, role_id: str, models: Sequence[ResolvedModel],
102
+ ) -> tuple[OperationSlot, ...]:
103
+ return tuple(
104
+ OperationSlot(
105
+ operation_id=operation_id, duty_id=duty_id, role_id=role_id, ordinal=ordinal,
106
+ model_ref=str(model.model_ref), provider_id=model.provider_id,
93
107
  display_name=model.display_name,
94
- ))
95
- return tuple(slots)
108
+ )
109
+ for ordinal, model in enumerate(models, start=1)
110
+ )
111
+
112
+
113
+ def operation_contract_root() -> Path:
114
+ """The directory holding `operations/<id>.json` contracts for this runtime."""
115
+ from .paths import find_asset_root
116
+
117
+ root = find_asset_root(("agents", "operations"), is_present=Path.is_dir)
118
+ if root is None:
119
+ raise OperationPreparationError(
120
+ "operation contracts not found: no agents/operations under OKSTRA_HOME or this checkout"
121
+ )
122
+ return root
123
+
124
+
125
+ def require_distinct_providers(providers: Sequence[str]) -> None:
126
+ """Every team needs its own provider.
127
+
128
+ The operation asks for cross-model verification, and two models of one
129
+ provider do not provide it.
130
+ """
131
+ if len(set(providers)) != len(providers):
132
+ raise OperationPreparationError(
133
+ "every team needs a different provider, got " + ", ".join(providers)
134
+ )
135
+
136
+
137
+ def resolve_model_reference(pool: ModelPool, value: str) -> ResolvedModel:
138
+ """A `provider/model` reference, or a provider alias such as `claude/opus`."""
139
+ from .domain.provider import UnknownModelError
140
+
141
+ try:
142
+ return pool.resolve(value)
143
+ except UnknownModelError:
144
+ provider, sep, alias = value.partition("/")
145
+ if not sep or not alias:
146
+ raise
147
+ return pool.resolve_alias(provider, alias)
148
+
149
+
150
+ def resolve_operation_models(
151
+ operation_id: str, references: Sequence[str], *, contract_root: Path, pool: ModelPool,
152
+ ) -> tuple[str, str, tuple[ResolvedModel, ...]]:
153
+ """The duty, role and models a caller chose for an operation, one per team, in order."""
154
+ from .domain.provider import UnknownModelError
155
+
156
+ duty_id, role_id, ceiling = _operation_contract(operation_id, contract_root)
157
+ if not references:
158
+ raise OperationPreparationError(f"operation {operation_id!r} needs at least one model")
159
+ if len(references) > ceiling:
160
+ raise OperationPreparationError(
161
+ f"operation {operation_id!r} takes at most {ceiling} models, got {len(references)}"
162
+ )
163
+ try:
164
+ models = [resolve_model_reference(pool, value) for value in references]
165
+ except UnknownModelError as exc:
166
+ raise OperationPreparationError(str(exc)) from exc
167
+ require_distinct_providers([model.provider_id for model in models])
168
+ for model in models:
169
+ if not pool.resolve_provider(model.provider_id).supports_role(role_id):
170
+ raise OperationPreparationError(
171
+ f"provider {model.provider_id!r} does not support role {role_id!r}"
172
+ )
173
+ availability = pool.availability(str(model.model_ref), role_id)
174
+ if not availability.available:
175
+ raise OperationPreparationError(
176
+ f"model {model.model_ref} is not available: {availability.reason}"
177
+ )
178
+ return duty_id, role_id, tuple(models)
179
+
180
+
181
+ def select_operation_models(
182
+ operation_id: str, flags: Sequence[str], count: int | None, *, contract_root: Path, cwd: Path,
183
+ ) -> tuple[tuple[str, ...], str]:
184
+ """Which model references an operation's teams use, and where they came from.
185
+
186
+ Flags win, then project and then global `operationModels`, then adapter
187
+ defaults (an empty tuple with source `bundled`). A count is checked
188
+ against the contract range first; with flags it must equal their number,
189
+ with a config list it takes that many from the front.
190
+ """
191
+ ceiling = operation_ceiling(operation_id, contract_root=contract_root)
192
+ if count is not None and not 1 <= count <= ceiling:
193
+ raise OperationPreparationError(
194
+ f"operation {operation_id!r} takes a count from 1 to {ceiling}, got {count}"
195
+ )
196
+ if flags:
197
+ if count is not None and count != len(flags):
198
+ raise OperationPreparationError("--count differs from the number of --model values")
199
+ return tuple(flags), "flag"
200
+ configured, scope = operation_model_defaults(operation_id, cwd)
201
+ if not configured or count is None:
202
+ return configured, scope
203
+ if count > len(configured):
204
+ raise OperationPreparationError(
205
+ f"{scope} operationModels names {len(configured)} models, fewer than --count {count}"
206
+ )
207
+ return configured[:count], scope
208
+
209
+
210
+ def resolve_operation_team(
211
+ operation_id: str, flags: Sequence[str], count: int | None, *,
212
+ contract_root: Path, pool: ModelPool, cwd: Path,
213
+ ) -> tuple[tuple[OperationSlot, ...], str]:
214
+ """The operation's slots for the selected models, and the models' source."""
215
+ references, source = select_operation_models(
216
+ operation_id, flags, count, contract_root=contract_root, cwd=cwd,
217
+ )
218
+ if not references:
219
+ return tuple(resolve_operation_slots(
220
+ operation_id, contract_root=contract_root, pool=pool, count=count,
221
+ )), source
222
+ duty_id, role_id, models = resolve_operation_models(
223
+ operation_id, references, contract_root=contract_root, pool=pool,
224
+ )
225
+ return _numbered_slots(operation_id, duty_id, role_id, models), source
226
+
227
+
228
+ def operation_model_defaults(operation_id: str, cwd: Path) -> tuple[tuple[str, ...], str]:
229
+ """The models `operationModels` names for an operation, and the scope that named them.
230
+
231
+ Project config wins over global config; neither merges with the other.
232
+ An empty tuple with scope `bundled` means no config names the operation.
233
+ """
234
+ from okstra_project.dirs import okstra_home
235
+
236
+ from .model_defaults import ModelDefaultScopes, default_candidates, default_scope
237
+
238
+ scopes = ModelDefaultScopes(
239
+ project=_operation_models(_project_config(cwd)),
240
+ global_=_operation_models(okstra_home() / "config.json"),
241
+ bundled={},
242
+ )
243
+ refs = default_candidates(operation_id, scopes)
244
+ return refs, default_scope(operation_id, scopes) or "bundled"
245
+
246
+
247
+ def _project_config(cwd: Path) -> Path:
248
+ from okstra_project import project_json_path, resolve_project_root
249
+
250
+ try:
251
+ return project_json_path(resolve_project_root(cwd=str(cwd)))
252
+ except Exception:
253
+ return cwd / ".okstra" / "project.json"
254
+
255
+
256
+ def _operation_models(path: Path) -> dict[str, tuple[str, ...]]:
257
+ from .json_boundary import load_owned_object
258
+ from .model_defaults import ModelDefaultError, parse_model_lists
259
+
260
+ payload = load_owned_object(path, artifact="model configuration") if path.is_file() else {}
261
+ try:
262
+ return parse_model_lists(payload, "operationModels", path)
263
+ except ModelDefaultError as exc:
264
+ raise OperationPreparationError(str(exc)) from exc
265
+
266
+
267
+ def slot_payload(slot: OperationSlot) -> dict[str, object]:
268
+ """The JSON row callers print for one slot."""
269
+ return {
270
+ "ordinal": slot.ordinal,
271
+ "provider": slot.provider_id,
272
+ "modelRef": slot.model_ref,
273
+ "model": slot.display_name,
274
+ }