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
@@ -241,17 +241,10 @@ def reference_source_extracts(
241
241
  reference_text: str, clarification_text: str,
242
242
  ) -> str:
243
243
  """합성 입력 안에 원문이 함께 있을 때 일치하는 발췌만 참조로 바꾼다."""
244
- lines = packet_text.splitlines()
245
- headings = _heading_lines(lines)
246
- if headings and headings[0][1] == "## Section Index":
247
- start = headings[0][0] - 2
248
- end = start + _INDEX_PREAMBLE_LINES + len(headings) - 1
249
- unindexed = "\n".join(lines[:start] + lines[end:]) + "\n"
250
- # 생성기가 만든 목차임을 재구성으로 확인한다. 수정된 목차가 있으면
251
- # 원문 전체를 유지해 내용 손실이나 잘못된 줄번호를 만들지 않는다.
252
- if _with_section_index(unindexed) != packet_text:
253
- return packet_text
254
- lines = unindexed.splitlines()
244
+ unindexed = _without_generated_section_index(packet_text)
245
+ if unindexed is None:
246
+ return packet_text
247
+ lines = unindexed.splitlines()
255
248
  blocks = (
256
249
  ("Task brief", brief_text, _brief_block(brief_text)),
257
250
  ("Analysis profile", profile_text, _profile_block(task_type, profile_text)),
@@ -277,6 +270,24 @@ def reference_source_extracts(
277
270
  return "\n".join(lines).rstrip() + "\n" if changed else packet_text
278
271
 
279
272
 
273
+ def replace_analysis_packet_block(packet_text: str, expected: str, replacement: str) -> str:
274
+ unindexed = _without_generated_section_index(packet_text)
275
+ if unindexed is None or unindexed.count(expected) != 1:
276
+ raise ValueError("analysis packet has no matching pending resolved-lens census or valid section index")
277
+ return _with_section_index(unindexed.replace(expected, replacement))
278
+
279
+
280
+ def _without_generated_section_index(packet_text: str) -> str | None:
281
+ lines = packet_text.splitlines()
282
+ headings = _heading_lines(lines)
283
+ if not headings or headings[0][1] != "## Section Index":
284
+ return packet_text
285
+ start = headings[0][0] - 2
286
+ end = start + _INDEX_PREAMBLE_LINES + len(headings) - 1
287
+ unindexed = "\n".join(lines[:start] + lines[end:]) + "\n"
288
+ return unindexed if _with_section_index(unindexed) == packet_text else None
289
+
290
+
280
291
  def _with_section_index(body: str) -> str:
281
292
  """Prefix the rendered packet with every section's line range.
282
293
 
@@ -5,11 +5,11 @@ import json
5
5
  import sys
6
6
  from pathlib import Path
7
7
 
8
- from ..json_boundary import JsonBoundaryError
9
- from ..report_language import resolve_report_language
10
- from .contracts import BusinessFlowError, FlowRequest
8
+ from ..json_boundary import JsonBoundaryError, external_user_json_source, load_external_json
9
+ from .contracts import BusinessFlowError, FlowRequest, flow_report_language
11
10
  from .engine import explain_flow, load_execution, rerun_explanation
12
11
  from .store import query_knowledge
12
+ from .sweep import plan_sweep, run_sweep
13
13
 
14
14
 
15
15
  def build_parser() -> argparse.ArgumentParser:
@@ -29,6 +29,11 @@ def build_parser() -> argparse.ArgumentParser:
29
29
  help="existing read-only verification record",
30
30
  )
31
31
  explain.add_argument("--host-runtime", default="claude-code")
32
+ explain.add_argument(
33
+ "--project-group",
34
+ default="",
35
+ help="limit candidate projects to this registered project group",
36
+ )
32
37
  explain.add_argument("--project-root", type=Path, default=Path.cwd())
33
38
  explain.add_argument("--json", action="store_true")
34
39
  parser = argparse.ArgumentParser(prog="okstra explain-flow", parents=[explain])
@@ -42,11 +47,22 @@ def build_parser() -> argparse.ArgumentParser:
42
47
  "knowledge", help="query relevant shared business knowledge"
43
48
  )
44
49
  knowledge.add_argument("--query", required=True)
50
+ knowledge.add_argument("--project-group", default="")
45
51
  rerun = commands.add_parser(
46
52
  "rerun", help="retry only an explanation and retain its history"
47
53
  )
48
54
  rerun.add_argument("--execution", required=True)
49
55
  rerun.add_argument("--source-root", type=Path)
56
+ sweep = commands.add_parser(
57
+ "sweep", help="plan or run explanations for a list of questions across a project group"
58
+ )
59
+ sweep.add_argument("--project-group", required=True)
60
+ sweep.add_argument("--questions", type=Path, help='JSON array of {"projectId", "question"}')
61
+ sweep.add_argument("--stale", action="store_true", help="also explain stored flows whose source changed")
62
+ sweep.add_argument("--run", action="store_true", help="call the investigator for every planned target")
63
+ sweep.add_argument("--report-language", default="")
64
+ sweep.add_argument("--host-runtime", default="claude-code")
65
+ sweep.add_argument("--json", action="store_true")
50
66
  status = commands.add_parser("status", help="inspect an explanation execution")
51
67
  status.add_argument("--execution", required=True)
52
68
  for child in (knowledge, rerun, status):
@@ -66,6 +82,7 @@ def main(argv: list[str] | None = None) -> int:
66
82
  "knowledge",
67
83
  "rerun",
68
84
  "status",
85
+ "sweep",
69
86
  "-h",
70
87
  "--help",
71
88
  }
@@ -83,14 +100,18 @@ def main(argv: list[str] | None = None) -> int:
83
100
  args.task_key,
84
101
  args.baseline,
85
102
  args.source_root,
86
- args.report_language
87
- or resolve_report_language(args.project_root, {}, {}),
103
+ flow_report_language(args.project_root, args.report_language),
88
104
  tuple(args.source_artifact),
89
105
  args.host_runtime,
106
+ args.project_group,
90
107
  )
91
108
  )
92
109
  elif args.command == "knowledge":
93
- result = query_knowledge(args.project_root, args.query)
110
+ result = query_knowledge(
111
+ args.project_root, args.query, project_group=args.project_group
112
+ )
113
+ elif args.command == "sweep":
114
+ result = _sweep(args)
94
115
  elif args.command == "rerun":
95
116
  result = rerun_explanation(
96
117
  args.project_root, args.execution, source_root=args.source_root
@@ -108,7 +129,40 @@ def main(argv: list[str] | None = None) -> int:
108
129
  return 1
109
130
 
110
131
 
132
+ def _sweep(args: argparse.Namespace) -> dict:
133
+ if args.questions is None and not args.stale:
134
+ raise BusinessFlowError("sweep needs --questions, --stale, or both")
135
+ questions = (
136
+ load_external_json(
137
+ external_user_json_source(args.questions), artifact="sweep questions", max_bytes=2_000_000
138
+ )
139
+ if args.questions
140
+ else []
141
+ )
142
+ plan = plan_sweep(args.project_group, questions, stale=args.stale)
143
+ if not args.run:
144
+ return {**plan, "status": "planned"}
145
+ return run_sweep(plan, report_language=args.report_language, host_runtime=args.host_runtime)
146
+
147
+
111
148
  def render_result(result: dict) -> str:
149
+ if "targets" in result:
150
+ lines = [
151
+ "Business Flow Sweep",
152
+ f"Project group: {result['projectGroup']}",
153
+ f"Status: {result['status']}",
154
+ f"Targets: {len(result['targets'])}; skipped as current: {len(result['skipped'])}",
155
+ ]
156
+ rows = result.get("results", result["targets"])
157
+ for row in rows:
158
+ outcome = f" -> {row['status']} {row['executionId'] or '(no record)'}" if "status" in row else ""
159
+ lines.append(f"- {row['projectId']} ({row['reason']}): {row['question']}{outcome}")
160
+ if row.get("error"):
161
+ lines.append(f" - Error: {row['error']}")
162
+ lines.extend(f"- Problem: {problem}" for problem in result["problems"])
163
+ if result["status"] == "planned":
164
+ lines.append("Nothing was explained. Add --run to call the investigator for each target.")
165
+ return "\n".join(lines)
112
166
  if "claims" in result:
113
167
  lines = ["Shared Business Knowledge", ""]
114
168
  for row in result["claims"]:
@@ -7,6 +7,7 @@ from datetime import datetime, timezone
7
7
  from pathlib import Path
8
8
  from typing import Any, Literal, TypedDict
9
9
 
10
+ from ..report_language import resolve_report_language
10
11
  from ..json_boundary import load_owned_object, write_owned_object_atomic
11
12
  from ..paths import find_asset_root
12
13
  from ..report_language import is_language_tag
@@ -112,7 +113,7 @@ class SourceSnapshot(_SourceSnapshotRequired, total=False):
112
113
  statusDigest: str
113
114
 
114
115
 
115
- class FlowRequestPayload(TypedDict):
116
+ class _FlowRequestPayloadRequired(TypedDict):
116
117
  project_root: str
117
118
  question: str
118
119
  mode: str
@@ -124,6 +125,10 @@ class FlowRequestPayload(TypedDict):
124
125
  host_runtime: str
125
126
 
126
127
 
128
+ class FlowRequestPayload(_FlowRequestPayloadRequired, total=False):
129
+ project_group: str
130
+
131
+
127
132
  class _FlowExecutionRequired(TypedDict):
128
133
  schemaVersion: int
129
134
  id: str
@@ -204,6 +209,7 @@ class FlowRequest:
204
209
  report_language: str = "en"
205
210
  source_artifacts: tuple[str, ...] = ()
206
211
  host_runtime: str = "claude-code"
212
+ project_group: str = ""
207
213
 
208
214
  def validate(self) -> None:
209
215
  if not self.project_root.is_dir() or not self.question.strip():
@@ -220,6 +226,11 @@ class FlowRequest:
220
226
  )
221
227
 
222
228
 
229
+ def flow_report_language(project_root: Path, requested: str) -> str:
230
+ """The requested report language, or the project's configured one when none was given."""
231
+ return requested or resolve_report_language(project_root, {}, {})
232
+
233
+
223
234
  def now_iso() -> str:
224
235
  return datetime.now(timezone.utc).isoformat(timespec="seconds")
225
236
 
@@ -140,7 +140,9 @@ def _investigate(
140
140
  request.project_root, result["facts"], execution["projects"], producer
141
141
  )
142
142
  if result["resolutions"]:
143
- resolve_conflicts(request.project_root, result["resolutions"], producer)
143
+ resolve_conflicts(
144
+ request.project_root, result["resolutions"], producer, request.project_group
145
+ )
144
146
  write_artifact(path, execution, "execution")
145
147
  _reinvestigate_conflicts(request, execution, path, executor)
146
148
  if request.mode != "contribute":
@@ -349,7 +351,7 @@ def _validate_reconciliation(
349
351
  raise BusinessFlowError(
350
352
  "conflict resolutions require a dedicated reinvestigation"
351
353
  )
352
- knowledge = read_shared_knowledge(request.project_root)
354
+ knowledge = read_shared_knowledge(request.project_root, request.project_group)
353
355
  validate_resolutions(knowledge, result["resolutions"])
354
356
  claims = {row["id"]: row for row in knowledge["claims"]}
355
357
  states = {row["projectId"]: row["digest"] for row in projects}
@@ -440,7 +442,11 @@ def _investigation_context(
440
442
  if baseline
441
443
  else "",
442
444
  "knowledge": query_knowledge(
443
- request.project_root, request.question, request.source_root
445
+ request.project_root,
446
+ request.question,
447
+ request.source_root,
448
+ request.project_group,
449
+ members_only=request.mode != "reconcile",
444
450
  ),
445
451
  }
446
452
 
@@ -453,7 +459,10 @@ def _reinvestigate_conflicts(
453
459
  conflict_keys = {
454
460
  row["key"]
455
461
  for row in query_knowledge(
456
- request.project_root, request.question, request.source_root
462
+ request.project_root,
463
+ request.question,
464
+ request.source_root,
465
+ request.project_group,
457
466
  )["claims"]
458
467
  if row["status"] == "conflict"
459
468
  }
@@ -477,7 +486,10 @@ def _reinvestigate_conflicts(
477
486
  unresolved = [
478
487
  row["key"]
479
488
  for row in query_knowledge(
480
- request.project_root, request.question, request.source_root
489
+ request.project_root,
490
+ request.question,
491
+ request.source_root,
492
+ request.project_group,
481
493
  )["claims"]
482
494
  if row["status"] == "conflict"
483
495
  ]
@@ -0,0 +1,60 @@
1
+ """Which stored explanation currently answers each question of a project."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ from collections.abc import Callable
6
+ from pathlib import Path
7
+ from typing import cast
8
+
9
+ from ..json_boundary import JsonBoundaryError
10
+ from .contracts import BusinessFlowError, FlowExecution, business_root, read_artifact
11
+
12
+ # `pre` describes the state before a change, and `contribute` / `reconcile` are not explanations.
13
+ DESCRIBING_MODES = ("current", "post")
14
+ ACCEPTED_STATUSES = ("complete", "partial")
15
+
16
+
17
+ def flow_id(question: str) -> str:
18
+ """One question is one flow; a later explanation of it replaces the earlier one."""
19
+ normalized = " ".join(question.casefold().split())
20
+ return "flow-" + hashlib.sha256(normalized.encode("utf-8")).hexdigest()[:16]
21
+
22
+
23
+ def _read(path: Path) -> FlowExecution:
24
+ return cast(FlowExecution, read_artifact(path, "execution"))
25
+
26
+
27
+ def latest_explanations(
28
+ project_root: Path,
29
+ *,
30
+ read: Callable[[Path], FlowExecution] = _read,
31
+ unreadable: tuple[type[Exception], ...] = (),
32
+ ) -> tuple[dict[str, tuple[Path, FlowExecution]], int]:
33
+ """The newest accepted explanation per `flow_id`, and how many records could not be read.
34
+
35
+ `read` must validate a record against the execution schema; `unreadable` names the
36
+ extra errors that reader raises for a record it refuses.
37
+ """
38
+ executions = business_root(project_root) / "executions"
39
+ latest: dict[str, tuple[Path, FlowExecution]] = {}
40
+ refused = 0
41
+ for directory in sorted(executions.iterdir()) if executions.is_dir() else []:
42
+ if not directory.is_dir():
43
+ continue
44
+ path = directory / "execution.json"
45
+ try:
46
+ execution = read(path)
47
+ if execution["status"] not in ACCEPTED_STATUSES or execution["request"]["mode"] not in DESCRIBING_MODES:
48
+ continue
49
+ if "result" not in execution:
50
+ raise BusinessFlowError("accepted explanation has no result")
51
+ key = flow_id(execution["request"]["question"])
52
+ if key not in latest or execution["createdAt"] > latest[key][1]["createdAt"]:
53
+ latest[key] = (path, execution)
54
+ except (BusinessFlowError, JsonBoundaryError, OSError, RecursionError, *unreadable):
55
+ refused += 1
56
+ return latest, refused
57
+
58
+
59
+ def recorded_source_states(execution: FlowExecution) -> dict[str, dict[str, str]]:
60
+ return {row["projectId"]: {"head": row["head"], "digest": row["digest"]} for row in execution["projects"]}
@@ -10,6 +10,7 @@ from typing import Any
10
10
  from ..json_boundary import load_owned_object
11
11
  from ..manager_store import discover_projects
12
12
  from ..paths import okstra_home
13
+ from ..project_group import ProjectGroupError, read_group
13
14
  from .contracts import (
14
15
  BusinessEvidence,
15
16
  BusinessFlowError,
@@ -21,6 +22,22 @@ from .contracts import (
21
22
 
22
23
 
23
24
  def candidate_projects(request: FlowRequest) -> list[ProjectCandidate]:
25
+ """Projects an investigation inspects: the group's members when a group is set."""
26
+ # A reconciliation settles a conflict whose other side may sit outside the group.
27
+ grouped = bool(request.project_group) and request.mode != "reconcile"
28
+ return _projects(request, with_run_history=not grouped)
29
+
30
+
31
+ def knowledge_projects(request: FlowRequest) -> list[ProjectCandidate]:
32
+ """Projects whose knowledge stores are read: run history plus the group's members.
33
+
34
+ A group only adds stores here. Conflicts and their resolutions are judged over this
35
+ set, so a group never hides one side of a stored resolution.
36
+ """
37
+ return _projects(request, with_run_history=True)
38
+
39
+
40
+ def _projects(request: FlowRequest, *, with_run_history: bool) -> list[ProjectCandidate]:
24
41
  root = request.project_root.resolve()
25
42
  config = root / ".okstra" / "project.json"
26
43
  project_id = root.name
@@ -30,8 +47,10 @@ def candidate_projects(request: FlowRequest) -> list[ProjectCandidate]:
30
47
  or project_id
31
48
  )
32
49
  candidates = {
33
- row["projectId"]: {"projectId": row["projectId"], "root": row["projectRoot"]}
34
- for row in discover_projects(okstra_home())
50
+ name: {"projectId": name, "root": registered_root}
51
+ for name, registered_root in registered_roots(
52
+ request.project_group, with_run_history=with_run_history
53
+ ).items()
35
54
  }
36
55
  candidates[project_id] = {
37
56
  "projectId": project_id,
@@ -40,6 +59,20 @@ def candidate_projects(request: FlowRequest) -> list[ProjectCandidate]:
40
59
  return sorted(candidates.values(), key=lambda row: row["projectId"])
41
60
 
42
61
 
62
+ def registered_roots(
63
+ project_group: str, *, with_run_history: bool, home: Path | None = None
64
+ ) -> dict[str, str]:
65
+ """The root of each projectId from run history and the group's registration; the group's row wins."""
66
+ home = home or okstra_home()
67
+ registered = discover_projects(home) if with_run_history else []
68
+ if project_group:
69
+ try:
70
+ registered += read_group(home, project_group)["projects"]
71
+ except ProjectGroupError as exc:
72
+ raise BusinessFlowError(str(exc)) from exc
73
+ return {row["projectId"]: row["projectRoot"] for row in registered}
74
+
75
+
43
76
  def git_output(root: Path, *args: str) -> bytes:
44
77
  result = subprocess.run(
45
78
  ["git", "-C", str(root), *args], capture_output=True, check=False
@@ -25,7 +25,7 @@ from .contracts import (
25
25
  read_artifact,
26
26
  write_artifact,
27
27
  )
28
- from .source import candidate_projects, capture_project
28
+ from .source import candidate_projects, capture_project, knowledge_projects
29
29
 
30
30
  CONFIRMED_LEVELS = frozenset({"static", "execution-verified"})
31
31
  PACKET_CLAIM_LIMIT = 40
@@ -160,12 +160,17 @@ def _mark_conflicts(claims: list[StoredClaim]) -> None:
160
160
 
161
161
 
162
162
  def resolve_conflicts(
163
- project_root: Path, resolutions: list[BusinessResolution], producer: ClaimProducer
163
+ project_root: Path,
164
+ resolutions: list[BusinessResolution],
165
+ producer: ClaimProducer,
166
+ project_group: str,
164
167
  ) -> None:
165
168
  path = artifact_path(project_root, "knowledge.json")
166
169
  with dir_flock(path.parent, ".knowledge.lock"):
167
170
  data = read_knowledge(project_root)
168
- validate_resolutions(read_shared_knowledge(project_root), resolutions)
171
+ validate_resolutions(
172
+ read_shared_knowledge(project_root, project_group), resolutions
173
+ )
169
174
  by_id = {row["id"]: row for row in data["claims"]}
170
175
  for resolution in resolutions:
171
176
  ids = resolution["claimIds"]
@@ -238,9 +243,11 @@ def _resolution_rows(
238
243
  return rows
239
244
 
240
245
 
241
- def read_shared_knowledge(project_root: Path) -> dict[str, Any]:
246
+ def read_shared_knowledge(project_root: Path, project_group: str) -> dict[str, Any]:
242
247
  claims, resolutions, errors = [], [], []
243
- candidates = candidate_projects(FlowRequest(project_root, "business"))
248
+ candidates = knowledge_projects(
249
+ FlowRequest(project_root, "business", project_group=project_group)
250
+ )
244
251
  for candidate in candidates:
245
252
  root = Path(candidate["root"])
246
253
  try:
@@ -289,17 +296,40 @@ def _apply_shared_resolutions(
289
296
 
290
297
 
291
298
  def query_knowledge(
292
- project_root: Path, query: str, source_root: Path | None = None
299
+ project_root: Path,
300
+ query: str,
301
+ source_root: Path | None = None,
302
+ project_group: str = "",
303
+ *,
304
+ members_only: bool = True,
293
305
  ) -> dict[str, Any]:
306
+ """Select stored claims for a question.
307
+
308
+ With a group, `members_only` keeps the claims its members own. Their status still
309
+ comes from the whole knowledge scope, so a conflict with an outside claim shows.
310
+ """
294
311
  sources = {
295
312
  row["projectId"]: row["root"]
296
- for row in candidate_projects(
297
- FlowRequest(project_root, query or "business", source_root=source_root)
313
+ for row in knowledge_projects(
314
+ FlowRequest(
315
+ project_root,
316
+ query or "business",
317
+ source_root=source_root,
318
+ project_group=project_group,
319
+ )
298
320
  )
299
321
  }
300
322
  tokens = set(re.findall(r"[\w-]{2,}", query.casefold()))
301
- shared = read_shared_knowledge(project_root)
323
+ shared = read_shared_knowledge(project_root, project_group)
302
324
  claims, errors = shared["claims"], shared["errors"]
325
+ if project_group and members_only:
326
+ member_roots = {
327
+ row["root"]
328
+ for row in candidate_projects(
329
+ FlowRequest(project_root, "business", project_group=project_group)
330
+ )
331
+ }
332
+ claims = [row for row in claims if row["ownerRoot"] in member_roots]
303
333
  selected = [
304
334
  row
305
335
  for row in claims
@@ -328,15 +358,22 @@ def query_knowledge(
328
358
  selected, keys = expanded, {row["key"] for row in expanded}
329
359
  states: dict[str, dict[str, Any]] = {}
330
360
  for row in selected:
331
- row["freshness"] = _freshness(row, states, sources)
361
+ row["freshness"] = source_freshness(row["sourceStates"], states, sources)
332
362
  row["selectionReason"] = "business terms or a connected claim key"
333
363
  return {"claims": selected, "errors": errors, "query": query}
334
364
 
335
365
 
336
- def _freshness(
337
- claim: dict[str, Any], cache: dict[str, dict[str, Any]], sources: dict[str, str]
366
+ def source_freshness(
367
+ source_states: dict[str, Any], cache: dict[str, dict[str, Any]], sources: dict[str, str]
338
368
  ) -> str:
339
- for project_id, expected in claim["sourceStates"].items():
369
+ """Compare recorded source versions with the projects as they are now.
370
+
371
+ `cache` keeps one capture per root across calls; `sources` maps a projectId to its root.
372
+ """
373
+ for project_id, expected in source_states.items():
374
+ # A version that was not captured when it was recorded cannot be compared.
375
+ if not expected.get("digest"):
376
+ return "unverified"
340
377
  root = sources.get(project_id)
341
378
  if root is None:
342
379
  return "unverified"
@@ -347,7 +384,7 @@ def _freshness(
347
384
  return "unverified"
348
385
  if current["digest"] != expected["digest"]:
349
386
  return "historical"
350
- return "current" if claim["sourceStates"] else "unverified"
387
+ return "current" if source_states else "unverified"
351
388
 
352
389
 
353
390
  def knowledge_packet(
@@ -0,0 +1,124 @@
1
+ """Explain a list of questions across a project group, skipping the ones still current."""
2
+ from __future__ import annotations
3
+
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+ from ..paths import okstra_home
8
+ from ..json_boundary import JsonBoundaryError
9
+ from ..project_group import ProjectGroupError, show_group
10
+ from .contracts import BusinessFlowError, FlowRequest, flow_report_language
11
+ from .engine import explain_flow
12
+ from .history import flow_id, latest_explanations, recorded_source_states
13
+ from .invocation import FlowExecutor
14
+ from .source import registered_roots
15
+ from .store import source_freshness
16
+
17
+
18
+ def _questions(rows: object) -> list[tuple[str, str]]:
19
+ if not isinstance(rows, list):
20
+ raise BusinessFlowError("sweep questions must be a JSON array")
21
+ questions = []
22
+ for row in rows:
23
+ if (
24
+ not isinstance(row, dict)
25
+ or not isinstance(row.get("projectId"), str)
26
+ or not isinstance(row.get("question"), str)
27
+ or not row["question"].strip()
28
+ ):
29
+ raise BusinessFlowError('each sweep question needs a "projectId" and a non-empty "question"')
30
+ questions.append((row["projectId"], row["question"]))
31
+ return questions
32
+
33
+
34
+ def plan_sweep(project_group: str, questions: object, *, stale: bool, home: Path | None = None) -> dict[str, Any]:
35
+ """Decide what a sweep would explain. No model is called.
36
+
37
+ A listed question is a target unless its newest explanation is still `current`; its
38
+ reason is `new` (never explained), `historical` (a recorded project changed) or
39
+ `unverified` (a recorded version cannot be compared, so it is a target on every sweep).
40
+ With `stale`, every stored explanation that is `historical` is a target too.
41
+ A member whose root is missing or unreadable is reported in `problems`, and each of
42
+ its listed questions is reported there as not planned.
43
+ """
44
+ home = home or okstra_home()
45
+ try:
46
+ group = show_group(home, project_group)
47
+ except ProjectGroupError as exc:
48
+ raise BusinessFlowError(str(exc)) from exc
49
+ members = {member["projectId"]: member for member in group["projects"]}
50
+ roots = registered_roots(group["projectGroup"], with_run_history=True, home=home)
51
+ captured: dict[str, dict[str, Any]] = {}
52
+ targets: dict[tuple[str, str], dict[str, str]] = {}
53
+ skipped: dict[tuple[str, str], dict[str, str]] = {}
54
+ problems = []
55
+ stored: dict[str, dict[str, tuple[str, str]]] = {}
56
+ for project_id, member in sorted(members.items()):
57
+ if not member["rootExists"]:
58
+ problems.append(f"{project_id}: registered root is missing: {member['projectRoot']}")
59
+ continue
60
+ try:
61
+ latest, refused = latest_explanations(Path(member["projectRoot"]))
62
+ except (OSError, BusinessFlowError) as exc:
63
+ problems.append(f"{project_id}: stored explanations could not be listed: {exc}")
64
+ continue
65
+ if refused:
66
+ problems.append(f"{project_id}: {refused} stored explanation record(s) could not be read")
67
+ stored[project_id] = {
68
+ key: (execution["request"]["question"], source_freshness(recorded_source_states(execution), captured, roots))
69
+ for key, (_, execution) in latest.items()
70
+ }
71
+ for project_id, question in _questions(questions):
72
+ if project_id not in members:
73
+ raise BusinessFlowError(f"project {project_id} is not in project-group {group['projectGroup']}")
74
+ if project_id not in stored:
75
+ problems.append(f"{project_id}: not planned because the project could not be read: {question}")
76
+ continue
77
+ key = flow_id(question)
78
+ freshness = stored[project_id].get(key, (question, "new"))[1]
79
+ row = {"projectId": project_id, "question": question, "reason": freshness}
80
+ (skipped if freshness == "current" else targets)[(project_id, key)] = row
81
+ if stale:
82
+ for project_id, flows in stored.items():
83
+ for key, (question, freshness) in flows.items():
84
+ if freshness == "historical":
85
+ targets.setdefault((project_id, key), {"projectId": project_id, "question": question, "reason": freshness})
86
+ return {
87
+ "projectGroup": group["projectGroup"],
88
+ "targets": [targets[key] for key in sorted(targets)],
89
+ "skipped": [skipped[key] for key in sorted(skipped)],
90
+ "problems": problems,
91
+ "roots": {name: member["projectRoot"] for name, member in members.items()},
92
+ }
93
+
94
+
95
+ def run_sweep(
96
+ plan: dict[str, Any], *, report_language: str, host_runtime: str, executor: FlowExecutor | None = None
97
+ ) -> dict[str, Any]:
98
+ """Explain every planned target in order. One failure does not stop the rest.
99
+
100
+ A target that fails before its execution record exists is reported with an empty
101
+ `executionId`.
102
+ """
103
+ results = []
104
+ for target in plan["targets"]:
105
+ root = Path(plan["roots"][target["projectId"]])
106
+ try:
107
+ execution = explain_flow(
108
+ FlowRequest(
109
+ root,
110
+ target["question"],
111
+ report_language=flow_report_language(root, report_language),
112
+ host_runtime=host_runtime,
113
+ project_group=plan["projectGroup"],
114
+ ),
115
+ executor,
116
+ )
117
+ except (OSError, BusinessFlowError, JsonBoundaryError) as exc:
118
+ # explain_flow validates the request and writes its first record before it starts catching.
119
+ results.append({**target, "executionId": "", "status": "failed", "error": str(exc)})
120
+ continue
121
+ results.append({
122
+ **target, "executionId": execution["id"], "status": execution["status"], "error": execution.get("error", ""),
123
+ })
124
+ return {**plan, "results": results, "status": "failed" if any(row["status"] == "failed" for row in results) else "complete"}