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
@@ -12,6 +12,9 @@ from typing import Any
12
12
  from .final_report_schema import SchemaError, validate as validate_schema
13
13
 
14
14
 
15
+ OUTSIDE_WORKER_RESULT_LANES = "outside worker result lanes"
16
+
17
+
15
18
  class JsonBoundaryError(ValueError):
16
19
  """An owned JSON artifact could not satisfy its persistence contract."""
17
20
 
@@ -22,6 +25,16 @@ class JsonBoundaryError(ValueError):
22
25
  super().__init__(f"{artifact}: {reason}: {path}")
23
26
 
24
27
 
28
+ class PageBudgetExhausted(Exception):
29
+ """Let callers paginate without labeling an unread source as unavailable."""
30
+
31
+
32
+ @dataclass
33
+ class ReadBudget:
34
+ max_bytes: int
35
+ bytes_read: int = 0
36
+
37
+
25
38
  _EXTERNAL_SOURCE_SEAL = object()
26
39
 
27
40
 
@@ -86,7 +99,7 @@ def external_worker_json_source(
86
99
  )
87
100
  if not is_worker_lane or lexical_path.parent != lexical_lane:
88
101
  raise JsonBoundaryError(
89
- path, "worker JSON", "outside worker result lanes"
102
+ path, "worker JSON", OUTSIDE_WORKER_RESULT_LANES
90
103
  )
91
104
  try:
92
105
  lexical_lane.relative_to(lexical_root)
@@ -96,12 +109,12 @@ def external_worker_json_source(
96
109
  path.resolve(strict=False).relative_to(resolved_lane)
97
110
  except ValueError as exc:
98
111
  raise JsonBoundaryError(
99
- path, "worker JSON", "outside worker result lanes"
112
+ path, "worker JSON", OUTSIDE_WORKER_RESULT_LANES
100
113
  ) from exc
101
114
  if _has_symlink_component(lexical_lane, lexical_root) or _has_symlink_component(
102
115
  lexical_path, lexical_lane
103
116
  ):
104
- raise JsonBoundaryError(path, "worker JSON", "outside worker result lanes")
117
+ raise JsonBoundaryError(path, "worker JSON", OUTSIDE_WORKER_RESULT_LANES)
105
118
  return _issue_external_source(path, "worker")
106
119
 
107
120
 
@@ -203,6 +216,8 @@ def load_owned_object(
203
216
  artifact: str,
204
217
  schema: Mapping[str, Any] | None = None,
205
218
  validate_cross_fields: Callable[[dict[str, Any]], object] | None = None,
219
+ max_bytes: int | None = None,
220
+ budget: ReadBudget | None = None,
206
221
  ) -> dict[str, Any]:
207
222
  """Load and validate one okstra-owned JSON object."""
208
223
  return load_owned_object_snapshot(
@@ -210,6 +225,8 @@ def load_owned_object(
210
225
  artifact=artifact,
211
226
  schema=schema,
212
227
  validate_cross_fields=validate_cross_fields,
228
+ max_bytes=max_bytes,
229
+ budget=budget,
213
230
  ).value
214
231
 
215
232
 
@@ -219,10 +236,16 @@ def load_owned_object_snapshot(
219
236
  artifact: str,
220
237
  schema: Mapping[str, Any] | None = None,
221
238
  validate_cross_fields: Callable[[dict[str, Any]], object] | None = None,
239
+ max_bytes: int | None = None,
240
+ budget: ReadBudget | None = None,
222
241
  ) -> OwnedJsonSnapshot:
223
242
  """한 번 읽은 바이트에서 객체를 파싱·검증해 함께 반환한다."""
243
+ if budget is not None and max_bytes is None:
244
+ max_bytes = budget.max_bytes
224
245
  try:
225
- raw_bytes = path.read_bytes()
246
+ raw_bytes = path.read_bytes() if max_bytes is None else read_bounded_bytes(
247
+ path, max_bytes=max_bytes, artifact=artifact, budget=budget,
248
+ )
226
249
  value = json.loads(
227
250
  raw_bytes.decode("utf-8"),
228
251
  parse_constant=_reject_nonstandard_json_constant,
@@ -249,19 +272,42 @@ def load_owned_object_snapshot(
249
272
  )
250
273
 
251
274
 
275
+ def read_bounded_bytes(path: Path, *, max_bytes: int, artifact: str, budget: ReadBudget | None = None) -> bytes:
276
+ maximum = max_bytes
277
+ if budget is not None:
278
+ if budget.bytes_read > budget.max_bytes:
279
+ raise PageBudgetExhausted("Page source byte budget exhausted")
280
+ maximum = min(maximum, budget.max_bytes - budget.bytes_read)
281
+ with path.open("rb") as handle:
282
+ content = handle.read(maximum + 1)
283
+ if budget is not None:
284
+ budget.bytes_read += len(content)
285
+ if budget.bytes_read > budget.max_bytes:
286
+ raise PageBudgetExhausted("Page source byte budget exhausted")
287
+ if len(content) > max_bytes:
288
+ raise JsonBoundaryError(path, artifact, f"input exceeds {max_bytes} bytes")
289
+ return content
290
+
291
+
252
292
  def load_external_json(
253
293
  source: ExternalJsonSource,
254
294
  *,
255
295
  artifact: str,
256
296
  object_pairs_hook: Callable[[list[tuple[str, Any]]], Any] | None = None,
297
+ max_bytes: int | None = None,
257
298
  ) -> Any:
258
299
  """Load external JSON without applying an owned-artifact contract."""
259
300
  if not isinstance(source, ExternalJsonSource):
260
301
  raise TypeError("load_external_json requires ExternalJsonSource")
261
302
  path = source.path
262
303
  try:
304
+ if max_bytes is None:
305
+ content = path.read_text(encoding="utf-8")
306
+ else:
307
+ raw = read_bounded_bytes(path, max_bytes=max_bytes, artifact=artifact)
308
+ content = raw.decode("utf-8")
263
309
  return json.loads(
264
- path.read_text(encoding="utf-8"),
310
+ content,
265
311
  object_pairs_hook=object_pairs_hook,
266
312
  )
267
313
  except FileNotFoundError as exc:
@@ -50,6 +50,27 @@ def read_jsonl(path: Path) -> List[dict]:
50
50
  return rows
51
51
 
52
52
 
53
+ def _reject_jsonl_constant(value: str) -> None:
54
+ raise ValueError("non-finite JSON constant")
55
+
56
+
57
+ def parse_jsonl_snapshot(text: str) -> tuple[list[dict], list[int]]:
58
+ rows: list[dict] = []
59
+ invalid_lines: list[int] = []
60
+ for number, line in enumerate(text.split("\n"), start=1):
61
+ if not line.strip():
62
+ continue
63
+ try:
64
+ row = json.loads(line, parse_constant=_reject_jsonl_constant)
65
+ if not isinstance(row, dict):
66
+ raise ValueError("JSONL row must be an object")
67
+ except (ValueError, RecursionError):
68
+ invalid_lines.append(number)
69
+ continue
70
+ rows.append(row)
71
+ return rows, invalid_lines
72
+
73
+
53
74
  def remove_jsonl_row(path: Path, match: Callable[[dict], bool]) -> Optional[dict]:
54
75
  """match 가 True 인 첫 행을 제거하고 반환. 없으면 None.
55
76
  임시 파일 + os.replace 로 원자적으로 교체한다.
@@ -3,6 +3,7 @@ from __future__ import annotations
3
3
 
4
4
  import argparse
5
5
  import json
6
+ import subprocess
6
7
  import sys
7
8
  from pathlib import Path
8
9
 
@@ -10,7 +11,10 @@ from okstra_project.dirs import okstra_home
10
11
 
11
12
  from .manager_launch import build_launch_packet
12
13
  from .fixed_text import line, value_lines
14
+ from .manager_journal import JOURNAL_KINDS, add_journal_entry, read_body_file
15
+ from .manager_log import DEFAULT_LIMIT, read_activity_page
13
16
  from .manager_paths import ManagerPathError
17
+ from .manager_resume import DEFAULT_RECENT, resume_manager
14
18
  from .manager_store import (
15
19
  ManagerError,
16
20
  append_directive,
@@ -56,7 +60,8 @@ def render_manager_text(command: str, payload: dict | list[dict]) -> str:
56
60
  allowed = {"init", "discover-projects", "new-project", "new-task-group", "new-task",
57
61
  "task-assign", "task-note", "task-sync", "task-status", "task-run", "task-split",
58
62
  "list-managers", "list-projects", "list-task-groups", "list-tasks", "view",
59
- "task-update", "task-remove-child", "remove-project", "remove-task", "remove-task-group"}
63
+ "task-update", "task-remove-child", "remove-project", "remove-task", "remove-task-group",
64
+ "log", "journal-add", "resume"}
60
65
  if command not in allowed:
61
66
  raise ValueError("unknown manager text purpose")
62
67
  rows = [f"Okstra manager {command}\n", line("Status", "ready")]
@@ -110,9 +115,84 @@ def render_manager_text(command: str, payload: dict | list[dict]) -> str:
110
115
  rows.extend(_render_removal(payload))
111
116
  if command == "task-sync" and "syncedAt" in payload:
112
117
  rows.append(line("Synced at", payload.get("syncedAt")))
118
+ if command == "log":
119
+ rows.extend(_render_log(payload))
120
+ if command == "resume":
121
+ rows.extend(_render_resume(payload))
122
+ if command == "journal-add":
123
+ for label, key in (("Entry ID", "id"), ("Kind", "kind"), ("Body", "body"),
124
+ ("Created at", "createdAt"), ("Resolves", "resolves")):
125
+ rows.append(line(label, payload.get(key)))
113
126
  return "".join(rows)
114
127
 
115
128
 
129
+ def _list_field(payload: dict, key: str) -> list:
130
+ value = payload.get(key)
131
+ return value if isinstance(value, list) else []
132
+
133
+
134
+ def _render_entries(prefix: str, entries: list) -> list[str]:
135
+ rows = [line(f"{prefix} count", len(entries))]
136
+ for index, entry in enumerate(entries, 1):
137
+ for label, key in (("created at", "createdAt"), ("origin", "origin"), ("kind", "kind"),
138
+ ("task group", "taskGroup"), ("task ID", "taskId")):
139
+ rows.append(line(f"{prefix} {index} {label}", entry.get(key)))
140
+ rows.extend(value_lines(f"{prefix} {index} row", entry.get("row")))
141
+ return rows
142
+
143
+
144
+ def _render_log(payload: dict) -> list[str]:
145
+ rows = [line("Matched count", payload.get("matchedCount"))]
146
+ rows.extend(_render_entries("Entry", _list_field(payload, "entries")))
147
+ rows.extend(_render_damaged(_list_field(payload, "damaged")))
148
+ return rows
149
+
150
+
151
+ def _render_last_summary(payload: dict) -> list[str]:
152
+ last_summary = payload.get("lastSummary") if isinstance(payload.get("lastSummary"), dict) else None
153
+ row = last_summary["row"] if last_summary is not None else {}
154
+ rows = [line("Last session summary at", last_summary["createdAt"] if last_summary is not None else "none"),
155
+ line("Last session summary", row.get("body") or "none")]
156
+ count = payload.get("unsummarizedCount") or 0
157
+ since = payload.get("unsummarizedSince") or "the first entry"
158
+ rows.append(line("Unsummarized activity", f"{count} rows since {since}" if count else "none"))
159
+ return rows
160
+
161
+
162
+ def _render_resume(payload: dict) -> list[str]:
163
+ rows = _render_last_summary(payload)
164
+ rows.extend(_render_entries("Open follow-up", _list_field(payload, "openFollowups")))
165
+ rows.extend(_render_entries("Recent decision", _list_field(payload, "recentDecisions")))
166
+ rows.extend(_render_entries("Recent entry", _list_field(payload, "recentEntries")))
167
+ rows.extend(_render_task_overviews(_list_field(payload, "tasks")))
168
+ rows.extend(_render_damaged(_list_field(payload, "damaged")))
169
+ return rows
170
+
171
+
172
+ def _render_task_overviews(tasks: list) -> list[str]:
173
+ rows = [line("Task count", len(tasks))]
174
+ for index, task in enumerate(tasks, 1):
175
+ rows.append(line(f"Task {index} group", task.get("taskGroup")))
176
+ rows.append(line(f"Task {index} ID", task.get("taskId")))
177
+ if "error" in task:
178
+ rows.append(line(f"Task {index} error", task["error"]))
179
+ continue
180
+ rows.append(line(f"Task {index} synced at", task.get("syncedAt") or "never"))
181
+ if "syncAgeSeconds" in task:
182
+ rows.append(line(f"Task {index} sync age", _age_text(task["syncAgeSeconds"])))
183
+ rows.append(line(f"Task {index} changed since sync count", task.get("changedSinceSyncCount")))
184
+ rows.append(line(f"Task {index} unlinked child count", task.get("unlinkedChildCount")))
185
+ return rows
186
+
187
+
188
+ def _render_damaged(damaged: list) -> list[str]:
189
+ rows = [line("Damaged file count", len(damaged))]
190
+ for index, item in enumerate(damaged, 1):
191
+ rows.append(line(f"Damaged file {index} path", item.get("path")))
192
+ rows.append(line(f"Damaged file {index} lines", ", ".join(str(number) for number in item.get("lines") or [])))
193
+ return rows
194
+
195
+
116
196
  # 삭제 명령은 --confirm 이 없으면 대상만 보여 준다. 무엇이 지워지고 무엇이 남는지 한 줄씩 찍는다.
117
197
  def _render_removal(payload: dict) -> list[str]:
118
198
  rows = [line("Removed", "yes" if payload.get("removed") else "no — dry run; rerun with --confirm")]
@@ -264,6 +344,9 @@ _CLI_EPILOG = r"""Usage:
264
344
  okstra manager list task-groups --manager-id <id>
265
345
  okstra manager list tasks --manager-id <id>
266
346
  okstra manager view --manager-id <id>
347
+ okstra manager journal add --manager-id <id> --kind <decision|finding|followup|session-summary> (--body <text> | --body-file <path>) [--task-group <task-group> --task-id <task-id>] [--resolves <entry-id>]
348
+ okstra manager resume --manager-id <id> [--recent <n>]
349
+ okstra manager log --manager-id <id> [--task-group <task-group> --task-id <task-id>] [--kind <name>] [--since <ISO>] [--grep <text>] [--open-followups] [--limit <n>]
267
350
 
268
351
  remove and task remove-child only show their targets unless --confirm is given.
269
352
  --workspace-root is owned by this command.
@@ -391,9 +474,60 @@ def _parser() -> argparse.ArgumentParser:
391
474
 
392
475
  view = sub.add_parser("view")
393
476
  view.add_argument("--manager-id", required=True)
477
+
478
+ journal = sub.add_parser("journal")
479
+ journal_sub = journal.add_subparsers(dest="journal_command", required=True)
480
+ journal_add = journal_sub.add_parser("add")
481
+ journal_add.add_argument("--manager-id", required=True)
482
+ journal_add.add_argument("--kind", choices=JOURNAL_KINDS, required=True)
483
+ body = journal_add.add_mutually_exclusive_group(required=True)
484
+ body.add_argument("--body")
485
+ body.add_argument("--body-file", type=Path)
486
+ journal_add.add_argument("--task-group", default=None)
487
+ journal_add.add_argument("--task-id", default=None)
488
+ journal_add.add_argument("--resolves", default="")
489
+
490
+ resume = sub.add_parser("resume")
491
+ resume.add_argument("--manager-id", required=True)
492
+ resume.add_argument("--recent", type=int, default=DEFAULT_RECENT)
493
+
494
+ activity = sub.add_parser("log")
495
+ activity.add_argument("--manager-id", required=True)
496
+ activity.add_argument("--task-group", default=None)
497
+ activity.add_argument("--task-id", default=None)
498
+ activity.add_argument("--kind", default=None)
499
+ activity.add_argument("--since", default=None)
500
+ activity.add_argument("--grep", default=None)
501
+ activity.add_argument("--open-followups", action="store_true")
502
+ activity.add_argument("--limit", type=int, default=DEFAULT_LIMIT)
394
503
  return parser
395
504
 
396
505
 
506
+ def _manager_state_changed(args: argparse.Namespace) -> bool:
507
+ if args.command in ("init", "new"):
508
+ return True
509
+ if args.command == "journal":
510
+ return args.journal_command == "add"
511
+ if args.command == "remove":
512
+ return args.confirm
513
+ if args.command == "task":
514
+ if args.task_command == "remove-child":
515
+ return args.confirm
516
+ return args.task_command in ("assign", "note", "sync", "run", "split", "update")
517
+ return False
518
+
519
+
520
+ def _register_manager_change(home: Path, manager_id: str) -> None:
521
+ try:
522
+ from .manager_registration import register_manager_source
523
+
524
+ registered = register_manager_source(home, manager_id)
525
+ except (ImportError, OSError, ValueError, RecursionError, subprocess.TimeoutExpired):
526
+ registered = False
527
+ if not registered:
528
+ print("okstra manager: knowledge registration is pending; run 'okstra doyouknow sync' to retry.", file=sys.stderr)
529
+
530
+
397
531
  def main(argv: list[str] | None = None) -> int:
398
532
  parser = _parser()
399
533
  args = parser.parse_args(_normalize_global_flags(argv if argv is not None else sys.argv[1:]))
@@ -521,9 +655,22 @@ def main(argv: list[str] | None = None) -> int:
521
655
  _emit("list-tasks", list_tasks(home, args.manager_id), args.json)
522
656
  elif args.command == "view":
523
657
  _emit("view", write_view(home, args.manager_id), args.json)
658
+ elif args.command == "journal" and args.journal_command == "add":
659
+ body = args.body if args.body is not None else read_body_file(args.body_file)
660
+ _emit("journal-add", add_journal_entry(home, args.manager_id, kind=args.kind, body=body,
661
+ task_group=args.task_group, task_id=args.task_id,
662
+ resolves=args.resolves), args.json)
663
+ elif args.command == "resume":
664
+ _emit("resume", resume_manager(home, args.manager_id, recent=args.recent), args.json)
665
+ elif args.command == "log":
666
+ _emit("log", read_activity_page(home, args.manager_id, task_group=args.task_group, task_id=args.task_id,
667
+ kind=args.kind, since=args.since, grep=args.grep,
668
+ open_followups=args.open_followups, limit=args.limit), args.json)
524
669
  else:
525
670
  parser.print_help()
526
671
  return 2
672
+ if _manager_state_changed(args):
673
+ _register_manager_change(home, args.manager_id)
527
674
  return 0
528
675
  except (ManagerError, ManagerPathError) as exc:
529
676
  print(f"okstra manager: {exc}", file=sys.stderr)
@@ -0,0 +1,126 @@
1
+ """Manager-only journal: decisions, findings, follow-ups and session summaries.
2
+
3
+ Child launch preparation does not read this file. Anything a child task must see
4
+ belongs in `task note` (directives.jsonl).
5
+
6
+ This module owns the journal vocabulary and the follow-up resolution rule; the log,
7
+ resume and view readers import them from here.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import secrets
12
+ from collections.abc import Mapping
13
+ from pathlib import Path
14
+
15
+ from okstra_ctl.jsonl import append_jsonl
16
+
17
+ from .doyouknow.contracts import DoyouknowError, reject_secrets
18
+ from .manager_paths import journal_jsonl_path, task_manifest_path
19
+ from .manager_store import ManagerError, _now_iso, _read_json, load_manager, read_jsonl_rows, task_selection
20
+
21
+ JOURNAL_ORIGIN = "journal"
22
+ DECISION = "decision"
23
+ FINDING = "finding"
24
+ FOLLOWUP = "followup"
25
+ SESSION_SUMMARY = "session-summary"
26
+ JOURNAL_KINDS = (DECISION, FINDING, FOLLOWUP, SESSION_SUMMARY)
27
+ MAX_BODY_CHARS = 4000
28
+
29
+
30
+ def resolved_entry_ids(journal_rows: list[dict]) -> set[str]:
31
+ """Ids that any journal row names in `resolves`."""
32
+ return {str(row["resolves"]) for row in journal_rows if row.get("resolves")}
33
+
34
+
35
+ def is_journal_kind(entry: Mapping[str, object], kind: str) -> bool:
36
+ """Whether a merged activity entry is a journal entry of `kind`."""
37
+ return entry["origin"] == JOURNAL_ORIGIN and entry["kind"] == kind
38
+
39
+
40
+ def is_open_followup(entry: Mapping[str, object], resolved: set[str]) -> bool:
41
+ row = entry["row"]
42
+ return is_journal_kind(entry, FOLLOWUP) and isinstance(row, Mapping) and row.get("id") not in resolved
43
+
44
+
45
+ def open_followups_oldest_first(entries_newest_first: list, resolved: set[str]) -> list:
46
+ return [entry for entry in reversed(entries_newest_first) if is_open_followup(entry, resolved)]
47
+
48
+
49
+ def read_body_file(path: Path) -> str:
50
+ """The `--body-file` text, read as UTF-8 and checked like `--body`."""
51
+ try:
52
+ return path.read_text(encoding="utf-8")
53
+ except (OSError, UnicodeDecodeError) as exc:
54
+ reason = exc.strerror if isinstance(exc, OSError) and exc.strerror else exc
55
+ raise ManagerError(f"failed to read --body-file {path}: {reason}") from exc
56
+
57
+
58
+ def _check_body(body: str) -> None:
59
+ if not body.strip():
60
+ raise ManagerError("journal body is empty")
61
+ if len(body) > MAX_BODY_CHARS:
62
+ raise ManagerError(f"journal body has {len(body)} characters; the limit is {MAX_BODY_CHARS}")
63
+ try:
64
+ reject_secrets(body)
65
+ except DoyouknowError as exc:
66
+ raise ManagerError(f"journal body refused: {exc}") from exc
67
+
68
+
69
+ def _check_resolves(rows: list[dict], resolves: str) -> None:
70
+ if not resolves:
71
+ return
72
+ target = next((row for row in rows if row.get("id") == resolves), None)
73
+ if target is None or target.get("kind") != FOLLOWUP:
74
+ raise ManagerError(f"--resolves must name a followup entry of this manager: {resolves}")
75
+ if resolves in resolved_entry_ids(rows):
76
+ raise ManagerError(f"followup is already resolved: {resolves}")
77
+
78
+
79
+ def _new_entry_id(when: str, rows: list[dict]) -> str:
80
+ stamp = when.replace("-", "").replace(":", "")
81
+ taken = {row.get("id") for row in rows}
82
+ while True:
83
+ candidate = f"j-{stamp}-{secrets.token_hex(2)}"
84
+ if candidate not in taken:
85
+ return candidate
86
+
87
+
88
+ def add_journal_entry(
89
+ home: Path,
90
+ manager_id: str,
91
+ *,
92
+ kind: str,
93
+ body: str,
94
+ task_group: str | None = None,
95
+ task_id: str | None = None,
96
+ resolves: str = "",
97
+ now: str | None = None,
98
+ ) -> dict:
99
+ """Append one journal entry after every check passes; a refused entry writes nothing."""
100
+ load_manager(home, manager_id)
101
+ if kind not in JOURNAL_KINDS:
102
+ raise ManagerError(f"journal kind must be one of {', '.join(JOURNAL_KINDS)}")
103
+ task = task_selection(task_group, task_id)
104
+ if task is not None:
105
+ # The path is a slug, so another spelling reaches the same task; store the manifest's names.
106
+ manifest = _read_json(task_manifest_path(home, manager_id, *task))
107
+ task = (str(manifest.get("taskGroup") or task[0]), str(manifest.get("taskId") or task[1]))
108
+ _check_body(body)
109
+ path = journal_jsonl_path(home, manager_id)
110
+ rows, _ = read_jsonl_rows(path)
111
+ _check_resolves(rows, resolves)
112
+ when = now or _now_iso()
113
+ row = {
114
+ "id": _new_entry_id(when, rows),
115
+ "kind": kind,
116
+ "body": body,
117
+ "createdAt": when,
118
+ "taskGroup": task[0] if task is not None else "",
119
+ "taskId": task[1] if task is not None else "",
120
+ "resolves": resolves,
121
+ }
122
+ try:
123
+ append_jsonl(path, row)
124
+ except OSError as exc:
125
+ raise ManagerError(f"failed to write {path}: {exc.strerror or exc}") from exc
126
+ return row
@@ -4,7 +4,7 @@ from __future__ import annotations
4
4
  import shlex
5
5
  from pathlib import Path
6
6
 
7
- from okstra_ctl.jsonl import append_jsonl, read_jsonl
7
+ from okstra_ctl.jsonl import read_jsonl
8
8
  from okstra_ctl.phases.discussion.followup import RECOMMENDED_PHASE as DISCUSSION_FOLLOW_UP_PHASE
9
9
  from okstra_ctl.phases.discussion.followup import brief_revision_ref
10
10
  from okstra_ctl.phases.discussion.store import same_task
@@ -19,7 +19,7 @@ from .manager_paths import (
19
19
  snapshots_json_path,
20
20
  task_manifest_path,
21
21
  )
22
- from .manager_store import ManagerError, _now_iso, _read_json, _read_json_default, _write_json
22
+ from .manager_store import ManagerError, _now_iso, _read_json, _read_json_default, _write_json, record_event
23
23
  from .manager_sync import _snapshot_child, summary_bucket
24
24
 
25
25
 
@@ -205,7 +205,7 @@ def _record_launch_prepared(
205
205
  )
206
206
  child["launch"] = launch
207
207
  _write_json(children_json_path(home, manager_id, task_group, task_id), children)
208
- append_jsonl(
208
+ record_event(
209
209
  events_jsonl_path(home, manager_id, task_group, task_id),
210
210
  {
211
211
  "event": "child-launch-prepared",