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,116 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+ from typing import cast
5
+
6
+ from okstra_project.dirs import PROJECT_JSON_RELATIVE
7
+
8
+ from ...business_flow.contracts import BusinessFact, BusinessFlowError, BusinessResult, FlowExecution, business_root, schema_definition
9
+ from ...business_flow.history import flow_id, latest_explanations, recorded_source_states
10
+ from ...business_flow.store import CONFIRMED_LEVELS
11
+ from ...json_boundary import JsonBoundaryError, load_owned_object
12
+ from ..config import SourceConfig, includes_project
13
+ from ..contracts import MAX_INPUT_BYTES, DoyouknowError, Node, Relation
14
+ from ..source_contracts import SourceDomain, SourceRef, SourceScan, SourceSnapshot, snapshot_payload
15
+ from .io import read_source_object, safe_source_path
16
+
17
+ _UNREADABLE = (DoyouknowError, BusinessFlowError, JsonBoundaryError, OSError, RecursionError)
18
+
19
+
20
+ def _evidence_refs(fact: BusinessFact) -> list[str]:
21
+ return [f"{row['projectId']}:{row['path']}:{row['line']}" for row in fact["evidence"]]
22
+
23
+
24
+ def _project_node(project_id: str) -> Node:
25
+ return {"kind": "project", "scope": "okstra-project", "key": project_id, "title": project_id, "ref": "project:" + project_id}
26
+
27
+
28
+ def _graph(project_id: str, result: BusinessResult, locator: str) -> tuple[list[Node], list[Relation]]:
29
+ facts = {fact["key"]: fact for fact in result["facts"]}
30
+ involved = {project_id, *result["inspectedProjects"]}
31
+ for step in result["steps"]:
32
+ involved.update(step["projectIds"])
33
+ for row in result["relationships"]:
34
+ involved.update((row["from"], row["to"]))
35
+ nodes = [_project_node(name) for name in sorted(involved)]
36
+ relations: list[Relation] = [
37
+ {
38
+ "from": "$source", "to": "project:" + name,
39
+ "kind": "belongs-to" if name == project_id else "involves",
40
+ "reason": "The project stores this explanation." if name == project_id else "The explanation covers this project.",
41
+ "evidence": [locator], "standing": "observed",
42
+ }
43
+ for name in sorted(involved)
44
+ ]
45
+ # The explanation schema allows a blank term or meaning; a graph node and its relation do not.
46
+ terms = {row["term"].casefold(): row for row in result["terms"] if row["term"].strip() and row["meaning"].strip()}
47
+ for index, (key, row) in enumerate(sorted(terms.items())):
48
+ ref = f"term:{index}"
49
+ nodes.append({"kind": "concept", "scope": project_id, "key": key, "title": row["term"], "ref": ref})
50
+ relations.append({"from": "$source", "to": ref, "kind": "defines", "reason": row["meaning"], "evidence": [locator], "standing": "observed"})
51
+ for row in result["relationships"]:
52
+ linked = [facts[key] for key in row["factKeys"] if key in facts]
53
+ relations.append({
54
+ "from": "project:" + row["from"], "to": "project:" + row["to"], "kind": row["kind"],
55
+ "reason": row["data"],
56
+ "evidence": [ref for fact in linked for ref in _evidence_refs(fact)] or [locator],
57
+ "standing": "observed" if linked and all(fact["level"] in CONFIRMED_LEVELS for fact in linked) else "candidate",
58
+ })
59
+ return nodes, relations
60
+
61
+
62
+ def _snapshot(project_id: str, locator: str, execution: FlowExecution, settings: SourceConfig) -> SourceSnapshot:
63
+ result, request = execution["result"], execution["request"]
64
+ nodes, relations = _graph(project_id, result, locator)
65
+ metadata = {
66
+ "projectId": project_id, "executionId": execution["id"], "question": request["question"], "mode": request["mode"],
67
+ "status": execution["status"], "summary": result["summary"],
68
+ "terms": result["terms"], "steps": result["steps"], "relationships": result["relationships"],
69
+ # Excerpts are source text; the graph keeps where each fact was read, not the text.
70
+ "facts": [{**{key: fact[key] for key in ("key", "business", "value", "level")}, "evidence": _evidence_refs(fact)} for fact in result["facts"]],
71
+ "inspectedProjects": result["inspectedProjects"], "gaps": result["gaps"], "questions": result["questions"],
72
+ "sourceStates": recorded_source_states(execution),
73
+ }
74
+ native_id = flow_id(request["question"])
75
+ snapshot = SourceSnapshot(
76
+ ref=SourceRef("business", project_id, native_id),
77
+ primary_node={"kind": "flow", "scope": project_id, "key": native_id, "ref": "primary", "title": result["title"]},
78
+ locator=locator, metadata=metadata, nodes=tuple(nodes), relations=tuple(relations),
79
+ source_updated_at=execution["createdAt"], scope=settings["scope"],
80
+ )
81
+ snapshot_payload(snapshot)
82
+ return snapshot
83
+
84
+
85
+ def _latest_explanations(project_root: Path) -> tuple[dict[str, tuple[Path, FlowExecution]], int]:
86
+ """The owner's selection, read with this store's containment and size limits."""
87
+ safe_source_path(project_root, business_root(project_root) / "executions")
88
+
89
+ def read(path: Path) -> FlowExecution:
90
+ return cast(FlowExecution, load_owned_object(
91
+ safe_source_path(project_root, path), artifact="business flow execution",
92
+ schema=schema_definition("execution"), max_bytes=MAX_INPUT_BYTES,
93
+ ))
94
+
95
+ return latest_explanations(project_root, read=read, unreadable=(DoyouknowError,))
96
+
97
+
98
+ def scan_business_flows(project_root: Path, project_id: str, settings: SourceConfig) -> SourceScan:
99
+ domain = SourceDomain("business", project_id)
100
+ if "business" not in settings["sources"] or not includes_project(settings, project_id):
101
+ return SourceScan(domain, (), (), "partial")
102
+ try:
103
+ if read_source_object(project_root, PROJECT_JSON_RELATIVE).get("projectId") != project_id:
104
+ raise DoyouknowError("registered project identity does not match its source")
105
+ latest, unreadable = _latest_explanations(project_root)
106
+ except _UNREADABLE:
107
+ return SourceScan(domain, (), (), "unavailable", ("project-source-unavailable",))
108
+ snapshots, observed = [], []
109
+ errors = ["business-source-unavailable"] * unreadable
110
+ for native_id, (locator, execution) in sorted(latest.items()):
111
+ observed.append(SourceRef("business", project_id, native_id))
112
+ try:
113
+ snapshots.append(_snapshot(project_id, str(locator), execution, settings))
114
+ except _UNREADABLE:
115
+ errors.append("business-source-unavailable")
116
+ return SourceScan(domain, tuple(snapshots), tuple(observed), "partial" if errors else "complete", tuple(errors))
@@ -13,7 +13,7 @@ from ...json_boundary import JsonBoundaryError
13
13
  from ...jsonl import parse_jsonl_snapshot
14
14
  from ...manager_paths import (
15
15
  ManagerPathError, canonical_manager_id, children_json_path,
16
- directives_jsonl_path, manager_json_path, projects_json_path,
16
+ directives_jsonl_path, journal_jsonl_path, manager_json_path, projects_json_path,
17
17
  manager_root, snapshots_json_path, task_groups_root, task_manifest_path,
18
18
  )
19
19
  from ..config import SourceConfig, includes_project
@@ -58,14 +58,24 @@ def _manager_projects(home: Path, root: Path, settings: SourceConfig) -> list[di
58
58
  return rows
59
59
 
60
60
 
61
+ JOURNAL_NATIVE_ID = "journal"
62
+
63
+
64
+ def _optional_jsonl(home: Path, path: Path) -> tuple[list[dict], list[int]]:
65
+ """Rows and damaged line numbers of an optional JSONL source file."""
66
+ target = safe_source_path(home, path)
67
+ return parse_jsonl_snapshot(read_source_text(home, target)) if target.exists() else ([], [])
68
+
69
+
61
70
  def _root_snapshot(home: Path, manager: dict, projects: list[dict], settings: SourceConfig) -> SourceSnapshot:
62
71
  manager_id = manager["managerId"]
72
+ metadata = {"manager": manager, "projects": projects}
63
73
  nodes = tuple({"kind": "project", "scope": "okstra-project", "key": row["projectId"], "ref": f"project-{index}", "title": row["projectId"]} for index, row in enumerate(projects))
64
74
  relations = tuple({"from": "$source", "to": node["ref"], "kind": "includes-project", "reason": "The manager registers this project.", "evidence": [str(projects_json_path(home, manager_id))], "standing": "observed"} for node in nodes)
65
75
  snapshot = SourceSnapshot(
66
76
  SourceRef("manager", manager_id, "$manager"),
67
77
  {"kind": "entity", "scope": "okstra-manager", "key": manager_id, "ref": "primary", "title": manager_id},
68
- str(manager_json_path(home, manager_id)), {"manager": manager, "projects": projects}, nodes, relations,
78
+ str(manager_json_path(home, manager_id)), metadata, nodes, relations,
69
79
  source_updated_at=manager.get("updatedAt"), scope=settings["scope"],
70
80
  )
71
81
  return snapshot
@@ -75,8 +85,7 @@ def _task_records(home: Path, manager_id: str, group: str, task_id: str, setting
75
85
  children = _project_rows(read_source_object(home, children_json_path(home, manager_id, group, task_id)).get("children"), settings)
76
86
  saved = _optional_object(home, snapshots_json_path(home, manager_id, group, task_id), {})
77
87
  saved = {**saved, "children": _project_rows(saved.get("children", []), settings)}
78
- directives_path = safe_source_path(home, directives_jsonl_path(home, manager_id, group, task_id))
79
- directives, damaged = parse_jsonl_snapshot(read_source_text(home, directives_path)) if directives_path.exists() else ([], [])
88
+ directives, damaged = _optional_jsonl(home, directives_jsonl_path(home, manager_id, group, task_id))
80
89
  if damaged:
81
90
  raise DoyouknowError("manager notes contain damaged rows")
82
91
  return children, _project_rows(directives, settings), saved
@@ -115,6 +124,33 @@ def _task_snapshot(home: Path, path: Path, manifest: dict, ref: SourceRef, proje
115
124
  return snapshot
116
125
 
117
126
 
127
+ def _journal_source(home: Path, manager_id: str, settings: SourceConfig) -> tuple[SourceRef | None, SourceSnapshot | None, str | None]:
128
+ """The manager journal as its own source, so its damage or size cannot stop the root and task sources."""
129
+ path = journal_jsonl_path(home, manager_id)
130
+ if not safe_source_path(home, path).exists():
131
+ return None, None, None
132
+ ref = SourceRef("manager", manager_id, JOURNAL_NATIVE_ID)
133
+ try:
134
+ rows, damaged = _optional_jsonl(home, path)
135
+ except (DoyouknowError, JsonBoundaryError, OSError):
136
+ return ref, None, "manager-journal-unavailable"
137
+ if damaged:
138
+ return ref, None, "manager-journal-damaged"
139
+ snapshot = SourceSnapshot(
140
+ ref,
141
+ {"kind": "entity", "scope": "manager:" + manager_id, "key": JOURNAL_NATIVE_ID, "ref": "primary", "title": "Manager journal"},
142
+ str(path), {"journal": rows},
143
+ ({"kind": "entity", "scope": "okstra-manager", "key": manager_id, "ref": "manager", "title": manager_id},),
144
+ ({"from": "$source", "to": "manager", "kind": "belongs-to", "reason": "The manager owns this journal.", "evidence": [str(path)], "standing": "observed"},),
145
+ scope=settings["scope"],
146
+ )
147
+ return ref, snapshot, None
148
+
149
+
150
+ def _snapshot_error(snapshot: SourceSnapshot) -> str:
151
+ return "manager-journal-unavailable" if snapshot.ref.native_id == JOURNAL_NATIVE_ID else "manager-task-unavailable"
152
+
153
+
118
154
  def _manager_manifest_data(home: Path, path: Path) -> dict:
119
155
  manifest = read_source_object(home, path)
120
156
  group, task_id = manifest.get("taskGroup"), manifest.get("taskId")
@@ -156,13 +192,15 @@ def _scan_manager(home: Path, root: Path, settings: SourceConfig, *, validate: b
156
192
  root_snapshot = _root_snapshot(home, manager, projects, settings)
157
193
  snapshots.append(root_snapshot)
158
194
  observed.append(SourceRef("manager", manager_id, "$manager"))
159
- for path in _manager_manifest_candidates(home, root):
160
- ref, snapshot, error = _manager_task_source(home, path, manager_id, projects, settings)
195
+ child_sources = [_manager_task_source(home, path, manager_id, projects, settings)
196
+ for path in _manager_manifest_candidates(home, root)]
197
+ child_sources.append(_journal_source(home, manager_id, settings))
198
+ for ref, snapshot, error in child_sources:
161
199
  if ref is not None:
162
200
  observed.append(ref)
163
201
  if snapshot is not None:
164
202
  snapshots.append(snapshot)
165
- else:
203
+ elif error is not None:
166
204
  errors.append(error)
167
205
  except (DoyouknowError, JsonBoundaryError, ManagerPathError, OSError, StateError, TypeError, RecursionError):
168
206
  return SourceScan(domain, (), (), "unavailable", ("manager-source-unavailable",)), []
@@ -194,13 +232,14 @@ def gate_manager_scan(scan: SourceScan, *, gate: Callable[[PreparedSource], bool
194
232
  except SecretRefusal:
195
233
  errors.append("manager-secret-refused")
196
234
  except (DoyouknowError, JsonBoundaryError, OSError, StateError, TypeError, RecursionError):
197
- errors.append("manager-task-unavailable")
235
+ errors.append(_snapshot_error(snapshot))
198
236
  return replace(scan, snapshots=tuple(snapshots), status="partial" if errors else scan.status, errors=tuple(errors))
199
237
 
200
238
 
201
239
  def _manager_source_paths(home: Path, root: Path) -> list[tuple[Path, bool]]:
202
240
  manager_id = root.name
203
- paths = [(manager_json_path(home, manager_id), True), (projects_json_path(home, manager_id), False)]
241
+ paths = [(manager_json_path(home, manager_id), True), (projects_json_path(home, manager_id), False),
242
+ (journal_jsonl_path(home, manager_id), False)]
204
243
  for path in _manager_manifest_candidates(home, root):
205
244
  manifest = _manager_manifest_data(home, path)
206
245
  group, task_id = manifest["taskGroup"], manifest["taskId"]
@@ -1,16 +1,18 @@
1
1
  from __future__ import annotations
2
2
 
3
- from collections.abc import Iterator
3
+ from collections.abc import Callable, Iterator
4
4
  from functools import partial
5
5
  from pathlib import Path
6
6
 
7
7
  from ..json_boundary import JsonBoundaryError
8
+ from ..project_group import group_project_roots
8
9
  from .config import SourceConfig, load_config
9
10
  from .contracts import DoyouknowError
10
11
  from .identity import stable_id
11
12
  from .registration import retry_pending, validate_source_and_update_refusal_cache
12
13
  from .source_contracts import SourceDomain, SourceKind, SourceScan
13
14
  from .source_store import apply_source_scan
15
+ from .sources.business import scan_business_flows
14
16
  from .sources.manager import scan_managers
15
17
  from .sources.memory import scan_memory_sources
16
18
  from .sources.task import scan_project_tasks
@@ -26,14 +28,37 @@ def _source_scans(home: Path, settings: SourceConfig) -> Iterator[SourceScan]:
26
28
  managers, projects = scan_managers(home, settings, gate=gate)
27
29
  yield from managers
28
30
  if "task" in enabled:
29
- registry_unavailable = any(scan.status == "unavailable" for scan in managers)
30
- for project_id, roots in sorted(projects.items()):
31
- if registry_unavailable:
32
- yield SourceScan(SourceDomain("task", project_id), (), (), "unavailable", ("project-registry-incomplete",))
33
- elif len(roots) != 1:
34
- yield SourceScan(SourceDomain("task", project_id), (), (), "unavailable", ("conflicting-project-roots",))
35
- else:
36
- yield scan_project_tasks(roots[0], project_id, settings)
31
+ incomplete = "project-registry-incomplete" if any(scan.status == "unavailable" for scan in managers) else None
32
+ yield from _project_scans("task", projects, incomplete, partial(_scan_with, scan_project_tasks, settings))
33
+ if "business" in enabled:
34
+ projects, registry_errors = group_project_roots(home)
35
+ incomplete = "project-group-registry-incomplete" if registry_errors else None
36
+ if incomplete:
37
+ # Reported on its own domain as well: with no readable group there is no project to carry it.
38
+ yield SourceScan(SourceDomain("business", "project-group-registry"), (), (), "unavailable", (incomplete,))
39
+ yield from _project_scans("business", projects, incomplete, partial(_scan_with, scan_business_flows, settings))
40
+
41
+
42
+ def _scan_with(scan: Callable[[Path, str, SourceConfig], SourceScan], settings: SourceConfig, root: Path, project_id: str) -> SourceScan:
43
+ return scan(root, project_id, settings)
44
+
45
+
46
+ def _project_scans(
47
+ kind: SourceKind, projects: dict[str, tuple[Path, ...]], incomplete: str | None, scan: Callable[[Path, str], SourceScan],
48
+ ) -> Iterator[SourceScan]:
49
+ """Scan each project under its one registered root.
50
+
51
+ A complete scan marks sources it did not see as missing, and one root is only known
52
+ to be the only root when the whole registry was read, so an incomplete registry
53
+ scans nothing.
54
+ """
55
+ for project_id, roots in sorted(projects.items()):
56
+ if incomplete:
57
+ yield SourceScan(SourceDomain(kind, project_id), (), (), "unavailable", (incomplete,))
58
+ elif len(roots) != 1:
59
+ yield SourceScan(SourceDomain(kind, project_id), (), (), "unavailable", ("conflicting-project-roots",))
60
+ else:
61
+ yield scan(roots[0], project_id)
37
62
 
38
63
 
39
64
  def sync_sources(*, home: Path | None = None, source: SourceKind | None = None) -> dict:
@@ -393,15 +393,14 @@ class _Validator:
393
393
  self.errors.append(f"{_format_path(path)}: {message}")
394
394
 
395
395
 
396
- def follow_up_task_rules(schema: Mapping[str, Any], task_type: str) -> tuple[str, ...]:
397
- """이 task type 의 `followUpTasks` 에 스키마가 못 박은 행 규칙, 저작 문장으로.
398
-
399
- `allOf` 의 if/then 가지 하나가 비종결 task type 에 phase-continuation 행
400
- 하나를 요구하고(`minItems`, `contains.origin.const`), `FollowUpRow` 의
401
- 가지가 그 행의 `autoSpawn` 을 `no` 로 고정한다. 작성자는 둘 다 읽지 못해
402
- 빈 배열을 냈고 조립이 `array length 0 < minItems 1` 로 거절했다(2026-09-09
403
- 실측, dev-10642 requirements-discovery: 이 계열로만 라운드 3회). 가지가
404
- 이 task type 에 없으면 빈 튜플이다 — 제약이 없다는 뜻이지 실패가 아니다.
396
+ def follow_up_task_rules(
397
+ schema: Mapping[str, Any], task_type: str, *, authoring_format: str = "markdown-v1",
398
+ ) -> tuple[str, ...]:
399
+ """Describe schema-pinned follow-up rows in the declared authoring format.
400
+
401
+ Task-specific conditions supply minimum counts and the continuation origin;
402
+ FollowUpRow conditions supply pinned values such as autoSpawn. A task with
403
+ no matching condition has no additional rules.
405
404
  """
406
405
  def _task_matches(condition: Any) -> bool:
407
406
  if not isinstance(condition, dict):
@@ -413,6 +412,10 @@ def follow_up_task_rules(schema: Mapping[str, Any], task_type: str) -> tuple[str
413
412
  allowed = [selector["const"]]
414
413
  return isinstance(allowed, list) and task_type in allowed
415
414
 
415
+ follow_up_label = "followUpTasks" if authoring_format == "json-v1" else "Follow Up Tasks"
416
+ origin_label = "origin" if authoring_format == "json-v1" else "Origin"
417
+ row_label = "array item(s)" if authoring_format == "json-v1" else "`- Item N` row(s)"
418
+ key_note = "" if authoring_format == "json-v1" else "(schema key; write its Title Case label) "
416
419
  rules: list[str] = []
417
420
  for branch in schema.get("allOf") or []:
418
421
  if not isinstance(branch, dict) or not _task_matches(branch.get("if")):
@@ -426,12 +429,12 @@ def follow_up_task_rules(schema: Mapping[str, Any], task_type: str) -> tuple[str
426
429
  ).get("const")
427
430
  if isinstance(min_items, int) and min_items > 0:
428
431
  rules.append(
429
- f"`Follow Up Tasks`: at least {min_items} `- Item N` row(s) for task "
432
+ f"`{follow_up_label}`: at least {min_items} {row_label} for task "
430
433
  f"type `{task_type}`; an empty list is refused."
431
434
  )
432
435
  if isinstance(origin, str) and origin:
433
436
  rules.append(
434
- f"`Follow Up Tasks`: one row must carry `Origin` `{origin}` — the "
437
+ f"`{follow_up_label}`: one row must carry `{origin_label}` `{origin}` — the "
435
438
  "next phase of this task."
436
439
  )
437
440
  row_schema = (schema.get("$defs") or {}).get("FollowUpRow") or {}
@@ -445,8 +448,8 @@ def follow_up_task_rules(schema: Mapping[str, Any], task_type: str) -> tuple[str
445
448
  for key, value in pinned.items():
446
449
  if isinstance(value, dict) and "const" in value:
447
450
  rules.append(
448
- f"`Follow Up Tasks`: the `{origin}` row's `{key}` "
449
- f"(schema key; write its Title Case label) is exactly "
451
+ f"`{follow_up_label}`: the `{origin}` row's `{key}` "
452
+ f"{key_note}is exactly "
450
453
  f"`{value['const']}`."
451
454
  )
452
455
  return tuple(rules)
@@ -492,19 +495,14 @@ def verdict_token_rule(schema: Mapping[str, Any], task_type: str) -> tuple[str,
492
495
  return _walk(dict(schema))
493
496
 
494
497
 
495
- def task_block_rules(schema: Mapping[str, Any], block_key: str) -> tuple[str, ...]:
496
- """최상위 필드(`properties[block_key]`)가 요구하는 모양을 한
497
- 객체당 한 줄의 저작 계약 문장으로 편다.
498
+ def task_block_rules(
499
+ schema: Mapping[str, Any], block_key: str, *, authoring_format: str = "markdown-v1",
500
+ ) -> tuple[str, ...]:
501
+ """Describe a top-level block using the declared format's value grammar.
498
502
 
499
- 리드는 report-writer 지시문을 쓸 때 블록 안쪽의 필수 필드·식별자 패턴·
500
- 정수 필드·고정 길이 배열을 알 길이 프롬프트 경로에 없어 스키마 JSON 을
501
- 손으로 파싱했고, 그래도 놓친 만큼 같은 리포트를 다시 썼다(2026-09-03 실측,
502
- dev-10626 implementation-option-selection: 네 회차). 여기서 뽑아 합성 묶음의
503
- 저작 계약에 싣는다. 필드가 없으면 빈 튜플이다.
504
-
505
- 경로는 스키마 키다(`rankedOptions[]` 는 `- Item N` 목록의 각 항목). 같은
506
- 정의(`$ref`)가 두 경로에 나오면 두 번째는 첫 경로를 가리킨다 — 랭킹 옵션과
507
- 감사 항목이 하위 구조 여섯 개를 공유한다.
503
+ Emit one rule per object using exact schema-key paths; [] denotes each
504
+ array item. Repeated references point to their first described path.
505
+ Schema values remain unchanged; only the authoring vocabulary varies.
508
506
  """
509
507
  root = dict(schema)
510
508
  block = (root.get("properties") or {}).get(block_key)
@@ -514,14 +512,14 @@ def task_block_rules(schema: Mapping[str, Any], block_key: str) -> tuple[str, ..
514
512
  described: dict[str, str] = {}
515
513
  resolved, _ = _resolved(root, block)
516
514
  if resolved.get("type") == "object" or "properties" in resolved:
517
- _describe_object(root, block, block_key, lines, described)
515
+ _describe_object(root, block, block_key, lines, described, authoring_format)
518
516
  else:
519
517
  nested: list[tuple[str, Any]] = []
520
- constraint = _describe_property(root, block, block_key, nested)
518
+ constraint = _describe_property(root, block, block_key, nested, authoring_format)
521
519
  if constraint:
522
520
  lines.append(f"`{block_key}`: {constraint}")
523
521
  for child_path, child in nested:
524
- _describe_object(root, child, child_path, lines, described)
522
+ _describe_object(root, child, child_path, lines, described, authoring_format)
525
523
  return tuple(lines)
526
524
 
527
525
 
@@ -558,6 +556,7 @@ def _resolved(root: dict, node: Any) -> tuple[dict, str | None]:
558
556
 
559
557
  def _describe_object(
560
558
  root: dict, node: Any, path: str, lines: list[str], described: dict[str, str],
559
+ authoring_format: str,
561
560
  ) -> None:
562
561
  schema, ref_name = _resolved(root, node)
563
562
  if ref_name and ref_name in described:
@@ -575,18 +574,19 @@ def _describe_object(
575
574
  parts.append("optional " + ", ".join(f"`{key}`" for key in optional))
576
575
  nested: list[tuple[str, Any]] = []
577
576
  for key, value in properties.items():
578
- constraint = _describe_property(root, value, f"{path}.{key}", nested)
577
+ constraint = _describe_property(root, value, f"{path}.{key}", nested, authoring_format)
579
578
  if constraint:
580
579
  parts.append(f"`{key}` {constraint}")
581
580
  lines.append(f"`{path}`: " + "; ".join(parts))
582
581
  for child_path, child in nested:
583
- _describe_object(root, child, child_path, lines, described)
582
+ _describe_object(root, child, child_path, lines, described, authoring_format)
584
583
 
585
584
 
586
585
  def _describe_property(
587
586
  root: dict, node: Any, path: str, nested: list[tuple[str, Any]],
587
+ authoring_format: str,
588
588
  ) -> str:
589
- """한 속성의 제약을 한 구절로. 객체 자식은 `nested` 에 넣어 자기 줄을 받는다."""
589
+ """Describe one field and queue nested objects for their own rule lines."""
590
590
  schema, _ref = _resolved(root, node)
591
591
  branches = schema.get("oneOf") or schema.get("anyOf") or []
592
592
  nullable = False
@@ -601,7 +601,8 @@ def _describe_property(
601
601
  if "null" in types:
602
602
  nullable = True
603
603
  types = [item for item in types if item != "null"]
604
- suffix = " or `_none_`" if nullable else ""
604
+ null_value = "`null`" if authoring_format == "json-v1" else "`_none_`"
605
+ suffix = f" or {null_value}" if nullable else ""
605
606
  if "const" in schema:
606
607
  return f"exactly `{schema['const']}`{suffix}"
607
608
  if isinstance(schema.get("enum"), list):
@@ -610,7 +611,7 @@ def _describe_property(
610
611
  nested.append((path, schema.get("__branch", node)))
611
612
  return f"object (see `{path}`){suffix}"
612
613
  if types == ["array"] or "items" in schema or "prefixItems" in schema:
613
- return _describe_array(root, schema, path, nested) + suffix
614
+ return _describe_array(root, schema, path, nested, authoring_format) + suffix
614
615
  if types == ["integer"]:
615
616
  return "integer" + _range(schema) + suffix
616
617
  if types == ["number"]:
@@ -625,11 +626,13 @@ def _describe_property(
625
626
 
626
627
  def _describe_array(
627
628
  root: dict, schema: dict, path: str, nested: list[tuple[str, Any]],
629
+ authoring_format: str,
628
630
  ) -> str:
629
631
  minimum = schema.get("minItems")
630
632
  maximum = schema.get("maxItems")
631
633
  if maximum == 0:
632
- return "must be empty (`> _none_`)"
634
+ empty_value = "[]" if authoring_format == "json-v1" else "> _none_"
635
+ return f"must be empty (`{empty_value}`)"
633
636
  if minimum is not None and minimum == maximum:
634
637
  size = f"exactly {maximum} items"
635
638
  else:
@@ -52,6 +52,16 @@ def value_lines(label: str, value: object) -> list[str]:
52
52
  return _value_lines(label, value, line)
53
53
 
54
54
 
55
+ def emit_result(payload: dict, *, text: bool, title: str) -> None:
56
+ """Print a command result as one JSON line, or as fixed text fields under `title`."""
57
+ if not text:
58
+ print(json.dumps(payload, ensure_ascii=False, allow_nan=False))
59
+ return
60
+ rows = [f"{title}\n", line("OK", payload["ok"])]
61
+ rows.extend(value_lines("Result", payload))
62
+ print("".join(rows), end="")
63
+
64
+
55
65
  def _quoted_scalar_line(label: str, value: object) -> str:
56
66
  return _line_prefix(label) + json.dumps(value, ensure_ascii=True) + "\n"
57
67
 
@@ -10,8 +10,7 @@ from pathlib import Path
10
10
  from typing import Any, Mapping
11
11
 
12
12
  from .convergence_store import write_json_atomic
13
- from .final_report_schema import load_schema_version
14
- from .report_narrative import parse_narrative, writer_owned_data
13
+ from .report_narrative import load_writer_input, writer_owned_data
15
14
  from .json_boundary import load_owned_object
16
15
  from .plan_item_evidence import dependency_scopes, reusable_item_ids
17
16
  from .plan_items import (
@@ -579,7 +578,7 @@ def _load_data(path: str, *, option: str) -> dict:
579
578
 
580
579
 
581
580
  _CLI_EPILOG = r"""Usage:
582
- okstra incremental-carry --prev-data <path> --cur-narrative <path> \
581
+ okstra incremental-carry --run-manifest <path> --prev-data <path> --cur-narrative <path> \
583
582
  --state <path> --prev-seq <str> --carry-stages <csv> \
584
583
  --reverify-stages <csv> --out-state <path>
585
584
  okstra incremental-carry --prev-data <path> --cur-data <path> \
@@ -600,7 +599,8 @@ def main(argv: list[str]) -> int:
600
599
  ap.add_argument("--prev-data", required=True, help="prior run final-report data.json")
601
600
  current = ap.add_mutually_exclusive_group(required=True)
602
601
  current.add_argument("--cur-data", help="historical v2 current data.json")
603
- current.add_argument("--cur-narrative", help="contract v3 current narrative Markdown")
602
+ current.add_argument("--cur-narrative", help="contract v3 current writer input")
603
+ ap.add_argument("--run-manifest", type=Path)
604
604
  ap.add_argument("--state", help="contract v3 convergence-owned plan state")
605
605
  ap.add_argument("--prev-seq", required=True, help="prior run seq, tagged onto carried items")
606
606
  ap.add_argument(
@@ -639,9 +639,8 @@ def main(argv: list[str]) -> int:
639
639
  if carry_stages is None or reverify_stages is None:
640
640
  raise CarryError("contract v3 carry requires both stage sets")
641
641
  try:
642
- narrative = parse_narrative(
643
- Path(args.cur_narrative).read_text(encoding="utf-8"),
644
- load_schema_version("3.0"),
642
+ narrative = load_writer_input(
643
+ Path(args.cur_narrative), run_manifest=args.run_manifest,
645
644
  )
646
645
  except (OSError, UnicodeError, ValueError) as exc:
647
646
  raise CarryError(f"--cur-narrative could not be read: {exc}") from exc
@@ -25,9 +25,11 @@ from .agent.invocation import (
25
25
  verify_agent_invocation,
26
26
  )
27
27
  from .path_hints import hydrate_active_run_context
28
+ from .coverage_census import CensusError
29
+ from .phases.improvement_discovery.resolved_census import prepare_resolved_lens_census
28
30
  from .verification_dispatch import VerificationDispatchError, seal_dispatch_generation
29
31
  from .verification_invocation import VerificationGenerationReference
30
- from .report_inputs import report_narrative_path, uses_report_contract_v3
32
+ from .report_inputs import report_authoring_format, report_narrative_path, uses_report_contract_v3
31
33
  from .report_synthesis_packet import (
32
34
  ReportSynthesisPacketError,
33
35
  materialize_report_synthesis_packet,
@@ -352,6 +354,11 @@ def _materialize_initial_prompts(
352
354
  _resolve_prompt_item(context, worker)
353
355
  for worker in request.workers
354
356
  ]
357
+ if any(item.plan.audience == "analysis" for item in resolved_items):
358
+ try:
359
+ prepare_resolved_lens_census(context.project_root, context.manifest)
360
+ except (CensusError, JsonBoundaryError, OSError, UnicodeError) as exc:
361
+ raise InitialPromptMaterializationError("required_input_missing", str(exc)) from exc
355
362
  items: list[_PromptItem] = []
356
363
  completed = False
357
364
  try:
@@ -785,7 +792,7 @@ def _report_writer_packet_source(
785
792
  if not _report_writer_reads_a_packet(context, plan):
786
793
  return None
787
794
  _, markdown_path = report_synthesis_packet_paths(
788
- _report_writer_narrative_path(context)
795
+ _report_writer_narrative_path(context), report_authoring_format(context.manifest),
789
796
  )
790
797
  return AgentInstructionSource(
791
798
  "project",