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
@@ -56,6 +56,7 @@ from .phases.implementation_planning.entry import (
56
56
  )
57
57
  from . import fix_cycles
58
58
  from .analysis_packet import build_analysis_packet, cited_documents_block
59
+ from .user_authorization import validate_wizard_authorization
59
60
  from .mcp_servers import NO_MCP_SERVERS_LINE, prepare_mcp
60
61
  from .coverage_census import (
61
62
  CensusError,
@@ -161,7 +162,7 @@ from .legacy_model_selection import (
161
162
  normalize_model_selection_inputs,
162
163
  serialize_host_session_context,
163
164
  )
164
- from .model_defaults import ModelDefaultScopes
165
+ from .model_defaults import ModelDefaultError, ModelDefaultScopes, parse_model_lists
165
166
  from .worker_prompt_policy import (
166
167
  ANALYSIS_DUTY_BY_TASK_TYPE,
167
168
  critic_assignment_ref,
@@ -1302,9 +1303,7 @@ class _ResolvedAssets:
1302
1303
  lead_contract: Path
1303
1304
  run_validator: Path
1304
1305
  brief_validator: Path
1305
- # None when this task-type's host orchestration carries no gates; see
1306
- # prompts/host-orchestration/README.md. Absence is a normal state, not a
1307
- # broken install, so it is exempt from the _INSTALL_HINT contract above.
1306
+ # None only when the phase catalog declares no host orchestration rules.
1308
1307
  host_rules_file: Path | None
1309
1308
 
1310
1309
 
@@ -1359,7 +1358,10 @@ def _resolve_runtime_assets(workspace_root: Path, inp: PrepareInputs) -> _Resolv
1359
1358
  raise PrepareError(
1360
1359
  f"required okstra template or lead contract missing: {required}.{_INSTALL_HINT}"
1361
1360
  )
1362
- host_rules_file = host_rules(workspace_root, inp.task_type)
1361
+ try:
1362
+ host_rules_file = host_rules(workspace_root, inp.task_type)
1363
+ except PhaseAssetError as exc:
1364
+ raise PrepareError(f"{exc}.{_INSTALL_HINT}") from exc
1363
1365
  return _ResolvedAssets(
1364
1366
  profile_file=profile_file,
1365
1367
  prompt_template=prompt_template,
@@ -1368,7 +1370,7 @@ def _resolve_runtime_assets(workspace_root: Path, inp: PrepareInputs) -> _Resolv
1368
1370
  lead_contract=lead_contract,
1369
1371
  run_validator=run_validator,
1370
1372
  brief_validator=brief_validator,
1371
- host_rules_file=host_rules_file if host_rules_file.is_file() else None,
1373
+ host_rules_file=host_rules_file,
1372
1374
  )
1373
1375
 
1374
1376
 
@@ -1800,6 +1802,13 @@ def _clear_stale_stage_waiver(inp: "PrepareInputs", project_root: Path, stage: i
1800
1802
  )
1801
1803
 
1802
1804
 
1805
+ def prepare_exception_applies(task_type: str, option: str) -> bool:
1806
+ return {
1807
+ "--qa-waiver": "implementation",
1808
+ "--tdd-bypass": "implementation-planning",
1809
+ }.get(option) == task_type
1810
+
1811
+
1803
1812
  def _register_and_check_project(project_root: Path, inp: PrepareInputs) -> None:
1804
1813
  """project.json self-registration + (implementation 한정) qaCommands gate 검증."""
1805
1814
  from okstra_project import ResolverError
@@ -1815,10 +1824,10 @@ def _register_and_check_project(project_root: Path, inp: PrepareInputs) -> None:
1815
1824
 
1816
1825
  validate_project_qa_commands(inp.task_type, project_root)
1817
1826
  # waiver 는 stage 단위 Tier 3 면제라 implementation 진입에서만 적용한다.
1818
- if inp.task_type == "implementation":
1827
+ if prepare_exception_applies(inp.task_type, "--qa-waiver"):
1819
1828
  _apply_qa_waiver_if_requested(inp, project_root)
1820
1829
  # TDD 우회는 계획서의 stage 를 면제하므로 계획 진입에서만 적용한다.
1821
- if inp.task_type == "implementation-planning":
1830
+ if prepare_exception_applies(inp.task_type, "--tdd-bypass"):
1822
1831
  _apply_tdd_bypass_if_requested(inp, project_root)
1823
1832
 
1824
1833
 
@@ -2350,20 +2359,10 @@ def _read_model_defaults(path: Path) -> dict[str, tuple[str, ...]]:
2350
2359
  payload = load_owned_object(path, artifact="model defaults config")
2351
2360
  except (OSError, JsonBoundaryError) as exc:
2352
2361
  raise PrepareError(f"model defaults file is invalid: {path}: {exc}") from exc
2353
- raw_defaults = payload.get("modelDefaults", {}) if isinstance(payload, dict) else {}
2354
- if not isinstance(raw_defaults, dict):
2355
- raise PrepareError(f"modelDefaults must be an object: {path}")
2356
- defaults: dict[str, tuple[str, ...]] = {}
2357
- for role, models in raw_defaults.items():
2358
- if (
2359
- not isinstance(role, str)
2360
- or not isinstance(models, list)
2361
- or not models
2362
- or not all(isinstance(model, str) and model for model in models)
2363
- ):
2364
- raise PrepareError(f"modelDefaults entries must be non-empty string arrays: {path}")
2365
- defaults[role] = tuple(models)
2366
- return defaults
2362
+ try:
2363
+ return parse_model_lists(payload, "modelDefaults", path)
2364
+ except ModelDefaultError as exc:
2365
+ raise PrepareError(str(exc)) from exc
2367
2366
 
2368
2367
 
2369
2368
  @dataclass
@@ -3142,12 +3141,24 @@ def _write_instruction_set_sources(
3142
3141
  def _write_coverage_census(
3143
3142
  inp: PrepareInputs, ctx: dict, instruction_set: Path,
3144
3143
  ) -> str:
3145
- """Persist this run's coverage census and return its packet block.
3144
+ """Return the packet block for deferred or immediately persisted coverage.
3146
3145
 
3147
- The run-scoped state file is the canonical copy because the packet lives in
3148
- the task-scoped instruction set and the next phase overwrites it. A profile
3149
- block that cannot be read is reported and the run goes on without a census.
3146
+ Resolved-lens runs defer the canonical run-scoped census until the first
3147
+ analysis prompt; other runs persist any profile-declared census here.
3148
+ Invalid immediate census declarations are reported without blocking
3149
+ preparation. The packet is task-scoped.
3150
3150
  """
3151
+ if inp.task_type == "improvement-discovery":
3152
+ from .phases.improvement_discovery.lenses import RESOLVED_LENSES_POLICY
3153
+ from .phases.improvement_discovery.resolved_census import (
3154
+ improvement_census_policy_fields, pending_census_section,
3155
+ )
3156
+
3157
+ manifest_path = Path(ctx["RUN_MANIFEST_PATH"])
3158
+ recorded = _read_existing_manifest(manifest_path) if manifest_path.is_file() else None
3159
+ policy_fields = improvement_census_policy_fields(inp.task_type, recorded)
3160
+ if policy_fields.get("coverageCensusPolicy") == RESOLVED_LENSES_POLICY:
3161
+ return pending_census_section(ctx["RUN_MANIFEST_RELATIVE_PATH"])
3151
3162
  changed_files: tuple[str, ...] = ()
3152
3163
  if inp.task_type == "final-verification":
3153
3164
  changed_files = tuple(_git_out(
@@ -3414,6 +3425,8 @@ def _load_recorded_run_manifest_strict(
3414
3425
  def _verification_input_source(
3415
3426
  ctx: dict, reference: VerificationInputReference | None,
3416
3427
  ) -> Path | None:
3428
+ if ctx["TASK_TYPE"] == "implementation-planning":
3429
+ return Path(ctx.get("EXECUTOR_WORKTREE_PATH") or ctx["PROJECT_ROOT"]).resolve()
3417
3430
  source_key = ("EXECUTOR_WORKTREE_PATH" if ctx["TASK_TYPE"] == "implementation"
3418
3431
  else "VERIFICATION_WORKTREE_PATH")
3419
3432
  source_path = ctx.get(source_key, "")
@@ -3459,7 +3472,7 @@ def _validate_recorded_verification_inputs(
3459
3472
  def _prepare_verification_input_reference(
3460
3473
  ctx: dict, store: VerificationInputStore,
3461
3474
  ) -> None:
3462
- if ctx["TASK_TYPE"] not in QA_COMMAND_EXECUTING_TASK_TYPES:
3475
+ if ctx["TASK_TYPE"] not in (*QA_COMMAND_EXECUTING_TASK_TYPES, "implementation-planning"):
3463
3476
  return
3464
3477
  try:
3465
3478
  project_root = Path(ctx["PROJECT_ROOT"]).resolve()
@@ -4199,15 +4212,10 @@ def _prepare_user_authorization(inp: PrepareInputs) -> dict:
4199
4212
  record = json.loads(inp.user_authorization_json)
4200
4213
  except (TypeError, ValueError) as exc:
4201
4214
  raise PrepareError("invalid user authorization JSON") from exc
4202
- if not isinstance(record, dict) or (
4203
- record.get("schemaVersion") != "1.0"
4204
- or record.get("source") != "wizard-confirmation"
4205
- or record.get("response") != "proceed"
4206
- or not isinstance(record.get("prompt"), str)
4207
- or not record["prompt"].strip()
4208
- or not isinstance(record.get("scope"), dict)
4209
- ):
4210
- raise PrepareError("user authorization requires the displayed prompt, proceed response, and scope")
4215
+ try:
4216
+ validate_wizard_authorization(record)
4217
+ except ValueError as exc:
4218
+ raise PrepareError(str(exc)) from exc
4211
4219
  if inp.task_type == "implementation":
4212
4220
  stages = record.get("stageScope") or [record["scope"].get("stage")]
4213
4221
  if not isinstance(stages, list) or inp.stage not in stages:
@@ -4257,11 +4265,32 @@ def _prepare_mcp_block(
4257
4265
  return prepared.block
4258
4266
 
4259
4267
 
4268
+ def _validate_new_review_policy(inp: PrepareInputs, project: Path) -> None:
4269
+ from .review_policy import capture_review_policy
4270
+
4271
+ if inp.task_type not in (*QA_COMMAND_EXECUTING_TASK_TYPES, "implementation-planning"):
4272
+ return
4273
+ override = os.environ.get("OKSTRA_RUN_SEQ_OVERRIDE", "")
4274
+ if override.isdecimal() and int(override) > 0:
4275
+ ref = RunRef(project_root=project, task_group=inp.task_group, task_id=inp.task_id,
4276
+ task_type=inp.task_type, seq=int(override))
4277
+ recorded = [ref.manifest, *ref.run_dir.glob(f"stage-*/manifests/{ref.manifest.name}")]
4278
+ if any(path.is_file() for path in recorded):
4279
+ return
4280
+ try:
4281
+ config_path = project_json_path(project)
4282
+ config = load_owned_object(config_path, artifact="project config") if config_path.exists() else {}
4283
+ capture_review_policy(project, config)
4284
+ except (OSError, ValueError) as exc:
4285
+ raise PrepareError(f"review policy preflight failed: {exc}") from exc
4286
+
4287
+
4260
4288
  def prepare_task_bundle(inp: PrepareInputs) -> PrepareOutputs:
4261
4289
  """Produce a complete okstra task bundle on disk. See module docstring."""
4262
4290
  user_authorization = _prepare_user_authorization(inp)
4263
4291
  workspace_root = Path(inp.workspace_root)
4264
4292
  project_root = Path(inp.project_root)
4293
+ _validate_new_review_policy(inp, project_root)
4265
4294
  lead_runtime = _normalize_lead_runtime(inp.lead_runtime)
4266
4295
  lead_runtime_request = (inp.lead_runtime_request or lead_runtime).strip()
4267
4296
  runtime_resolution_json = (inp.runtime_resolution_json or "{}").strip()
@@ -4413,6 +4442,8 @@ def prepare_task_bundle(inp: PrepareInputs) -> PrepareOutputs:
4413
4442
  project_id=inp.project_id, task_group=inp.task_group, task_id=inp.task_id,
4414
4443
  task_type=inp.task_type, run_seq_override=run_seq_override,
4415
4444
  stage=stage_arg,
4445
+ report_authoring_format="json-v1",
4446
+ usage_accounting_policy="advisory",
4416
4447
  )
4417
4448
 
4418
4449
  ctx.update({
@@ -16,6 +16,7 @@ seq advance 와 파일 쓰기를 수행한다.
16
16
  from __future__ import annotations
17
17
 
18
18
  import fcntl
19
+ import hashlib
19
20
  import json
20
21
  import os
21
22
  from contextlib import contextmanager
@@ -24,6 +25,8 @@ from pathlib import Path
24
25
  from typing import Iterator, Optional
25
26
 
26
27
  from okstra_project.dirs import okstra_home
28
+ from okstra_project.state import parse_task_key
29
+ from okstra_project.slug import slugify
27
30
 
28
31
  from .path_hints import compact_run_context, hydrate_run_context
29
32
  from .json_boundary import JsonBoundaryError, load_owned_object, write_owned_object_atomic
@@ -92,7 +95,9 @@ def _task_lock_path(task_key: str) -> Path:
92
95
  home = okstra_home()
93
96
  locks = home / ".locks"
94
97
  locks.mkdir(parents=True, exist_ok=True)
95
- safe = task_key.replace("/", "_").replace(":", "_")
98
+ project, group, task = parse_task_key(task_key)
99
+ identity = json.dumps((project, slugify(group), slugify(task)))
100
+ safe = hashlib.sha256(identity.encode("utf-8")).hexdigest()
96
101
  return locks / f"{safe}.lock"
97
102
 
98
103
 
@@ -156,6 +161,8 @@ def compute_and_write_run_context(
156
161
  task_type: str,
157
162
  run_seq_override: Optional[int] = None,
158
163
  stage: Optional[int] = None,
164
+ report_authoring_format: str = "markdown-v1",
165
+ usage_accounting_policy: str = "strict",
159
166
  ) -> dict:
160
167
  """task per-mutex 안에서 run paths 를 계산하고 디스크에 박는다.
161
168
 
@@ -180,7 +187,9 @@ def compute_and_write_run_context(
180
187
  task_type=task_type,
181
188
  run_seq_override=run_seq_override,
182
189
  stage=stage,
190
+ report_authoring_format=report_authoring_format,
183
191
  )
192
+ ctx["USAGE_ACCOUNTING_POLICY"] = usage_accounting_policy
184
193
  ctx["RUN_TIMESTAMP_ISO"] = _now_iso()
185
194
  ctx["TASK_DATE"] = _now_task_date()
186
195
  run_manifests_dir = Path(ctx["RUN_MANIFESTS_DIR"])
@@ -14,7 +14,7 @@ from datetime import datetime, timezone
14
14
  from pathlib import Path
15
15
 
16
16
  from okstra_ctl import group_context
17
- from okstra_ctl.direct_work import find_brief_tasks, publish_direct_work, record_direct_work
17
+ from okstra_ctl.direct_work import find_brief_tasks, load_direct_task, publish_direct_work, record_direct_work
18
18
  from okstra_ctl.run_context import task_mutex
19
19
  from okstra_ctl.ids import slugify_task_segment
20
20
  from okstra_ctl.fixed_text import line, scalar
@@ -213,21 +213,10 @@ def _refresh_group_queue(project_root: Path, entry: dict) -> str:
213
213
  def _write_status(project_root: Path, entry: dict, args) -> dict:
214
214
  manifest_path = _manifest_path(project_root, entry)
215
215
  manifest_path.resolve().relative_to((project_root / ".okstra" / "tasks").resolve())
216
- if manifest_path.exists():
217
- manifest = load_owned_object(manifest_path, artifact="task manifest")
218
- elif entry.get("_briefVerified"):
219
- if (manifest_path.parent / "runs").exists() or entry.get("latestRunPath"):
220
- raise ValueError("Task manifest is missing for a task with run history")
221
- identity_fields = (
222
- "schemaVersion", "projectId", "projectRoot", "taskGroup", "taskId", "taskKey",
223
- "taskGroupPathSegment", "taskIdPathSegment", "taskBriefPath", "taskRootPath", "taskManifestPath",
224
- )
225
- manifest = {key: entry[key] for key in identity_fields if key in entry}
226
- manifest["registrationSource"] = "direct"
227
- else:
216
+ if not manifest_path.exists() and not entry.get("_briefVerified"):
228
217
  return {"ok": False, "stage": "manifest-missing", "taskKey": entry["taskKey"]}
229
- if str(manifest.get("taskKey", "")).casefold() != entry["taskKey"].casefold():
230
- raise ValueError("Task manifest identity does not match the requested task")
218
+ manifest_path, manifest = load_direct_task(project_root, {**entry, "taskManifestPath": str(manifest_path)},
219
+ allow_create=bool(entry.get("_briefVerified")))
231
220
  if manifest.get("registrationSource") == "direct" or args.note is not None:
232
221
  project_id, group, task_id = entry["taskKey"].split(":")
233
222
  for field, value in (("projectId", project_id), ("taskGroup", group), ("taskId", task_id)):
@@ -108,6 +108,14 @@ def done_stage(
108
108
  head = carry_head_commit(carry)
109
109
  file_size_cap = _check_file_size(project_root, carry, head)
110
110
  report = report if report.is_absolute() else project_root / report
111
+ try:
112
+ from .design_review_evidence import validate_stage_design_report
113
+
114
+ rng = carry.get("stageCommitRange") or {}
115
+ validate_stage_design_report(project_root, report, stage, head=head,
116
+ base=str(rng.get("base") or ""), task_key=task_key)
117
+ except (OSError, ValueError) as exc:
118
+ raise StateError(f"design review prevents stage completion: {exc}", stage="design-review") from exc
111
119
  try:
112
120
  report_rel = report.relative_to(RunRef.from_report_path(report).run_dir).as_posix()
113
121
  except ValueError as exc:
@@ -169,6 +177,9 @@ over the 500-line limit or takes one past it (`okstra correction file-size`); a
169
177
  file already over 500 at the stage base may grow. Re-running with the
170
178
  same carry writes nothing new.
171
179
 
180
+ Input-4.0 runs also require the latest accepted report for this task/stage and
181
+ matching base/head, current sealed verifier results and complete design coverage.
182
+
172
183
  Output: JSON { ok, taskKey, stage, headCommit, carryPath, supersededCarryPath,
173
184
  reportPath, consumersPath, fileSizeCap }. Exit 1 on a refusal, 2 when
174
185
  PROJECT_ROOT cannot be resolved.
@@ -0,0 +1,28 @@
1
+ """Post-execution integrity checks for independent code review."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import replace
5
+
6
+ from .execution_mutation_audit import (
7
+ ExecutionMutationAudit,
8
+ MutationAuditResult,
9
+ MutationSnapshot,
10
+ )
11
+ from .write_policy import WritePolicy
12
+
13
+ REVIEW_WRITE_VIOLATION_EXIT_CODE = 77
14
+
15
+
16
+ def compare_standalone_review(
17
+ before: MutationSnapshot, policy: WritePolicy, *, succeeded: bool,
18
+ ) -> MutationAuditResult:
19
+ result = ExecutionMutationAudit().compare(
20
+ before, (policy,), attempt_succeeded=succeeded,
21
+ )
22
+ if result.untracked_paths:
23
+ result = replace(
24
+ result, status="contract-failed-unattributed", source_changed=True,
25
+ retry_allowed=False,
26
+ violations=(*result.violations, "readonly review created untracked source paths"),
27
+ )
28
+ return result
@@ -20,6 +20,7 @@ from okstra_project import (
20
20
  )
21
21
 
22
22
  from .fixed_text import line
23
+ from .task_query import TaskQueryError, query_project_tasks
23
24
 
24
25
 
25
26
  def render_text(payload: dict) -> str:
@@ -36,7 +37,14 @@ def render_text(payload: dict) -> str:
36
37
  line("Work status", task["workStatus"]) if task.get("workStatus") else "",
37
38
  line("Direct work record", task["latestWorkRecordPath"]) if task.get("latestWorkRecordPath") else "",
38
39
  line("Updated at", task.get("updatedAt")),
40
+ line("Execution kind", task["executionKind"]) if task.get("executionKind") else "",
41
+ line("Implementation trace", task["implementationTracePath"]) if task.get("implementationTracePath") else "",
42
+ line("Match", task["preview"]) if task.get("preview") else "",
43
+ line("Relation reasons", task["reasons"]) if task.get("reasons") else "",
39
44
  ))
45
+ if "truncated" in payload:
46
+ parts.extend((line("Truncated", payload["truncated"]), line("Next cursor", payload["nextCursor"])))
47
+ parts.extend(line("Unavailable task", row["taskKey"]) for row in payload["unavailable"])
40
48
  return "".join(parts)
41
49
 
42
50
 
@@ -56,7 +64,16 @@ def collect(
56
64
  latest_run_status: str | None = None,
57
65
  task_group: str | None = None,
58
66
  limit: int | None = None,
67
+ query: str | None = None,
68
+ related_to: str | None = None,
69
+ after: str | None = None,
59
70
  ) -> dict:
71
+ if query is not None or related_to is not None or after is not None:
72
+ return query_project_tasks(
73
+ project_root, query=query or "", related_to=related_to or "", after=after or "",
74
+ limit=20 if limit is None else limit, task_type=task_type or "",
75
+ latest_run_status=latest_run_status or "", task_group=task_group or "",
76
+ )
60
77
  return {
61
78
  "ok": True,
62
79
  "projectRoot": str(project_root),
@@ -104,6 +121,9 @@ def main(argv: list[str] | None = None) -> int:
104
121
  parser.add_argument("--task-group", default="", help="filter by taskGroup")
105
122
  parser.add_argument("--limit", default="",
106
123
  help="keep the first N (the catalog is updatedAt desc)")
124
+ parser.add_argument("--query", default=None, help="match every whitespace-separated term")
125
+ parser.add_argument("--related-to", default=None, help="find explicit and shared-metadata relations")
126
+ parser.add_argument("--after", default=None, help="resume after the last inspected task key")
107
127
  mode = parser.add_mutually_exclusive_group()
108
128
  mode.add_argument("--json", dest="output_mode", action="store_const",
109
129
  const="json", default="json", help="emit JSON (default)")
@@ -122,17 +142,23 @@ def main(argv: list[str] | None = None) -> int:
122
142
  print(json.dumps({"ok": False, "stage": "resolve", "reason": str(exc)}))
123
143
  return 2
124
144
 
125
- payload = collect(
126
- Path(resolved),
127
- task_type=args.task_type or None,
128
- latest_run_status=args.latest_run_status or None,
129
- task_group=args.task_group or None,
130
- limit=int(args.limit) if args.limit else None,
131
- )
145
+ try:
146
+ payload = collect(
147
+ Path(resolved),
148
+ task_type=args.task_type or None,
149
+ latest_run_status=args.latest_run_status or None,
150
+ task_group=args.task_group or None,
151
+ limit=int(args.limit) if args.limit else None,
152
+ query=args.query, related_to=args.related_to, after=args.after,
153
+ )
154
+ except (TaskQueryError, ValueError) as exc:
155
+ payload = {"ok": False, "stage": "query", "reason": str(exc) if isinstance(exc, TaskQueryError) else "invalid-query"}
156
+ print(json.dumps(payload))
157
+ return 2
132
158
  if args.output_mode == "text":
133
159
  print(render_text(payload), end="")
134
160
  else:
135
- print(json.dumps(payload, default=str))
161
+ print(json.dumps(payload, default=str, ensure_ascii="truncated" not in payload))
136
162
  return 0
137
163
 
138
164
 
@@ -0,0 +1,239 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ from typing import TypedDict
7
+
8
+ from okstra_project import StateError, parse_task_key, resolve_task_root_read_only
9
+ from okstra_project.dirs import TASK_CATALOG_RELATIVE
10
+ from okstra_project.state import derived_task_status
11
+
12
+ from .doyouknow.contracts import DoyouknowError, reject_secrets
13
+ from .doyouknow.sources.io import safe_source_path
14
+ from .json_boundary import JsonBoundaryError, PageBudgetExhausted, ReadBudget, load_owned_object
15
+ from .trace_tasks import TRACE_METADATA_LIST_LIMITS, TRACE_METADATA_TEXT_LIMITS, read_task_trace
16
+
17
+ QUERY_CATALOG_BYTES = 4 * 1024 * 1024
18
+ QUERY_SOURCE_BYTES = 2 * 1024 * 1024
19
+ QUERY_OUTPUT_BYTES = 256 * 1024
20
+ QUERY_PAGE_SOURCE_BYTES = 16 * 1024 * 1024
21
+ QUERY_CATALOG_ENTRIES = 1000
22
+ QUERY_PAGE_TASKS = 64
23
+ QUERY_PREVIEW_CHARS = 160
24
+ QUERY_TEXT_CHARS = 256
25
+ QUERY_MAX_RESULTS = 100
26
+ QUERY_KEY_CHARS = 384
27
+ QUERY_TITLE_CHARS = TRACE_METADATA_TEXT_LIMITS["title"]
28
+ QUERY_LABEL_CHARS = 64
29
+ QUERY_METADATA_LIMITS = TRACE_METADATA_LIST_LIMITS
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class TaskDocument:
34
+ key: str
35
+ title: str
36
+ status: str
37
+ execution_kind: str
38
+ trace_path: str
39
+ record_path: str
40
+ text: str
41
+ links: frozenset[str]
42
+ tags: frozenset[str]
43
+ files: frozenset[str]
44
+ references: frozenset[str]
45
+
46
+
47
+ class SearchMetadata(TypedDict):
48
+ title: str
49
+ summary: str
50
+ links: frozenset[str]
51
+ tags: frozenset[str]
52
+ files: frozenset[str]
53
+ references: frozenset[str]
54
+
55
+
56
+ class TaskQueryError(Exception):
57
+ pass
58
+
59
+
60
+ def _regular_source_path(root: Path, path: str | Path) -> Path:
61
+ source = safe_source_path(root, path)
62
+ if not source.is_file():
63
+ raise TaskQueryError("source-unavailable")
64
+ return source
65
+
66
+
67
+ def _read_object(root: Path, path: str | Path, maximum: int = QUERY_SOURCE_BYTES, *, budget: ReadBudget | None = None) -> dict:
68
+ value = load_owned_object(_regular_source_path(root, path), artifact="task query source", max_bytes=maximum, budget=budget)
69
+ reject_secrets(json.dumps(value, ensure_ascii=False))
70
+ return value
71
+
72
+
73
+ def _string_values(value: object, maximum: int | None, item_chars: int) -> frozenset[str]:
74
+ if value is None:
75
+ return frozenset()
76
+ if not isinstance(value, list) or (maximum is not None and len(value) > maximum) or any(not isinstance(item, str) or len(item) > item_chars for item in value):
77
+ raise TaskQueryError("source-unavailable")
78
+ return frozenset(value)
79
+
80
+
81
+ def _read_owned_manifest(root: Path, project: str, entry: dict, catalog: list[dict], budget: ReadBudget) -> tuple[Path, dict]:
82
+ key = entry["taskKey"]
83
+ owner, group, task = parse_task_key(key)
84
+ if owner != project:
85
+ raise TaskQueryError("source-unavailable")
86
+ task_root = resolve_task_root_read_only(root, key, catalog=catalog)
87
+ if task_root is None:
88
+ raise TaskQueryError("source-unavailable")
89
+ task_root = safe_source_path(root, task_root)
90
+ manifest = _read_object(task_root, "task-manifest.json", budget=budget)
91
+ if (manifest.get("taskKey"), manifest.get("projectId"), manifest.get("taskGroup"), manifest.get("taskId")) != (key, project, group, task):
92
+ raise TaskQueryError("source-unavailable")
93
+ return task_root, manifest
94
+
95
+
96
+ def _normalize_search_metadata(manifest: dict, entry: dict) -> SearchMetadata:
97
+ metadata = manifest.get("traceMetadata", {})
98
+ if not isinstance(metadata, dict) or any(
99
+ field in metadata and (not isinstance(metadata[field], str) or len(metadata[field]) > maximum)
100
+ for field, maximum in TRACE_METADATA_TEXT_LIMITS.items()
101
+ ):
102
+ raise TaskQueryError("source-unavailable")
103
+ return {
104
+ "title": str(metadata.get("title") or manifest.get("title") or entry.get("title") or manifest["taskId"]),
105
+ "summary": str(metadata.get("summary") or manifest.get("workStatusNote") or ""),
106
+ "links": _string_values(manifest.get("relatedTasks"), None, QUERY_KEY_CHARS) | _string_values(metadata.get("relatedTasks"), *QUERY_METADATA_LIMITS["relatedTasks"]),
107
+ "tags": _string_values(metadata.get("tags", manifest.get("tags")), *QUERY_METADATA_LIMITS["tags"]),
108
+ "files": _string_values(metadata.get("changedFiles", manifest.get("changedFiles")), *QUERY_METADATA_LIMITS["changedFiles"]),
109
+ "references": _string_values(metadata.get("references", manifest.get("references")), *QUERY_METADATA_LIMITS["references"]),
110
+ }
111
+
112
+
113
+ def _read_linked_search_sources(root: Path, task_root: Path, manifest: dict, key: str, budget: ReadBudget) -> tuple[str, str]:
114
+ trace_path = manifest.get("implementationTracePath", "")
115
+ trace_text, record_summary = "", ""
116
+ if trace_path:
117
+ _regular_source_path(root, trace_path)
118
+ trace_text = read_task_trace(root, trace_path, key, budget=budget).text
119
+ reject_secrets(trace_text)
120
+ record_path = manifest.get("latestWorkRecordPath", "")
121
+ if record_path:
122
+ record = _read_object(task_root, safe_source_path(root, record_path), budget=budget)
123
+ if record.get("taskKey") != key:
124
+ raise TaskQueryError("source-unavailable")
125
+ record_summary = " " + str(record.get("summary") or "")
126
+ return trace_text, record_summary
127
+
128
+
129
+ def _read_document(root: Path, project: str, entry: dict, catalog: list[dict], budget: ReadBudget) -> TaskDocument:
130
+ task_root, manifest = _read_owned_manifest(root, project, entry, catalog, budget)
131
+ metadata = _normalize_search_metadata(manifest, entry)
132
+ trace_text, record_summary = _read_linked_search_sources(root, task_root, manifest, entry["taskKey"], budget)
133
+ text = "\n".join((metadata["title"], metadata["summary"] + record_summary,
134
+ *sorted(metadata["tags"]), *sorted(metadata["files"]), *sorted(metadata["references"]), *sorted(metadata["links"]), trace_text))
135
+ return TaskDocument(
136
+ key=entry["taskKey"], title=metadata["title"],
137
+ status=derived_task_status(manifest).get("workStatus", ""),
138
+ execution_kind=str(manifest.get("executionKind") or ""),
139
+ trace_path=manifest.get("implementationTracePath", ""),
140
+ record_path=manifest.get("latestWorkRecordPath", ""), text=text,
141
+ links=metadata["links"], tags=metadata["tags"], files=metadata["files"], references=metadata["references"],
142
+ )
143
+
144
+
145
+ def _relation_reasons(origin: TaskDocument, candidate: TaskDocument) -> list[dict]:
146
+ reasons = []
147
+ if candidate.key in origin.links or origin.key in candidate.links:
148
+ reasons.append({"kind": "related-task", "reason": "An explicit related-task link connects these tasks.", "standing": "user-stated", "evidence": [origin.key, candidate.key]})
149
+ for kind, shared in (("tag", origin.tags & candidate.tags), ("changed-file", origin.files & candidate.files), ("reference", origin.references & candidate.references)):
150
+ if shared:
151
+ reasons.append({"kind": kind, "reason": f"Tasks share {kind} metadata.", "standing": "candidate", "evidence": sorted(shared)})
152
+ return reasons
153
+
154
+
155
+ def _result(document: TaskDocument, terms: list[str], reasons: list[dict]) -> dict:
156
+ preview = document.text
157
+ if terms:
158
+ start = preview.casefold().find(terms[0])
159
+ preview = preview[max(0, start):]
160
+ return {"taskKey": document.key, "title": document.title[:QUERY_TITLE_CHARS], "workStatus": document.status[:QUERY_LABEL_CHARS],
161
+ "executionKind": document.execution_kind[:QUERY_LABEL_CHARS], "implementationTracePath": document.trace_path, "latestWorkRecordPath": document.record_path,
162
+ "preview": " ".join(preview.split())[:QUERY_PREVIEW_CHARS], "reasons": reasons}
163
+
164
+
165
+ def query_project_tasks(root: Path, *, query: str = "", related_to: str = "", after: str = "", limit: int = 20,
166
+ task_type: str = "", latest_run_status: str = "", task_group: str = "") -> dict:
167
+ if len(query) > QUERY_TEXT_CHARS or not isinstance(limit, int) or isinstance(limit, bool) or not 1 <= limit <= QUERY_MAX_RESULTS:
168
+ raise TaskQueryError("invalid-query")
169
+ try:
170
+ project = _read_object(root, ".okstra/project.json")["projectId"]
171
+ catalog_path = safe_source_path(root, TASK_CATALOG_RELATIVE)
172
+ catalog = _read_object(root, catalog_path, QUERY_CATALOG_BYTES).get("tasks", []) if catalog_path.exists() else []
173
+ if not isinstance(catalog, list) or len(catalog) > QUERY_CATALOG_ENTRIES:
174
+ raise TaskQueryError("source-unavailable")
175
+ if any(not isinstance(row, dict) or not isinstance(row.get("taskKey"), str) for row in catalog):
176
+ raise TaskQueryError("source-unavailable")
177
+ entries = sorted(catalog, key=lambda row: row["taskKey"])
178
+ keys = [row["taskKey"] for row in entries]
179
+ if len(set(keys)) != len(keys) or any(len(key) > QUERY_KEY_CHARS or parse_task_key(key)[0] != project for key in keys):
180
+ raise TaskQueryError("source-unavailable")
181
+ for token in (after, related_to):
182
+ if token and (len(token) > QUERY_KEY_CHARS or parse_task_key(token)[0] != project):
183
+ raise TaskQueryError("invalid-query")
184
+ budget = ReadBudget(QUERY_PAGE_SOURCE_BYTES)
185
+ origin = None
186
+ if related_to:
187
+ selected = next((entry for entry in entries if entry["taskKey"] == related_to), None)
188
+ if selected is None:
189
+ raise TaskQueryError("source-unavailable")
190
+ origin = _read_document(root, project, selected, catalog, budget)
191
+ return _query_page(root, project, entries, catalog, query, origin, after, limit, task_type, latest_run_status, task_group, budget)
192
+ except (OSError, UnicodeError, JsonBoundaryError, DoyouknowError, StateError, KeyError, TypeError, ValueError, RecursionError) as exc:
193
+ raise TaskQueryError("source-unavailable") from exc
194
+
195
+
196
+ def _append_page_item(payload: dict, field: str, item: dict, cursor: str) -> bool:
197
+ trial = {**payload, field: [*payload[field], item], "truncated": True, "nextCursor": item["taskKey"]}
198
+ if len(json.dumps(trial, ensure_ascii=False).encode("utf-8")) > QUERY_OUTPUT_BYTES:
199
+ payload.update(truncated=True, nextCursor=cursor)
200
+ return False
201
+ payload[field].append(item)
202
+ return True
203
+
204
+
205
+ def _query_page(root: Path, project: str, entries: list[dict], catalog: list[dict], query: str,
206
+ origin: TaskDocument | None, after: str, limit: int, task_type: str,
207
+ latest_run_status: str, task_group: str, budget: ReadBudget) -> dict:
208
+ terms = query.casefold().split()
209
+ remaining = [entry for entry in entries if entry["taskKey"] > after]
210
+ payload = {"ok": True, "projectRoot": str(root), "tasks": [], "unavailable": [], "truncated": False, "nextCursor": None}
211
+ cursor = after
212
+ for inspected, entry in enumerate(remaining):
213
+ if inspected >= QUERY_PAGE_TASKS - int(origin is not None) or len(payload["tasks"]) >= limit:
214
+ payload.update(truncated=True, nextCursor=cursor)
215
+ break
216
+ key = entry["taskKey"]
217
+ if origin and key == origin.key:
218
+ cursor = key
219
+ continue
220
+ try:
221
+ document = _read_document(root, project, entry, catalog, budget)
222
+ except PageBudgetExhausted:
223
+ payload.update(truncated=True, nextCursor=cursor)
224
+ break
225
+ except (OSError, UnicodeError, JsonBoundaryError, DoyouknowError, StateError, TaskQueryError, KeyError, TypeError, RecursionError, ValueError):
226
+ if not _append_page_item(payload, "unavailable", {"taskKey": key, "reason": "source-unavailable"}, cursor):
227
+ break
228
+ cursor = key
229
+ continue
230
+ reasons = _relation_reasons(origin, document) if origin else []
231
+ folded = document.text.casefold()
232
+ matched = (not origin or (key != origin.key and bool(reasons))) and all(term in folded for term in terms)
233
+ selected = (not task_type or entry.get("taskType") == task_type) and (not latest_run_status or entry.get("latestRunStatus") == latest_run_status) and (not task_group or entry.get("taskGroup") == task_group)
234
+ if matched and selected:
235
+ result = _result(document, terms, reasons)
236
+ if not _append_page_item(payload, "tasks", result, cursor):
237
+ break
238
+ cursor = key
239
+ return payload