okstra 0.231.1 → 0.233.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (265) hide show
  1. package/README.md +19 -271
  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/memory/memory.mjs +9 -55
  10. package/dist/commands/memory/memory.mjs.map +1 -1
  11. package/dist/commands/trace/capacity.d.mts +12 -0
  12. package/dist/commands/trace/capacity.mjs +21 -0
  13. package/dist/commands/trace/capacity.mjs.map +1 -0
  14. package/dist/commands/trace/model.d.mts +89 -0
  15. package/dist/commands/trace/model.mjs +251 -0
  16. package/dist/commands/trace/model.mjs.map +1 -0
  17. package/dist/commands/trace/progression.d.mts +11 -0
  18. package/dist/commands/trace/progression.mjs +194 -0
  19. package/dist/commands/trace/progression.mjs.map +1 -0
  20. package/dist/commands/trace/review.d.mts +7 -0
  21. package/dist/commands/trace/review.mjs +51 -0
  22. package/dist/commands/trace/review.mjs.map +1 -0
  23. package/dist/commands/trace/task-link.d.mts +18 -0
  24. package/dist/commands/trace/task-link.mjs +72 -0
  25. package/dist/commands/trace/task-link.mjs.map +1 -0
  26. package/dist/commands/trace/trace.d.mts +1 -0
  27. package/dist/commands/trace/trace.mjs +293 -0
  28. package/dist/commands/trace/trace.mjs.map +1 -0
  29. package/dist/lib/bounded-file.d.mts +1 -0
  30. package/dist/lib/bounded-file.mjs +36 -0
  31. package/dist/lib/bounded-file.mjs.map +1 -0
  32. package/dist/lib/config-store.d.mts +34 -0
  33. package/dist/lib/config-store.mjs +70 -0
  34. package/dist/lib/config-store.mjs.map +1 -0
  35. package/dist/lib/file-lock.mjs +4 -5
  36. package/dist/lib/file-lock.mjs.map +1 -1
  37. package/dist/lib/input-limit.d.mts +4 -0
  38. package/dist/lib/input-limit.mjs +8 -0
  39. package/dist/lib/input-limit.mjs.map +1 -0
  40. package/dist/lib/memory-auto-register.d.mts +1 -0
  41. package/dist/lib/memory-auto-register.mjs +98 -0
  42. package/dist/lib/memory-auto-register.mjs.map +1 -0
  43. package/dist/lib/memory-entry-contract.d.mts +12 -0
  44. package/dist/lib/memory-entry-contract.mjs +46 -0
  45. package/dist/lib/memory-entry-contract.mjs.map +1 -0
  46. package/dist/lib/python-helper.d.mts +1 -1
  47. package/dist/lib/python-helper.mjs +3 -2
  48. package/dist/lib/python-helper.mjs.map +1 -1
  49. package/dist/lib/record-secrets.d.mts +1 -0
  50. package/dist/lib/record-secrets.mjs +28 -0
  51. package/dist/lib/record-secrets.mjs.map +1 -0
  52. package/dist/lib/report-language-tag.d.mts +1 -0
  53. package/dist/lib/report-language-tag.mjs +4 -0
  54. package/dist/lib/report-language-tag.mjs.map +1 -0
  55. package/dist/lib/report-language.d.mts +1 -0
  56. package/dist/lib/report-language.mjs +50 -0
  57. package/dist/lib/report-language.mjs.map +1 -0
  58. package/dist/lib/skill-catalog.mjs +3 -0
  59. package/dist/lib/skill-catalog.mjs.map +1 -1
  60. package/dist/lib/types.d.mts +2 -1
  61. package/docs/architecture/storage-model.md +163 -5
  62. package/docs/architecture.md +17 -4
  63. package/docs/cli.md +511 -0
  64. package/docs/contributor-change-matrix.md +1 -2
  65. package/docs/project-structure-overview.md +33 -42
  66. package/package.json +1 -1
  67. package/runtime/BUILD.json +2 -2
  68. package/runtime/agents/common.json +8 -8
  69. package/runtime/agents/operations/trace-interface-review.json +6 -0
  70. package/runtime/agents/operations/trace-scope-review.json +6 -0
  71. package/runtime/agents/roles/verifier.json +2 -4
  72. package/runtime/bin/okstra-provider-exec.py +10 -4
  73. package/runtime/prompts/coding-preflight/architectures/hexagonal.md +23 -30
  74. package/runtime/prompts/coding-preflight/authoring-checks.md +17 -0
  75. package/runtime/prompts/coding-preflight/clean-code.md +88 -286
  76. package/runtime/prompts/coding-preflight/frameworks/node-server.md +2 -3
  77. package/runtime/prompts/coding-preflight/languages/java.md +3 -5
  78. package/runtime/prompts/coding-preflight/languages/javascript-typescript.md +5 -12
  79. package/runtime/prompts/coding-preflight/languages/kotlin.md +2 -4
  80. package/runtime/prompts/coding-preflight/languages/python.md +2 -7
  81. package/runtime/prompts/coding-preflight/languages/rust.md +2 -8
  82. package/runtime/prompts/coding-preflight/languages/sql.md +2 -4
  83. package/runtime/prompts/coding-preflight/overview.md +25 -38
  84. package/runtime/prompts/coding-preflight/review-rules.json +30 -0
  85. package/runtime/prompts/duties/code-reviewer.json +15 -18
  86. package/runtime/prompts/duties/implementation-verifier.json +1 -0
  87. package/runtime/prompts/duties/interface-reviewer.json +32 -0
  88. package/runtime/prompts/host-orchestration/README.md +18 -9
  89. package/runtime/prompts/launch.template.md +3 -2
  90. package/runtime/prompts/lead/context-loader.md +2 -0
  91. package/runtime/prompts/lead/okstra-lead-contract.md +7 -7
  92. package/runtime/prompts/lead/report-writer.md +6 -6
  93. package/runtime/prompts/profiles/_coding-conventions-preflight.md +41 -6
  94. package/runtime/prompts/profiles/_common-contract.md +1 -1
  95. package/runtime/python/okstra_ctl/agent/invocation.py +122 -36
  96. package/runtime/python/okstra_ctl/agent/prompt_cli/cli.py +72 -26
  97. package/runtime/python/okstra_ctl/agent/prompt_cli/corrections.py +23 -8
  98. package/runtime/python/okstra_ctl/agent/prompt_cli/materialize.py +58 -14
  99. package/runtime/python/okstra_ctl/agent/prompt_cli/results.py +8 -11
  100. package/runtime/python/okstra_ctl/agent/standalone.py +15 -0
  101. package/runtime/python/okstra_ctl/analysis_packet.py +24 -30
  102. package/runtime/python/okstra_ctl/attempt_evidence.py +10 -0
  103. package/runtime/python/okstra_ctl/code_review_census.py +162 -7
  104. package/runtime/python/okstra_ctl/code_review_coverage.py +4 -274
  105. package/runtime/python/okstra_ctl/code_review_integrity.py +154 -0
  106. package/runtime/python/okstra_ctl/code_review_invocation.py +212 -0
  107. package/runtime/python/okstra_ctl/code_review_prepare.py +381 -0
  108. package/runtime/python/okstra_ctl/code_review_run.py +384 -0
  109. package/runtime/python/okstra_ctl/code_review_scope.py +49 -9
  110. package/runtime/python/okstra_ctl/code_review_supervisor.py +41 -0
  111. package/runtime/python/okstra_ctl/code_review_target.py +212 -13
  112. package/runtime/python/okstra_ctl/consumers.py +12 -9
  113. package/runtime/python/okstra_ctl/coverage_census.py +11 -2
  114. package/runtime/python/okstra_ctl/design_review.py +207 -0
  115. package/runtime/python/okstra_ctl/design_review_evidence.py +297 -0
  116. package/runtime/python/okstra_ctl/design_snapshot.py +16 -9
  117. package/runtime/python/okstra_ctl/direct_work.py +45 -3
  118. package/runtime/python/okstra_ctl/dispatch_core.py +31 -15
  119. package/runtime/python/okstra_ctl/dispatch_state.py +9 -2
  120. package/runtime/python/okstra_ctl/doctor.py +8 -25
  121. package/runtime/python/okstra_ctl/domain/role.py +1 -0
  122. package/runtime/python/okstra_ctl/doyouknow/__init__.py +9 -0
  123. package/runtime/python/okstra_ctl/doyouknow/cli.py +91 -0
  124. package/runtime/python/okstra_ctl/doyouknow/config.py +58 -0
  125. package/runtime/python/okstra_ctl/doyouknow/contracts.py +184 -0
  126. package/runtime/python/okstra_ctl/doyouknow/identity.py +22 -0
  127. package/runtime/python/okstra_ctl/doyouknow/paths.py +22 -0
  128. package/runtime/python/okstra_ctl/doyouknow/pending.py +72 -0
  129. package/runtime/python/okstra_ctl/doyouknow/registration.py +260 -0
  130. package/runtime/python/okstra_ctl/doyouknow/source_contracts.py +128 -0
  131. package/runtime/python/okstra_ctl/doyouknow/source_store.py +172 -0
  132. package/runtime/python/okstra_ctl/doyouknow/sources/io.py +36 -0
  133. package/runtime/python/okstra_ctl/doyouknow/sources/manager.py +300 -0
  134. package/runtime/python/okstra_ctl/doyouknow/sources/memory.py +179 -0
  135. package/runtime/python/okstra_ctl/doyouknow/sources/task.py +95 -0
  136. package/runtime/python/okstra_ctl/doyouknow/store.py +260 -0
  137. package/runtime/python/okstra_ctl/doyouknow/sync.py +58 -0
  138. package/runtime/python/okstra_ctl/execution_mutation_audit.py +18 -2
  139. package/runtime/python/okstra_ctl/file_size_cap.py +3 -4
  140. package/runtime/python/okstra_ctl/final_report_schema.py +37 -34
  141. package/runtime/python/okstra_ctl/incremental_carry.py +6 -7
  142. package/runtime/python/okstra_ctl/initial_prompt_materialization.py +9 -2
  143. package/runtime/python/okstra_ctl/json_boundary.py +51 -5
  144. package/runtime/python/okstra_ctl/jsonl.py +21 -0
  145. package/runtime/python/okstra_ctl/manager_cli.py +148 -1
  146. package/runtime/python/okstra_ctl/manager_journal.py +126 -0
  147. package/runtime/python/okstra_ctl/manager_launch.py +3 -3
  148. package/runtime/python/okstra_ctl/manager_log.py +221 -0
  149. package/runtime/python/okstra_ctl/manager_paths.py +8 -0
  150. package/runtime/python/okstra_ctl/manager_registration.py +29 -0
  151. package/runtime/python/okstra_ctl/manager_resume.py +59 -0
  152. package/runtime/python/okstra_ctl/manager_split.py +2 -2
  153. package/runtime/python/okstra_ctl/manager_store.py +116 -17
  154. package/runtime/python/okstra_ctl/manager_sync.py +45 -25
  155. package/runtime/python/okstra_ctl/manager_view.py +35 -2
  156. package/runtime/python/okstra_ctl/material.py +2 -0
  157. package/runtime/python/okstra_ctl/model_cli.py +64 -14
  158. package/runtime/python/okstra_ctl/model_defaults.py +22 -0
  159. package/runtime/python/okstra_ctl/model_io/renderers.py +16 -2
  160. package/runtime/python/okstra_ctl/model_io_cli.py +7 -1
  161. package/runtime/python/okstra_ctl/operation_invocation.py +207 -28
  162. package/runtime/python/okstra_ctl/path_hints.py +14 -3
  163. package/runtime/python/okstra_ctl/paths.py +6 -1
  164. package/runtime/python/okstra_ctl/phases/catalog.py +24 -7
  165. package/runtime/python/okstra_ctl/phases/final_verification/validation.py +20 -0
  166. package/runtime/python/okstra_ctl/phases/implementation/host-rules.md +3 -3
  167. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-deliverable.md +10 -0
  168. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-diff-review.md +23 -8
  169. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-self-check.md +6 -4
  170. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-verifier.md +38 -10
  171. package/runtime/python/okstra_ctl/phases/implementation/report_assets/implementation.template.html +13 -0
  172. package/runtime/python/okstra_ctl/phases/implementation/spec.md +25 -0
  173. package/runtime/python/okstra_ctl/phases/implementation/validation.py +6 -0
  174. package/runtime/python/okstra_ctl/phases/implementation_option_selection/profile.md +1 -1
  175. package/runtime/python/okstra_ctl/phases/implementation_option_selection/votes.py +11 -11
  176. package/runtime/python/okstra_ctl/phases/implementation_planning/authoring.py +16 -9
  177. package/runtime/python/okstra_ctl/phases/implementation_planning/host-rules.md +3 -6
  178. package/runtime/python/okstra_ctl/phases/implementation_planning/instructions/plan-body-verification.md +12 -10
  179. package/runtime/python/okstra_ctl/phases/implementation_planning/profile.md +6 -6
  180. package/runtime/python/okstra_ctl/phases/improvement_discovery/lenses.py +12 -0
  181. package/runtime/python/okstra_ctl/phases/improvement_discovery/profile.md +7 -6
  182. package/runtime/python/okstra_ctl/phases/improvement_discovery/resolved_census.py +159 -0
  183. package/runtime/python/okstra_ctl/phases/improvement_discovery/spec.md +5 -2
  184. package/runtime/python/okstra_ctl/phases/improvement_discovery/validation.py +21 -7
  185. package/runtime/python/okstra_ctl/phases/release_handoff/boundary.json +1 -1
  186. package/runtime/python/okstra_ctl/phases/release_handoff/profile.md +4 -1
  187. package/runtime/python/okstra_ctl/plan_verify_cli.py +6 -4
  188. package/runtime/python/okstra_ctl/render.py +28 -2
  189. package/runtime/python/okstra_ctl/report_assembly.py +53 -11
  190. package/runtime/python/okstra_ctl/report_contract.py +26 -0
  191. package/runtime/python/okstra_ctl/report_corrections.py +36 -20
  192. package/runtime/python/okstra_ctl/report_inputs.py +1 -0
  193. package/runtime/python/okstra_ctl/report_language.py +4 -1
  194. package/runtime/python/okstra_ctl/report_narrative.py +182 -7
  195. package/runtime/python/okstra_ctl/report_projections.py +64 -18
  196. package/runtime/python/okstra_ctl/report_synthesis_packet.py +97 -38
  197. package/runtime/python/okstra_ctl/review_policy.py +359 -0
  198. package/runtime/python/okstra_ctl/review_verdicts.py +291 -0
  199. package/runtime/python/okstra_ctl/run.py +67 -36
  200. package/runtime/python/okstra_ctl/run_context.py +10 -1
  201. package/runtime/python/okstra_ctl/set_work_status.py +4 -15
  202. package/runtime/python/okstra_ctl/stage_done.py +11 -0
  203. package/runtime/python/okstra_ctl/standalone_review_audit.py +28 -0
  204. package/runtime/python/okstra_ctl/task_list_cli.py +34 -8
  205. package/runtime/python/okstra_ctl/task_query.py +239 -0
  206. package/runtime/python/okstra_ctl/trace_review.py +264 -0
  207. package/runtime/python/okstra_ctl/trace_tasks.py +197 -0
  208. package/runtime/python/okstra_ctl/user_authorization.py +14 -0
  209. package/runtime/python/okstra_ctl/verification_generation.py +23 -1
  210. package/runtime/python/okstra_ctl/verification_input_types.py +15 -1
  211. package/runtime/python/okstra_ctl/verification_inputs.py +28 -6
  212. package/runtime/python/okstra_ctl/verification_invocation.py +7 -1
  213. package/runtime/python/okstra_ctl/verification_target.py +2 -0
  214. package/runtime/python/okstra_ctl/wizard/confirmation.py +7 -3
  215. package/runtime/python/okstra_ctl/wizard/launch.py +52 -0
  216. package/runtime/python/okstra_ctl/wizard/launch_cli.py +39 -0
  217. package/runtime/python/okstra_ctl/wizard/outcome.py +17 -16
  218. package/runtime/python/okstra_ctl/wizard/registry.py +1 -1
  219. package/runtime/python/okstra_ctl/wizard/render.py +8 -0
  220. package/runtime/python/okstra_ctl/wizard/state.py +2 -1
  221. package/runtime/python/okstra_ctl/worker_prompt_headers.py +24 -9
  222. package/runtime/python/okstra_ctl/worker_runner.py +66 -10
  223. package/runtime/python/okstra_ctl/write_policy.py +34 -1
  224. package/runtime/python/okstra_project/__init__.py +2 -0
  225. package/runtime/python/okstra_project/dirs.py +18 -0
  226. package/runtime/python/okstra_project/state.py +45 -20
  227. package/runtime/python/okstra_token_usage/blocks.py +74 -0
  228. package/runtime/python/okstra_token_usage/cli.py +23 -10
  229. package/runtime/python/okstra_token_usage/collect.py +25 -22
  230. package/runtime/python/okstra_token_usage/policy.py +193 -0
  231. package/runtime/schemas/doyouknow-config-v1.schema.json +20 -0
  232. package/runtime/schemas/doyouknow-v1.schema.json +65 -0
  233. package/runtime/schemas/final-report-v2.0.schema.json +157 -0
  234. package/runtime/schemas/final-report-v3.0.schema.json +157 -0
  235. package/runtime/schemas/memory-entry-contract-v1.json +11 -0
  236. package/runtime/schemas/record-secret-patterns.json +41 -0
  237. package/runtime/schemas/report-synthesis-packet-v1.0.schema.json +1 -1
  238. package/runtime/skills/_fragments/wizard-confirm-step.md +1 -1
  239. package/runtime/skills/_fragments/wizard-preflight.md +1 -1
  240. package/runtime/skills/_fragments/wizard-prompt-loop.md +3 -5
  241. package/runtime/skills/_fragments/wizard-relay-protocol.md +1 -1
  242. package/runtime/skills/_fragments/wizard-render-bundle.md +15 -29
  243. package/runtime/skills/okstra-brief-gen/SKILL.md +7 -7
  244. package/runtime/skills/okstra-brief-gen/references/tracker-recursion.md +1 -1
  245. package/runtime/skills/okstra-code-review/SKILL.md +92 -136
  246. package/runtime/skills/okstra-code-review/references/census-rules.md +29 -105
  247. package/runtime/skills/okstra-code-review/references/review-calibration.md +37 -61
  248. package/runtime/skills/okstra-discussion/SKILL.md +22 -38
  249. package/runtime/skills/okstra-explain-flow/SKILL.md +6 -2
  250. package/runtime/skills/okstra-manager/SKILL.md +31 -0
  251. package/runtime/skills/okstra-memory/SKILL.md +8 -1
  252. package/runtime/skills/okstra-pr-gen/SKILL.md +1 -1
  253. package/runtime/skills/okstra-run/SKILL.md +55 -183
  254. package/runtime/skills/okstra-schedule-gen/SKILL.md +9 -13
  255. package/runtime/skills/okstra-setup/SKILL.md +3 -2
  256. package/runtime/skills/okstra-setup/references/project-config.md +2 -4
  257. package/runtime/skills/okstra-tdd/SKILL.md +187 -0
  258. package/runtime/skills/okstra-user-response/SKILL.md +4 -2
  259. package/runtime/templates/implementation-worker-preamble.md +4 -9
  260. package/runtime/templates/manager/view.template.html +4 -0
  261. package/runtime/templates/report-writer-prompt-preamble.md +15 -3
  262. package/runtime/templates/trace/trace.template.md +42 -0
  263. package/runtime/templates/worker-prompt-preamble.md +4 -12
  264. package/runtime/validators/checks/fixtures-02.py +25 -33
  265. package/runtime/validators/validate-run.py +107 -38
@@ -0,0 +1,260 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ import sqlite3
6
+ import os
7
+ import tempfile
8
+ import time
9
+ from collections.abc import Iterator
10
+ from contextlib import closing, contextmanager
11
+ from datetime import datetime, timezone
12
+ from pathlib import Path
13
+
14
+ from .contracts import DoyouknowError, Envelope, canonical_json, validate_envelope
15
+ from .identity import node_id, stable_id
16
+ from .paths import database_path, ensure_storage_root, require_database_location as _require_database_location
17
+
18
+ SCHEMA_VERSION = 2
19
+ SQLITE_TIMEOUT_SECONDS = 5
20
+ SCHEMA_STATEMENTS = (
21
+ """create table if not exists node (
22
+ id text primary key,
23
+ kind text not null,
24
+ scope text not null,
25
+ canonical_key text not null,
26
+ title text not null,
27
+ unique(kind, scope, canonical_key)
28
+ )""",
29
+ """create table if not exists record (
30
+ id text primary key references node(id),
31
+ latest_revision text
32
+ )""",
33
+ """create table if not exists revision (
34
+ id text primary key,
35
+ record_id text not null references record(id),
36
+ previous_revision text references revision(id),
37
+ content_digest text not null,
38
+ source_kind text not null,
39
+ source_id text not null,
40
+ source_revision text not null,
41
+ created_at text not null,
42
+ payload text not null,
43
+ unique(record_id, source_kind, source_id, source_revision)
44
+ )""",
45
+ """create table if not exists relation (
46
+ id text primary key,
47
+ revision_id text not null references revision(id),
48
+ from_node text not null references node(id),
49
+ to_node text not null references node(id),
50
+ kind text not null,
51
+ reason text not null,
52
+ evidence text not null,
53
+ standing text not null
54
+ check(standing in ('observed', 'user-stated', 'candidate'))
55
+ )""",
56
+ """create table if not exists request (
57
+ id text primary key,
58
+ input_digest text not null,
59
+ record_id text not null references record(id),
60
+ revision_id text not null references revision(id)
61
+ )""",
62
+ )
63
+
64
+
65
+ def _initialize_database(connection: sqlite3.Connection, path: Path) -> None:
66
+ version = connection.execute("pragma user_version").fetchone()[0]
67
+ if version not in (0, 1, SCHEMA_VERSION):
68
+ raise DoyouknowError(f"unsupported doyouknow database version: {version}")
69
+ if version == 1:
70
+ _backup_database(path)
71
+ for statement in SCHEMA_STATEMENTS:
72
+ connection.execute(statement)
73
+ from .source_store import SOURCE_SCHEMA_STATEMENTS
74
+
75
+ for statement in SOURCE_SCHEMA_STATEMENTS:
76
+ connection.execute(statement)
77
+ connection.execute(f"pragma user_version = {SCHEMA_VERSION}")
78
+
79
+
80
+ def _backup_database(path: Path) -> Path:
81
+ descriptor, name = tempfile.mkstemp(prefix="graph-v1-", suffix=".sqlite3", dir=path.parent)
82
+ os.close(descriptor)
83
+ backup = Path(name)
84
+ deadline = time.monotonic() + SQLITE_TIMEOUT_SECONDS
85
+
86
+ def check_deadline(status: int, remaining: int, total: int) -> None:
87
+ if time.monotonic() >= deadline:
88
+ raise DoyouknowError("doyouknow database backup timed out")
89
+
90
+ try:
91
+ with closing(sqlite3.connect(path.as_uri() + "?mode=ro", uri=True, timeout=SQLITE_TIMEOUT_SECONDS)) as source:
92
+ with closing(sqlite3.connect(backup)) as destination:
93
+ source.backup(destination, pages=128, progress=check_deadline, sleep=0.01)
94
+ except (OSError, sqlite3.Error, ValueError):
95
+ backup.unlink(missing_ok=True)
96
+ raise
97
+ return backup
98
+
99
+
100
+ def _content_payload(envelope: Envelope) -> dict:
101
+ return {key: value for key, value in envelope.items() if key not in {"requestId", "expectedPreviousRevision"}}
102
+
103
+
104
+ def _digest(value: object) -> str:
105
+ return hashlib.sha256(canonical_json(value).encode("utf-8")).hexdigest()
106
+
107
+
108
+ def capture_record(envelope: Envelope, *, home: Path | None = None) -> dict:
109
+ return _persist_record(validate_envelope(envelope), database_path(home))
110
+
111
+
112
+ def ingest_source(envelope: Envelope, *, home: Path | None = None) -> dict:
113
+ return _persist_record(validate_envelope(envelope), database_path(home))
114
+
115
+
116
+ def _persist_record(envelope: Envelope, path: Path) -> dict:
117
+ with write_connection(path) as connection:
118
+ result = _write_record(connection, envelope)
119
+ return {"ok": True, **result, "path": str(path)}
120
+
121
+
122
+ @contextmanager
123
+ def write_connection(path: Path) -> Iterator[sqlite3.Connection]:
124
+ _require_database_location(path)
125
+ ensure_storage_root(path.parent)
126
+ try:
127
+ with closing(sqlite3.connect(path, timeout=SQLITE_TIMEOUT_SECONDS, isolation_level=None)) as connection:
128
+ connection.execute("pragma foreign_keys = on")
129
+ connection.execute("begin immediate")
130
+ try:
131
+ _initialize_database(connection, path)
132
+ yield connection
133
+ connection.commit()
134
+ except (sqlite3.Error, ValueError):
135
+ connection.rollback()
136
+ raise
137
+ except sqlite3.Error as exc:
138
+ raise DoyouknowError(f"doyouknow storage failed: {exc}") from exc
139
+
140
+
141
+ def _write_record(connection: sqlite3.Connection, envelope: Envelope) -> dict:
142
+ record_id = stable_id("record", envelope["scope"], envelope["recordKey"])
143
+ request_id = stable_id("request", envelope["scope"], envelope["requestId"])
144
+ input_digest = _digest(envelope)
145
+ previous = _replayed_request(connection, request_id, input_digest)
146
+ if previous is not None:
147
+ return previous
148
+ payload = _content_payload(envelope)
149
+ digest = _digest(payload)
150
+ existing = _source_revision(connection, record_id, envelope)
151
+ if existing is not None:
152
+ if existing[1] != digest:
153
+ raise DoyouknowError("source revision already holds different content")
154
+ if existing[2] != envelope["expectedPreviousRevision"]:
155
+ raise DoyouknowError("source revision has a different previous revision")
156
+ result = {"recordId": record_id, "revisionId": existing[0], "created": False}
157
+ else:
158
+ result = _append_revision(connection, envelope, record_id, payload, digest)
159
+ connection.execute(
160
+ "insert into request (id, input_digest, record_id, revision_id) values (?, ?, ?, ?)",
161
+ (request_id, input_digest, record_id, result["revisionId"]),
162
+ )
163
+ return result
164
+
165
+
166
+ def _replayed_request(
167
+ connection: sqlite3.Connection, request_id: str, digest: str,
168
+ ) -> dict | None:
169
+ row = connection.execute(
170
+ "select input_digest, record_id, revision_id from request where id = ?", (request_id,),
171
+ ).fetchone()
172
+ if row is None:
173
+ return None
174
+ if row[0] != digest:
175
+ raise DoyouknowError("request id already holds a different input")
176
+ return {"recordId": row[1], "revisionId": row[2], "created": False}
177
+
178
+
179
+ def _source_revision(
180
+ connection: sqlite3.Connection, record_id: str, envelope: Envelope,
181
+ ) -> tuple | None:
182
+ source = envelope["source"]
183
+ return connection.execute(
184
+ "select id, content_digest, previous_revision from revision where record_id = ? and source_kind = ? and source_id = ? and source_revision = ?",
185
+ (record_id, source["kind"], source["id"], source["revision"]),
186
+ ).fetchone()
187
+
188
+
189
+ def _append_revision(
190
+ connection: sqlite3.Connection, envelope: Envelope, record_id: str,
191
+ payload: dict, digest: str,
192
+ ) -> dict:
193
+ row = connection.execute("select latest_revision from record where id = ?", (record_id,)).fetchone()
194
+ previous = row[0] if row else None
195
+ if previous != envelope["expectedPreviousRevision"]:
196
+ raise DoyouknowError("record has a different latest revision")
197
+ _insert_node(connection, record_id, "record", envelope["scope"], envelope["recordKey"], envelope["record"]["title"])
198
+ connection.execute("insert into record (id) values (?) on conflict(id) do nothing", (record_id,))
199
+ revision_id = stable_id("revision", record_id, envelope["requestId"])
200
+ source = envelope["source"]
201
+ connection.execute(
202
+ "insert into revision (id, record_id, previous_revision, content_digest, source_kind, source_id, source_revision, created_at, payload) values (?, ?, ?, ?, ?, ?, ?, ?, ?)",
203
+ (revision_id, record_id, previous, digest, source["kind"], source["id"], source["revision"], datetime.now(timezone.utc).isoformat(), canonical_json(payload)),
204
+ )
205
+ _insert_graph(connection, envelope, record_id, revision_id)
206
+ connection.execute("update record set latest_revision = ? where id = ?", (revision_id, record_id))
207
+ return {"recordId": record_id, "revisionId": revision_id, "created": True}
208
+
209
+
210
+ def _insert_node(
211
+ connection: sqlite3.Connection, identity: str, kind: str, scope: str,
212
+ key: str, title: str,
213
+ ) -> None:
214
+ connection.execute(
215
+ "insert into node (id, kind, scope, canonical_key, title) values (?, ?, ?, ?, ?) on conflict(id) do nothing",
216
+ (identity, kind, scope, key, title),
217
+ )
218
+
219
+
220
+ def _insert_graph(
221
+ connection: sqlite3.Connection, envelope: Envelope, record_id: str,
222
+ revision_id: str,
223
+ ) -> None:
224
+ identities = {"$record": record_id}
225
+ for node in envelope["nodes"]:
226
+ identity = node_id(node)
227
+ _insert_node(connection, identity, node["kind"], node["scope"], node["key"], node["title"])
228
+ identities[node.get("ref", node["key"])] = identity
229
+ for index, relation in enumerate(envelope["relations"]):
230
+ connection.execute(
231
+ "insert into relation (id, revision_id, from_node, to_node, kind, reason, evidence, standing) values (?, ?, ?, ?, ?, ?, ?, ?)",
232
+ (stable_id("relation", revision_id, str(index)), revision_id, identities[relation["from"]], identities[relation["to"]], relation["kind"], relation["reason"], canonical_json(relation["evidence"]), relation["standing"]),
233
+ )
234
+
235
+
236
+ def show_record(record_id: str, *, home: Path | None = None) -> dict:
237
+ path = database_path(home)
238
+ _require_database_location(path)
239
+ if not path.is_file():
240
+ raise DoyouknowError("doyouknow record was not found")
241
+ try:
242
+ with closing(sqlite3.connect(path.as_uri() + "?mode=ro", uri=True, timeout=SQLITE_TIMEOUT_SECONDS)) as connection:
243
+ connection.execute("begin")
244
+ version = connection.execute("pragma user_version").fetchone()[0]
245
+ if version not in (1, SCHEMA_VERSION):
246
+ raise DoyouknowError(f"unsupported doyouknow database version: {version}")
247
+ return _read_record(connection, record_id, path)
248
+ except sqlite3.Error as exc:
249
+ raise DoyouknowError(f"doyouknow lookup failed: {exc}") from exc
250
+
251
+
252
+ def _read_record(connection: sqlite3.Connection, record_id: str, path: Path) -> dict:
253
+ record = connection.execute("select latest_revision from record where id = ?", (record_id,)).fetchone()
254
+ if record is None:
255
+ raise DoyouknowError("doyouknow record was not found")
256
+ rows = connection.execute(
257
+ "select id, previous_revision, created_at, payload from revision where record_id = ? order by rowid", (record_id,),
258
+ ).fetchall()
259
+ revisions = [{"revisionId": row[0], "previousRevision": row[1], "createdAt": row[2], **json.loads(row[3])} for row in rows]
260
+ return {"ok": True, "recordId": record_id, "revisionId": record[0], "revisions": revisions, "path": str(path)}
@@ -0,0 +1,58 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Iterator
4
+ from functools import partial
5
+ from pathlib import Path
6
+
7
+ from ..json_boundary import JsonBoundaryError
8
+ from .config import SourceConfig, load_config
9
+ from .contracts import DoyouknowError
10
+ from .identity import stable_id
11
+ from .registration import retry_pending, validate_source_and_update_refusal_cache
12
+ from .source_contracts import SourceDomain, SourceKind, SourceScan
13
+ from .source_store import apply_source_scan
14
+ from .sources.manager import scan_managers
15
+ from .sources.memory import scan_memory_sources
16
+ from .sources.task import scan_project_tasks
17
+ from .store import database_path
18
+
19
+
20
+ def _source_scans(home: Path, settings: SourceConfig) -> Iterator[SourceScan]:
21
+ enabled = settings["sources"]
22
+ gate = partial(validate_source_and_update_refusal_cache, home=home)
23
+ if "memory" in enabled:
24
+ yield scan_memory_sources(home, settings, gate=gate)
25
+ if "manager" in enabled or "task" in enabled:
26
+ managers, projects = scan_managers(home, settings, gate=gate)
27
+ yield from managers
28
+ 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)
37
+
38
+
39
+ def sync_sources(*, home: Path | None = None, source: SourceKind | None = None) -> dict:
40
+ root = database_path(home).parent.parent
41
+ settings = load_config(home=root)
42
+ if source is not None:
43
+ settings = {**settings, "sources": [source] if source in settings["sources"] else []}
44
+ pending = retry_pending(home=root, source=source, manual=True)
45
+ results = []
46
+ for scan in _source_scans(root, settings):
47
+ domain_id = stable_id("source-domain", scan.domain.kind, scan.domain.owner_id)
48
+ try:
49
+ if scan.domain.kind in settings["sources"]:
50
+ result = apply_source_scan(scan, home=root)
51
+ else:
52
+ result = {"status": scan.status, "registered": 0, "errors": list(scan.errors)}
53
+ except (DoyouknowError, JsonBoundaryError, OSError):
54
+ result = {"status": "unavailable", "registered": 0, "errors": ["source-registration-failed"]}
55
+ results.append({"kind": scan.domain.kind, "domainId": domain_id, **result})
56
+ return {"ok": pending["ok"] and not pending["truncated"] and all(row["status"] == "complete" for row in results),
57
+ "registered": sum(row["registered"] for row in results), "results": results,
58
+ "pendingRetry": pending}
@@ -263,7 +263,7 @@ class ExecutionMutationAudit:
263
263
  # Reported and, through `_retry_allowed`, load-bearing: a stat-cache
264
264
  # refresh must not read as "this worker touched Git" and must not
265
265
  # withhold the retry a worker that failed for another reason is owed.
266
- git_changed = _stable_git_projection(before) != _stable_git_projection(after)
266
+ git_changed = _git_projection_changed(before, after)
267
267
  violations = _policy_violations(
268
268
  before,
269
269
  after,
@@ -346,6 +346,9 @@ def _artifact_observation_roots(policies: Sequence[WritePolicy]) -> tuple[str, .
346
346
  roots: set[str] = set()
347
347
  for path in _allowed_artifact_paths(policies):
348
348
  parts = Path(path).parts
349
+ if parts[:3] == (".okstra", "agent-invocations", "code-review"):
350
+ roots.add(Path(*parts[:3]).as_posix())
351
+ continue
349
352
  if len(parts) < 5 or parts[:2] != (".okstra", "tasks"):
350
353
  continue
351
354
  if parts[4] == "qa":
@@ -808,6 +811,9 @@ def _git_projection(root: Path) -> dict[str, Any]:
808
811
  "gitDir": str(git_dir.resolve()),
809
812
  "gitCommonDir": str(common_dir.resolve()),
810
813
  "indexDigest": _optional_file_digest(index_path),
814
+ "indexContentDigest": "sha256:" + hashlib.sha256(
815
+ _git_output(root, "ls-files", "--stage", "-z").encode("utf-8")
816
+ ).hexdigest(),
811
817
  "stagedPaths": sorted(_git_changed_paths(root, "--cached")),
812
818
  "worktreeRegistration": _worktree_registration(root),
813
819
  "reflogDigest": _reflog_digest(root),
@@ -1032,7 +1038,7 @@ def _policy_violations(
1032
1038
  ) -> list[str]:
1033
1039
  if all(policy.source_mode == "source-readonly" for policy in policies):
1034
1040
  failures = ["readonly source changed"] if source_changes else []
1035
- if _stable_git_projection(before) != _stable_git_projection(after):
1041
+ if _git_projection_changed(before, after):
1036
1042
  failures.append("gitPolicy disabled but Git projection changed")
1037
1043
  return failures
1038
1044
  policy = next(row for row in policies if row.source_mode == "project-mutation")
@@ -1064,6 +1070,16 @@ def _stable_git_projection(snapshot: MutationSnapshot) -> dict[str, Any]:
1064
1070
  }
1065
1071
 
1066
1072
 
1073
+ def _git_projection_changed(before: MutationSnapshot, after: MutationSnapshot) -> bool:
1074
+ old = _stable_git_projection(before)
1075
+ current = _stable_git_projection(after)
1076
+ # Historical snapshots cannot establish the semantic index content they
1077
+ # did not capture. Preserve their original observation coverage on resume.
1078
+ if "indexContentDigest" not in old:
1079
+ current.pop("indexContentDigest", None)
1080
+ return old != current
1081
+
1082
+
1067
1083
  def _source_policy_failures(
1068
1084
  policy: WritePolicy,
1069
1085
  changed: set[str],
@@ -122,8 +122,7 @@ def _breach(before: int | None, after: int, threshold: int) -> str:
122
122
  if before <= threshold:
123
123
  return f"crossed {threshold}"
124
124
  if threshold == FILE_LINE_LIMIT:
125
- # stage base 에서 이미 한도를 넘던 파일은 이 stage 가 만든 것이 아니고, 계획이 그 줄의
126
- # 이동을 금지할 수 있다. 그래서 성장은 차단하지 않고 권고(목표치)로 넘긴다.
125
+ # Size alone cannot establish whether this change adds an unrelated responsibility.
127
126
  return ""
128
127
  return f"grew a file over {threshold}" if after > before else ""
129
128
 
@@ -172,7 +171,7 @@ def _planned_files(planning: Mapping[str, Any], project_root: Path) -> dict[str,
172
171
 
173
172
 
174
173
  def planned_file_headroom(planning: Mapping[str, Any], project_root: Path) -> list[dict[str, Any]]:
175
- """Existing capped planned files with more than the target and at most the limit, one row
174
+ """Existing capped planned files with more than the target, one row
176
175
  per file with every stage that writes it and the lines left before the limit."""
177
176
  rows: list[dict[str, Any]] = []
178
177
  for rel, (absolute, stages) in _planned_files(planning, project_root).items():
@@ -180,7 +179,7 @@ def planned_file_headroom(planning: Mapping[str, Any], project_root: Path) -> li
180
179
  continue
181
180
  data = absolute.read_bytes()
182
181
  lines = physical_lines(data)
183
- if FILE_LINE_TARGET < lines <= FILE_LINE_LIMIT and not _declares_generated(data):
182
+ if FILE_LINE_TARGET < lines and not _declares_generated(data):
184
183
  rows.append({"path": rel, "stages": stages, "lines": lines,
185
184
  "headroom": FILE_LINE_LIMIT - lines})
186
185
  return rows
@@ -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:
@@ -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",