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
@@ -0,0 +1,59 @@
1
+ """Session start summary for `okstra manager resume`."""
2
+ from __future__ import annotations
3
+
4
+ from pathlib import Path
5
+
6
+ from .manager_journal import DECISION, SESSION_SUMMARY, is_journal_kind
7
+ from .manager_log import ActivityEntry, _task_identities, check_limit, merge_activity
8
+ from .manager_store import ManagerError
9
+ from .manager_sync import status_task
10
+
11
+ DEFAULT_RECENT = 10
12
+ RECENT_DECISION_COUNT = 5
13
+
14
+
15
+ def _last_summary_index(entries: list[ActivityEntry]) -> int | None:
16
+ return next((index for index, entry in enumerate(entries) if is_journal_kind(entry, SESSION_SUMMARY)), None)
17
+
18
+
19
+ def _task_overview(home: Path, manager_id: str, task_group: str, task_id: str, now: str | None) -> dict:
20
+ """One task's sync state, or its `error` when its files cannot be read, so other tasks still report."""
21
+ try:
22
+ status = status_task(home, manager_id, task_group, task_id, now=now)
23
+ except ManagerError as exc:
24
+ return {"taskGroup": task_group, "taskId": task_id, "error": str(exc)}
25
+ overview = {
26
+ "taskGroup": task_group,
27
+ "taskId": task_id,
28
+ "syncedAt": status["syncedAt"],
29
+ "changedSinceSyncCount": status["changedSinceSyncCount"],
30
+ "unlinkedChildCount": sum(1 for child in status["children"] if not child["projectLinked"]),
31
+ }
32
+ if "syncAgeSeconds" in status:
33
+ overview["syncAgeSeconds"] = status["syncAgeSeconds"]
34
+ return overview
35
+
36
+
37
+ def resume_manager(home: Path, manager_id: str, *, recent: int = DEFAULT_RECENT, now: str | None = None) -> dict:
38
+ """What the previous sessions left: last summary, activity after it, open follow-ups and task status.
39
+
40
+ `unsummarizedCount` counts the entries listed before the last session summary in
41
+ the newest-first order of `log`, so it follows the same tie rule.
42
+ """
43
+ check_limit(recent, "--recent")
44
+ activity = merge_activity(home, manager_id)
45
+ entries = activity.entries
46
+ summary_index = _last_summary_index(entries)
47
+ summary = entries[summary_index] if summary_index is not None else None
48
+ return {
49
+ "managerId": manager_id,
50
+ "lastSummary": summary,
51
+ "unsummarizedCount": summary_index if summary_index is not None else len(entries),
52
+ "unsummarizedSince": summary["createdAt"] if summary is not None else "",
53
+ "openFollowups": activity.open_followups_oldest_first(),
54
+ "recentDecisions": [entry for entry in entries if is_journal_kind(entry, DECISION)][:RECENT_DECISION_COUNT],
55
+ "recentEntries": entries[:recent],
56
+ "tasks": [_task_overview(home, manager_id, group, task_id, now)
57
+ for group, task_id in _task_identities(home, manager_id)],
58
+ "damaged": activity.damaged,
59
+ }
@@ -19,7 +19,6 @@ from types import ModuleType
19
19
  from typing import Any, TypedDict
20
20
 
21
21
  from okstra_ctl.json_boundary import JsonBoundaryError, load_owned_object
22
- from okstra_ctl.jsonl import append_jsonl
23
22
 
24
23
  from .analysis_packet import _fence_mask, project_relative_ref
25
24
  from .brief_sources import (
@@ -35,6 +34,7 @@ from .manager_store import (
35
34
  _read_json,
36
35
  _write_json,
37
36
  create_task,
37
+ record_event,
38
38
  list_projects,
39
39
  load_manager,
40
40
  )
@@ -746,7 +746,7 @@ def split_task(
746
746
  _write_json(split_plan_path(home, manager_id, task_group, task_id), plan)
747
747
  briefs = [{"taskKey": item["taskKey"], "projectId": item["projectId"], "ticketId": item["issue"]["ticketId"],
748
748
  "briefPath": str(item["briefPath"]), "briefStatus": item["briefStatus"]} for item in items]
749
- append_jsonl(events_jsonl_path(home, manager_id, task_group, task_id),
749
+ record_event(events_jsonl_path(home, manager_id, task_group, task_id),
750
750
  {"event": "task-split", "createdAt": when, "source": source["ref"],
751
751
  "taskKeys": [brief["taskKey"] for brief in briefs]})
752
752
  return {"managerId": manager_id, "taskGroup": task_group, "taskId": task_id, "briefs": briefs}
@@ -4,12 +4,13 @@ from __future__ import annotations
4
4
  import json
5
5
  import os
6
6
  import shutil
7
+ import sys
7
8
  from datetime import datetime, timezone
8
9
  from pathlib import Path
9
10
 
10
11
  from okstra_project import project_json_path, upsert_project_json
11
12
 
12
- from okstra_ctl.jsonl import append_jsonl
13
+ from okstra_ctl.jsonl import append_jsonl, parse_jsonl_snapshot
13
14
  from okstra_ctl.json_boundary import (
14
15
  JsonBoundaryError,
15
16
  load_owned_object,
@@ -23,6 +24,7 @@ from .manager_paths import (
23
24
  children_json_path,
24
25
  directives_jsonl_path,
25
26
  events_jsonl_path,
27
+ manager_events_jsonl_path,
26
28
  manager_json_path,
27
29
  manager_root,
28
30
  projects_json_path,
@@ -46,6 +48,28 @@ def _write_json(path: Path, payload: dict) -> None:
46
48
  write_owned_object_atomic(path, payload, artifact="manager state")
47
49
 
48
50
 
51
+ def record_event(path: Path, row: dict) -> None:
52
+ """Append one activity row after the state change it describes has been saved.
53
+
54
+ An `OSError` is not raised: it becomes one stderr warning and the caller continues,
55
+ so a failed append never turns a saved state change into a failed command.
56
+ """
57
+ try:
58
+ append_jsonl(path, row)
59
+ except OSError as exc:
60
+ # The state change already succeeded. Reporting failure would make the user repeat it.
61
+ print(f"okstra manager: activity log write failed: {path}: {exc.strerror or exc}", file=sys.stderr)
62
+
63
+
64
+ def _field_changes(current: dict, requested: dict) -> dict:
65
+ """`{field: {"from", "to"}}` for each requested value that differs from the current one."""
66
+ return {
67
+ key: {"from": current.get(key), "to": value}
68
+ for key, value in requested.items()
69
+ if current.get(key) != value
70
+ }
71
+
72
+
49
73
  def _read_json(path: Path) -> dict:
50
74
  if not path.is_file():
51
75
  raise ManagerError(f"manager file not found: {path}")
@@ -58,6 +82,28 @@ def _read_json(path: Path) -> dict:
58
82
  return data
59
83
 
60
84
 
85
+ def read_jsonl_rows(path: Path) -> tuple[list[dict], list[int]]:
86
+ """Parsed rows and the line numbers of damaged lines; a missing file has neither."""
87
+ if not path.is_file():
88
+ return [], []
89
+ try:
90
+ text = path.read_text(encoding="utf-8")
91
+ except (OSError, UnicodeDecodeError) as exc:
92
+ raise ManagerError(f"failed to read {path}: {exc}") from exc
93
+ return parse_jsonl_snapshot(text)
94
+
95
+
96
+ def task_selection(task_group: str | None, task_id: str | None) -> tuple[str, str] | None:
97
+ """`--task-group` / `--task-id` as one pair, or None when neither is given."""
98
+ if (task_group is None) != (task_id is None):
99
+ raise ManagerError("--task-group and --task-id must be given together")
100
+ if task_group is None or task_id is None:
101
+ return None
102
+ if not task_group.strip() or not task_id.strip():
103
+ raise ManagerError("--task-group and --task-id must not be empty")
104
+ return task_group, task_id
105
+
106
+
61
107
  def _read_json_default(path: Path, default: dict) -> dict:
62
108
  if not path.is_file():
63
109
  return default
@@ -91,6 +137,10 @@ def init_manager(home: Path, manager_id: str, *, now: str | None = None) -> dict
91
137
  }
92
138
  root.mkdir(parents=True, exist_ok=True)
93
139
  _write_json(path, payload)
140
+ record_event(
141
+ manager_events_jsonl_path(home, canonical_id),
142
+ {"event": "manager-initialized", "createdAt": payload["createdAt"]},
143
+ )
94
144
  return payload
95
145
 
96
146
 
@@ -214,29 +264,49 @@ def link_project(
214
264
  raise ManagerError(str(exc)) from exc
215
265
  payload = _load_projects(home, manager_id)
216
266
  entry = _project_entry(payload, project_id)
267
+ when = now or _now_iso()
217
268
  next_entry = {
218
269
  "projectId": project_id,
219
270
  "projectRoot": str(root),
220
271
  "role": role,
221
272
  "tags": list(tags),
222
- "linkedAt": now or _now_iso(),
273
+ "linkedAt": when,
223
274
  }
275
+ changes = {}
224
276
  if entry is None:
225
277
  payload["projects"].append(next_entry)
226
278
  else:
279
+ changes = _field_changes(entry, {key: next_entry[key] for key in ("projectRoot", "role", "tags")})
227
280
  entry.update(next_entry)
228
281
  payload["projects"].sort(key=lambda item: item.get("projectId", ""))
229
282
  _write_json(projects_json_path(home, manager_id), payload)
283
+ if entry is None or changes:
284
+ record_event(manager_events_jsonl_path(home, manager_id), _project_linked_event(next_entry, changes))
230
285
  return payload
231
286
 
232
287
 
288
+ def _project_linked_event(linked: dict, changes: dict) -> dict:
289
+ row = {"event": "project-linked", "createdAt": linked["linkedAt"]}
290
+ row.update({key: linked[key] for key in ("projectId", "projectRoot", "role", "tags")})
291
+ if changes:
292
+ row["changes"] = changes
293
+ return row
294
+
295
+
233
296
  def _ensure_group_meta(home: Path, manager_id: str, task_group: str, when: str) -> dict:
234
297
  """그룹 폴더와 `group.json` 을 만든다. 이미 있으면 처음 기록을 그대로 둔다."""
235
298
  path = task_group_meta_path(home, manager_id, task_group)
236
299
  if path.is_file():
237
300
  return _read_json(path)
301
+ # A group directory without group.json predates group.json, so the group is not new.
302
+ group_is_new = not path.parent.is_dir()
238
303
  meta = {"taskGroup": task_group, "createdAt": when}
239
304
  _write_json(path, meta)
305
+ if group_is_new:
306
+ record_event(
307
+ manager_events_jsonl_path(home, manager_id),
308
+ {"event": "task-group-created", "createdAt": when, "taskGroup": task_group},
309
+ )
240
310
  return meta
241
311
 
242
312
 
@@ -331,7 +401,7 @@ def create_task(
331
401
  _ensure_group_meta(home, manager_id, task_group, when)
332
402
  _write_json(manifest_path, manifest)
333
403
  _write_json(children_json_path(home, manager_id, task_group, task_id), children)
334
- append_jsonl(
404
+ record_event(
335
405
  events_jsonl_path(home, manager_id, task_group, task_id),
336
406
  {
337
407
  "event": "task-children-added" if existing else "task-created",
@@ -398,14 +468,21 @@ def assign_child(
398
468
  tags: list[str],
399
469
  assignment: str,
400
470
  child_task_id: str | None = None,
471
+ now: str | None = None,
401
472
  ) -> dict:
402
473
  _read_json(task_manifest_path(home, manager_id, task_group, task_id))
403
474
  payload = _load_children(home, manager_id, task_group, task_id)
404
475
  child = _select_child_for_assignment(payload["children"], project_id, task_group, child_task_id)
405
- child["role"] = role
406
- child["tags"] = list(tags)
407
- child["assignment"] = assignment
476
+ requested = {"role": role, "tags": list(tags), "assignment": assignment}
477
+ changes = _field_changes(child, requested)
478
+ child.update(requested)
408
479
  _write_json(children_json_path(home, manager_id, task_group, task_id), payload)
480
+ if changes:
481
+ record_event(
482
+ events_jsonl_path(home, manager_id, task_group, task_id),
483
+ {"event": "task-assigned", "createdAt": now or _now_iso(),
484
+ "taskKey": str(child.get("taskKey") or ""), "changes": changes},
485
+ )
409
486
  return payload
410
487
 
411
488
 
@@ -510,10 +587,18 @@ def unlink_project(
510
587
  _write_json(projects_json_path(home, manager_id), payload)
511
588
  when = now or _now_iso()
512
589
  for manifest, keys in affected:
513
- append_jsonl(
590
+ record_event(
514
591
  events_jsonl_path(home, manager_id, str(manifest["taskGroup"]), str(manifest["taskId"])),
515
592
  {"event": "project-unlinked", "createdAt": when, "projectId": project_id, "taskKeys": keys},
516
593
  )
594
+ # Task-level rows disappear with `remove task`; this copy keeps the unlink visible afterwards.
595
+ record_event(
596
+ manager_events_jsonl_path(home, manager_id),
597
+ {"event": "project-unlinked", "createdAt": when, "projectId": project_id,
598
+ "taskKeys": result["keptChildren"],
599
+ "tasks": [{"taskGroup": str(manifest["taskGroup"]), "taskId": str(manifest["taskId"])}
600
+ for manifest, _ in affected]},
601
+ )
517
602
  return result
518
603
 
519
604
 
@@ -550,7 +635,7 @@ def remove_child(
550
635
  child_context_path(
551
636
  home, manager_id, task_group, task_id, project_id, str(child.get("taskId") or task_id)
552
637
  ).unlink(missing_ok=True)
553
- append_jsonl(
638
+ record_event(
554
639
  events_jsonl_path(home, manager_id, task_group, task_id),
555
640
  {"event": "task-child-removed", "createdAt": now or _now_iso(), "taskKey": task_key},
556
641
  )
@@ -577,16 +662,12 @@ def update_task(
577
662
  raise ManagerError("task update needs at least one of --objective, --common-brief, --progress-mode")
578
663
  if requested.get("progressMode") not in (None, "manual", "auto"):
579
664
  raise ManagerError("progress-mode must be manual or auto")
580
- changes = {
581
- key: {"from": manifest.get(key), "to": value}
582
- for key, value in requested.items()
583
- if manifest.get(key) != value
584
- }
665
+ changes = _field_changes(manifest, requested)
585
666
  for key, change in changes.items():
586
667
  manifest[key] = change["to"]
587
668
  if changes:
588
669
  _write_json(manifest_path, manifest)
589
- append_jsonl(
670
+ record_event(
590
671
  events_jsonl_path(home, manager_id, task_group, task_id),
591
672
  {"event": "task-updated", "createdAt": now or _now_iso(), "changes": changes},
592
673
  )
@@ -594,7 +675,7 @@ def update_task(
594
675
 
595
676
 
596
677
  def remove_task(
597
- home: Path, manager_id: str, task_group: str, task_id: str, *, confirm: bool
678
+ home: Path, manager_id: str, task_group: str, task_id: str, *, confirm: bool, now: str | None = None
598
679
  ) -> dict:
599
680
  """manager task 폴더를 지운다. 하위 프로젝트의 태스크와 브리프는 남는다."""
600
681
  manifest = _read_json(task_manifest_path(home, manager_id, task_group, task_id))
@@ -610,16 +691,29 @@ def remove_task(
610
691
  }
611
692
  if confirm:
612
693
  shutil.rmtree(root)
694
+ record_event(
695
+ manager_events_jsonl_path(home, manager_id),
696
+ {"event": "task-removed", "createdAt": now or _now_iso(), "taskGroup": result["taskGroup"],
697
+ "taskId": result["taskId"],
698
+ "taskKeys": [str(child.get("taskKey") or "") for child in children if isinstance(child, dict)]},
699
+ )
613
700
  return result
614
701
 
615
702
 
616
- def remove_task_group(home: Path, manager_id: str, task_group: str, *, confirm: bool) -> dict:
703
+ def remove_task_group(
704
+ home: Path, manager_id: str, task_group: str, *, confirm: bool, now: str | None = None
705
+ ) -> dict:
617
706
  """그룹 폴더와 그 안의 manager task 전부를 지운다."""
618
707
  load_manager(home, manager_id)
619
708
  root = task_group_root(home, manager_id, task_group)
620
709
  if not root.is_dir():
621
710
  raise ManagerError(f"unknown task group: {task_group}")
622
- task_ids = [str(_read_json(path).get("taskId") or path.parent.name) for path in sorted(root.glob("*/manifest.json"))]
711
+ manifests = [(path, _read_json(path)) for path in sorted(root.glob("*/manifest.json"))]
712
+ task_ids = [str(manifest.get("taskId") or path.parent.name) for path, manifest in manifests]
713
+ meta_path = root / "group.json"
714
+ stored_name = str(_read_json(meta_path).get("taskGroup") or "") if meta_path.is_file() else ""
715
+ if not stored_name and manifests:
716
+ stored_name = str(manifests[0][1].get("taskGroup") or "")
623
717
  result = {
624
718
  "managerId": manager_id,
625
719
  "taskGroup": task_group,
@@ -629,4 +723,9 @@ def remove_task_group(home: Path, manager_id: str, task_group: str, *, confirm:
629
723
  }
630
724
  if confirm:
631
725
  shutil.rmtree(root)
726
+ record_event(
727
+ manager_events_jsonl_path(home, manager_id),
728
+ {"event": "task-group-removed", "createdAt": now or _now_iso(),
729
+ "taskGroup": stored_name or task_group, "taskIds": task_ids},
730
+ )
632
731
  return result
@@ -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