okstra 0.231.0 → 0.232.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 (143) hide show
  1. package/README.md +15 -3
  2. package/dist/cli-registry.mjs +6 -0
  3. package/dist/cli-registry.mjs.map +1 -1
  4. package/dist/commands/memory/memory.mjs +9 -55
  5. package/dist/commands/memory/memory.mjs.map +1 -1
  6. package/dist/lib/memory-auto-register.d.mts +1 -0
  7. package/dist/lib/memory-auto-register.mjs +113 -0
  8. package/dist/lib/memory-auto-register.mjs.map +1 -0
  9. package/dist/lib/memory-entry-contract.d.mts +12 -0
  10. package/dist/lib/memory-entry-contract.mjs +46 -0
  11. package/dist/lib/memory-entry-contract.mjs.map +1 -0
  12. package/dist/lib/python-helper.d.mts +1 -1
  13. package/dist/lib/python-helper.mjs +3 -2
  14. package/dist/lib/python-helper.mjs.map +1 -1
  15. package/dist/lib/record-secrets.d.mts +1 -0
  16. package/dist/lib/record-secrets.mjs +28 -0
  17. package/dist/lib/record-secrets.mjs.map +1 -0
  18. package/dist/lib/types.d.mts +2 -1
  19. package/docs/architecture/storage-model.md +129 -2
  20. package/docs/architecture.md +11 -2
  21. package/docs/cli.md +234 -0
  22. package/docs/project-structure-overview.md +2 -1
  23. package/package.json +1 -1
  24. package/runtime/BUILD.json +2 -2
  25. package/runtime/agents/common.json +8 -8
  26. package/runtime/agents/roles/verifier.json +2 -4
  27. package/runtime/bin/okstra-provider-exec.py +10 -4
  28. package/runtime/prompts/coding-preflight/architectures/hexagonal.md +23 -30
  29. package/runtime/prompts/coding-preflight/authoring-checks.md +17 -0
  30. package/runtime/prompts/coding-preflight/clean-code.md +85 -281
  31. package/runtime/prompts/coding-preflight/frameworks/node-server.md +2 -3
  32. package/runtime/prompts/coding-preflight/languages/java.md +3 -5
  33. package/runtime/prompts/coding-preflight/languages/javascript-typescript.md +5 -12
  34. package/runtime/prompts/coding-preflight/languages/kotlin.md +2 -4
  35. package/runtime/prompts/coding-preflight/languages/python.md +2 -7
  36. package/runtime/prompts/coding-preflight/languages/rust.md +2 -8
  37. package/runtime/prompts/coding-preflight/languages/sql.md +2 -4
  38. package/runtime/prompts/coding-preflight/overview.md +25 -38
  39. package/runtime/prompts/coding-preflight/review-rules.json +30 -0
  40. package/runtime/prompts/duties/code-reviewer.json +15 -18
  41. package/runtime/prompts/duties/implementation-verifier.json +1 -0
  42. package/runtime/prompts/lead/convergence.md +3 -3
  43. package/runtime/prompts/lead/okstra-lead-contract.md +2 -2
  44. package/runtime/prompts/lead/report-writer.md +1 -1
  45. package/runtime/prompts/lead/team-contract.md +1 -1
  46. package/runtime/prompts/profiles/_clarification-recommendation.md +3 -2
  47. package/runtime/prompts/profiles/_coding-conventions-preflight.md +41 -6
  48. package/runtime/python/okstra_ctl/agent/invocation.py +121 -36
  49. package/runtime/python/okstra_ctl/agent/prompt_cli/cli.py +6 -0
  50. package/runtime/python/okstra_ctl/agent/prompt_cli/materialize.py +30 -4
  51. package/runtime/python/okstra_ctl/agent/standalone.py +3 -0
  52. package/runtime/python/okstra_ctl/analysis_packet.py +2 -19
  53. package/runtime/python/okstra_ctl/approval_decisions.py +16 -0
  54. package/runtime/python/okstra_ctl/attempt_evidence.py +10 -0
  55. package/runtime/python/okstra_ctl/business_flow/invocation.py +35 -3
  56. package/runtime/python/okstra_ctl/code_review_census.py +71 -7
  57. package/runtime/python/okstra_ctl/code_review_coverage.py +4 -274
  58. package/runtime/python/okstra_ctl/code_review_integrity.py +154 -0
  59. package/runtime/python/okstra_ctl/code_review_invocation.py +212 -0
  60. package/runtime/python/okstra_ctl/code_review_scope.py +36 -9
  61. package/runtime/python/okstra_ctl/code_review_target.py +85 -11
  62. package/runtime/python/okstra_ctl/consumers.py +12 -9
  63. package/runtime/python/okstra_ctl/convergence.py +112 -20
  64. package/runtime/python/okstra_ctl/convergence_engine.py +1 -0
  65. package/runtime/python/okstra_ctl/convergence_provenance.py +27 -11
  66. package/runtime/python/okstra_ctl/correction_round.py +6 -1
  67. package/runtime/python/okstra_ctl/design_review.py +207 -0
  68. package/runtime/python/okstra_ctl/design_review_evidence.py +297 -0
  69. package/runtime/python/okstra_ctl/dispatch_checkpoints.py +28 -5
  70. package/runtime/python/okstra_ctl/dispatch_core.py +3 -11
  71. package/runtime/python/okstra_ctl/doctor.py +8 -25
  72. package/runtime/python/okstra_ctl/doyouknow/__init__.py +9 -0
  73. package/runtime/python/okstra_ctl/doyouknow/cli.py +91 -0
  74. package/runtime/python/okstra_ctl/doyouknow/config.py +58 -0
  75. package/runtime/python/okstra_ctl/doyouknow/contracts.py +184 -0
  76. package/runtime/python/okstra_ctl/doyouknow/identity.py +22 -0
  77. package/runtime/python/okstra_ctl/doyouknow/paths.py +22 -0
  78. package/runtime/python/okstra_ctl/doyouknow/pending.py +72 -0
  79. package/runtime/python/okstra_ctl/doyouknow/registration.py +260 -0
  80. package/runtime/python/okstra_ctl/doyouknow/source_contracts.py +128 -0
  81. package/runtime/python/okstra_ctl/doyouknow/source_store.py +172 -0
  82. package/runtime/python/okstra_ctl/doyouknow/sources/io.py +36 -0
  83. package/runtime/python/okstra_ctl/doyouknow/sources/manager.py +261 -0
  84. package/runtime/python/okstra_ctl/doyouknow/sources/memory.py +179 -0
  85. package/runtime/python/okstra_ctl/doyouknow/sources/task.py +95 -0
  86. package/runtime/python/okstra_ctl/doyouknow/store.py +260 -0
  87. package/runtime/python/okstra_ctl/doyouknow/sync.py +58 -0
  88. package/runtime/python/okstra_ctl/execution_mutation_audit.py +18 -2
  89. package/runtime/python/okstra_ctl/file_size_cap.py +3 -4
  90. package/runtime/python/okstra_ctl/json_boundary.py +21 -2
  91. package/runtime/python/okstra_ctl/jsonl.py +21 -0
  92. package/runtime/python/okstra_ctl/manager_cli.py +26 -0
  93. package/runtime/python/okstra_ctl/manager_registration.py +29 -0
  94. package/runtime/python/okstra_ctl/manager_sync.py +3 -22
  95. package/runtime/python/okstra_ctl/model_io/renderers.py +13 -2
  96. package/runtime/python/okstra_ctl/model_io_cli.py +7 -1
  97. package/runtime/python/okstra_ctl/phases/final_verification/validation.py +20 -0
  98. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-deliverable.md +12 -2
  99. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-diff-review.md +19 -6
  100. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-self-check.md +5 -3
  101. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-verifier.md +39 -11
  102. package/runtime/python/okstra_ctl/phases/implementation/report_assets/implementation.template.html +13 -0
  103. package/runtime/python/okstra_ctl/phases/implementation/spec.md +26 -1
  104. package/runtime/python/okstra_ctl/phases/implementation/validation.py +86 -2
  105. package/runtime/python/okstra_ctl/phases/implementation_planning/authoring.py +4 -0
  106. package/runtime/python/okstra_ctl/phases/implementation_planning/profile.md +1 -1
  107. package/runtime/python/okstra_ctl/report_assembly.py +15 -0
  108. package/runtime/python/okstra_ctl/report_narrative.py +3 -0
  109. package/runtime/python/okstra_ctl/report_prose_keys.py +7 -0
  110. package/runtime/python/okstra_ctl/report_synthesis_packet.py +19 -2
  111. package/runtime/python/okstra_ctl/review_policy.py +359 -0
  112. package/runtime/python/okstra_ctl/review_verdicts.py +291 -0
  113. package/runtime/python/okstra_ctl/run.py +24 -1
  114. package/runtime/python/okstra_ctl/stage_done.py +11 -0
  115. package/runtime/python/okstra_ctl/standalone_review_audit.py +28 -0
  116. package/runtime/python/okstra_ctl/team.py +3 -1
  117. package/runtime/python/okstra_ctl/verification_generation.py +23 -1
  118. package/runtime/python/okstra_ctl/verification_input_types.py +15 -1
  119. package/runtime/python/okstra_ctl/verification_inputs.py +28 -6
  120. package/runtime/python/okstra_ctl/verification_invocation.py +7 -1
  121. package/runtime/python/okstra_ctl/verification_target.py +2 -0
  122. package/runtime/python/okstra_ctl/worker_dispatch.py +3 -1
  123. package/runtime/python/okstra_ctl/worker_prompt_headers.py +24 -9
  124. package/runtime/python/okstra_ctl/worker_runner.py +66 -10
  125. package/runtime/python/okstra_ctl/wrapper_status.py +16 -0
  126. package/runtime/python/okstra_ctl/write_policy.py +34 -1
  127. package/runtime/python/okstra_project/__init__.py +2 -0
  128. package/runtime/python/okstra_project/dirs.py +18 -0
  129. package/runtime/python/okstra_project/state.py +25 -20
  130. package/runtime/schemas/doyouknow-config-v1.schema.json +20 -0
  131. package/runtime/schemas/doyouknow-v1.schema.json +65 -0
  132. package/runtime/schemas/final-report-v2.0.schema.json +157 -0
  133. package/runtime/schemas/final-report-v3.0.schema.json +157 -0
  134. package/runtime/schemas/memory-entry-contract-v1.json +11 -0
  135. package/runtime/schemas/record-secret-patterns.json +41 -0
  136. package/runtime/skills/okstra-code-review/SKILL.md +71 -123
  137. package/runtime/skills/okstra-code-review/references/census-rules.md +29 -105
  138. package/runtime/skills/okstra-code-review/references/review-calibration.md +34 -54
  139. package/runtime/skills/okstra-manager/SKILL.md +7 -0
  140. package/runtime/skills/okstra-memory/SKILL.md +7 -0
  141. package/runtime/templates/implementation-worker-preamble.md +4 -9
  142. package/runtime/templates/worker-prompt-preamble.md +4 -12
  143. package/runtime/validators/validate-run.py +17 -8
@@ -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
@@ -203,6 +203,7 @@ def load_owned_object(
203
203
  artifact: str,
204
204
  schema: Mapping[str, Any] | None = None,
205
205
  validate_cross_fields: Callable[[dict[str, Any]], object] | None = None,
206
+ max_bytes: int | None = None,
206
207
  ) -> dict[str, Any]:
207
208
  """Load and validate one okstra-owned JSON object."""
208
209
  return load_owned_object_snapshot(
@@ -210,6 +211,7 @@ def load_owned_object(
210
211
  artifact=artifact,
211
212
  schema=schema,
212
213
  validate_cross_fields=validate_cross_fields,
214
+ max_bytes=max_bytes,
213
215
  ).value
214
216
 
215
217
 
@@ -219,10 +221,13 @@ def load_owned_object_snapshot(
219
221
  artifact: str,
220
222
  schema: Mapping[str, Any] | None = None,
221
223
  validate_cross_fields: Callable[[dict[str, Any]], object] | None = None,
224
+ max_bytes: int | None = None,
222
225
  ) -> OwnedJsonSnapshot:
223
226
  """한 번 읽은 바이트에서 객체를 파싱·검증해 함께 반환한다."""
224
227
  try:
225
- raw_bytes = path.read_bytes()
228
+ raw_bytes = path.read_bytes() if max_bytes is None else read_bounded_bytes(
229
+ path, max_bytes=max_bytes, artifact=artifact,
230
+ )
226
231
  value = json.loads(
227
232
  raw_bytes.decode("utf-8"),
228
233
  parse_constant=_reject_nonstandard_json_constant,
@@ -249,19 +254,33 @@ def load_owned_object_snapshot(
249
254
  )
250
255
 
251
256
 
257
+ def read_bounded_bytes(path: Path, *, max_bytes: int, artifact: str) -> bytes:
258
+ with path.open("rb") as handle:
259
+ content = handle.read(max_bytes + 1)
260
+ if len(content) > max_bytes:
261
+ raise JsonBoundaryError(path, artifact, f"input exceeds {max_bytes} bytes")
262
+ return content
263
+
264
+
252
265
  def load_external_json(
253
266
  source: ExternalJsonSource,
254
267
  *,
255
268
  artifact: str,
256
269
  object_pairs_hook: Callable[[list[tuple[str, Any]]], Any] | None = None,
270
+ max_bytes: int | None = None,
257
271
  ) -> Any:
258
272
  """Load external JSON without applying an owned-artifact contract."""
259
273
  if not isinstance(source, ExternalJsonSource):
260
274
  raise TypeError("load_external_json requires ExternalJsonSource")
261
275
  path = source.path
262
276
  try:
277
+ if max_bytes is None:
278
+ content = path.read_text(encoding="utf-8")
279
+ else:
280
+ raw = read_bounded_bytes(path, max_bytes=max_bytes, artifact=artifact)
281
+ content = raw.decode("utf-8")
263
282
  return json.loads(
264
- path.read_text(encoding="utf-8"),
283
+ content,
265
284
  object_pairs_hook=object_pairs_hook,
266
285
  )
267
286
  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
 
@@ -394,6 +395,29 @@ def _parser() -> argparse.ArgumentParser:
394
395
  return parser
395
396
 
396
397
 
398
+ def _manager_state_changed(args: argparse.Namespace) -> bool:
399
+ if args.command in ("init", "new"):
400
+ return True
401
+ if args.command == "remove":
402
+ return args.confirm
403
+ if args.command == "task":
404
+ if args.task_command == "remove-child":
405
+ return args.confirm
406
+ return args.task_command in ("assign", "note", "sync", "run", "split", "update")
407
+ return False
408
+
409
+
410
+ def _register_manager_change(home: Path, manager_id: str) -> None:
411
+ try:
412
+ from .manager_registration import register_manager_source
413
+
414
+ registered = register_manager_source(home, manager_id)
415
+ except (ImportError, OSError, ValueError, RecursionError, subprocess.TimeoutExpired):
416
+ registered = False
417
+ if not registered:
418
+ print("okstra manager: knowledge registration is pending; run 'okstra doyouknow sync' to retry.", file=sys.stderr)
419
+
420
+
397
421
  def main(argv: list[str] | None = None) -> int:
398
422
  parser = _parser()
399
423
  args = parser.parse_args(_normalize_global_flags(argv if argv is not None else sys.argv[1:]))
@@ -524,6 +548,8 @@ def main(argv: list[str] | None = None) -> int:
524
548
  else:
525
549
  parser.print_help()
526
550
  return 2
551
+ if _manager_state_changed(args):
552
+ _register_manager_change(home, args.manager_id)
527
553
  return 0
528
554
  except (ManagerError, ManagerPathError) as exc:
529
555
  print(f"okstra manager: {exc}", file=sys.stderr)
@@ -0,0 +1,29 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import subprocess
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ from .manager_paths import canonical_manager_id
9
+
10
+ REGISTRATION_TIMEOUT_SECONDS = 5
11
+
12
+
13
+ def register_manager_source(home: Path, manager_id: str) -> bool:
14
+ from .doyouknow.config import load_config
15
+ from .doyouknow.pending import enqueue_source
16
+ from .doyouknow.source_contracts import SourceRef
17
+
18
+ settings = load_config(home=home)
19
+ if not settings["autoRegister"] or "manager" not in settings["sources"]:
20
+ return True
21
+ ref = SourceRef("manager", canonical_manager_id(manager_id), "$manager")
22
+ ticket = enqueue_source(ref, home=home)
23
+ result = subprocess.run(
24
+ [sys.executable, "-m", "okstra_ctl.doyouknow.cli", "register", "--ticket", ticket, "--json"],
25
+ env={**os.environ, "OKSTRA_HOME": str(home.expanduser().resolve())},
26
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
27
+ timeout=REGISTRATION_TIMEOUT_SECONDS, check=False,
28
+ )
29
+ return result.returncode == 0
@@ -4,7 +4,7 @@ from __future__ import annotations
4
4
  from datetime import datetime
5
5
  from pathlib import Path
6
6
 
7
- from okstra_project import TASKS_RELATIVE, StateError, parse_task_key, read_task_catalog, read_task_manifest, slugify
7
+ from okstra_project import StateError, read_task_manifest, resolve_task_root_read_only
8
8
  from okstra_project.dirs import TASK_MANIFEST_FILENAME
9
9
 
10
10
  from . import next_phase
@@ -39,25 +39,6 @@ def _list_field(payload: dict, field: str) -> list:
39
39
  return list(value) if isinstance(value, list) else []
40
40
 
41
41
 
42
- def _resolve_task_root_read_only(project_root: Path, task_key: str) -> Path | None:
43
- _, task_group, task_id = parse_task_key(task_key)
44
- requested_key = task_key.lower()
45
- for entry in read_task_catalog(project_root):
46
- entry_key = entry.get("taskKey") or ""
47
- if not isinstance(entry_key, str) or entry_key.lower() != requested_key:
48
- continue
49
- relative_path = entry.get("taskRootPath") or entry.get("taskRoot") or ""
50
- if not isinstance(relative_path, str) or not relative_path:
51
- continue
52
- candidate = project_root / relative_path if not Path(relative_path).is_absolute() else Path(relative_path)
53
- if candidate.is_dir():
54
- return candidate
55
- slug_path = project_root / TASKS_RELATIVE / slugify(task_group) / slugify(task_id)
56
- if slug_path.is_dir():
57
- return slug_path
58
- return None
59
-
60
-
61
42
  DISCUSSION_TASK_TYPE = "discussion"
62
43
 
63
44
 
@@ -77,7 +58,7 @@ def _snapshot_child(project_root: Path, child: dict) -> dict:
77
58
  base = _base_child_snapshot(child)
78
59
  task_key = base["taskKey"]
79
60
  try:
80
- task_dir = _resolve_task_root_read_only(project_root, task_key)
61
+ task_dir = resolve_task_root_read_only(project_root, task_key)
81
62
  if task_dir is None:
82
63
  return base
83
64
  manifest = read_task_manifest(task_dir) or {}
@@ -183,7 +164,7 @@ def _manifest_changed_since(project: dict | None, task_key: str, synced: int | N
183
164
  root = Path(str(project.get("projectRoot") or ""))
184
165
  if not root.is_dir():
185
166
  return False
186
- task_dir = _resolve_task_root_read_only(root, task_key)
167
+ task_dir = resolve_task_root_read_only(root, task_key)
187
168
  manifest_path = task_dir / TASK_MANIFEST_FILENAME if task_dir is not None else None
188
169
  if manifest_path is None or not manifest_path.is_file():
189
170
  return False
@@ -6,7 +6,7 @@
6
6
  from __future__ import annotations
7
7
 
8
8
  from pathlib import Path
9
- from typing import Any, Mapping
9
+ from typing import Any, Mapping, Sequence
10
10
 
11
11
  from okstra_project import StateError, parse_task_key, slugify
12
12
 
@@ -20,6 +20,7 @@ from ..fixed_text import line as _line, scalar as _value, quoted_value_lines
20
20
  from ..json_boundary import JsonBoundaryError, load_owned_object
21
21
  from ..paths import find_asset_root, okstra_home
22
22
  from ..ports.verification_inputs import VerificationInputStore
23
+ from ..review_policy import render_review_policy, review_policy_context
23
24
  from ..phases.catalog import PhaseAssetError, profile_markdown
24
25
  from ..recap import assemble_group_recap, assemble_recap
25
26
  from ..role_requirements import RoleProfileError, load_role_profile
@@ -148,7 +149,8 @@ def render_project_context(project_root: Path, task_ref: str = "") -> str:
148
149
 
149
150
 
150
151
  def render_verification_input(
151
- run_manifest: Path, store: VerificationInputStore,
152
+ run_manifest: Path, store: VerificationInputStore, *, source_paths: Sequence[str] = (),
153
+ resources: Sequence[str] = (),
152
154
  ) -> str:
153
155
  reference, inputs = _load_verification_input(run_manifest, store)
154
156
  rows = [
@@ -162,6 +164,15 @@ def render_verification_input(
162
164
  "\n## QA Commands\n\n",
163
165
  *quoted_value_lines("QA commands", inputs["qaCommands"]),
164
166
  ]
167
+ if "reviewPolicy" in inputs:
168
+ project_paths, manifests = (review_policy_context(
169
+ Path(inputs["sourceRoot"]), "HEAD", source_paths,
170
+ ) if source_paths else ((), {}))
171
+ rows.append(render_review_policy(
172
+ inputs["reviewPolicy"], source_paths, project_paths=project_paths,
173
+ manifest_contents=manifests,
174
+ resources=resources,
175
+ ))
165
176
  rows.append("\n## QA Source Observations\n\n")
166
177
  if "qaSourceObservations" in inputs:
167
178
  rows.extend(quoted_value_lines(
@@ -32,7 +32,7 @@ from .model_io.renderers import (
32
32
  _CLI_EPILOG = r"""Usage:
33
33
  okstra model-io project-context --project-root <dir> [--task-ref <task-id|task-key|task-manifest-path>]
34
34
  okstra model-io run-input --run-manifest <path>
35
- okstra model-io verification-input --run-manifest <path>
35
+ okstra model-io verification-input --run-manifest <path> [--source-path <relative-file> ...] [--resource <pack-relative-resource> ...]
36
36
  okstra model-io active-context-input --project-root <dir> --run-manifest <path>
37
37
  okstra model-io schedule-input --project-root <dir> --task-group <id>
38
38
  okstra model-io code-review-input --project-root <dir> --base <ref> --head <ref>
@@ -57,6 +57,10 @@ def build_parser() -> argparse.ArgumentParser:
57
57
  run.add_argument("--run-manifest", required=True)
58
58
  verification = commands.add_parser("verification-input")
59
59
  verification.add_argument("--run-manifest", required=True)
60
+ verification.add_argument("--source-path", action="append", default=[],
61
+ help="load frozen rules applicable to this repository-relative source")
62
+ verification.add_argument("--resource", action="append", default=[],
63
+ help="load an additional captured pack-relative rule resource")
60
64
  active = commands.add_parser("active-context-input")
61
65
  active.add_argument("--project-root", required=True)
62
66
  active.add_argument("--run-manifest", required=True)
@@ -101,6 +105,8 @@ def main(argv: list[str] | None = None) -> int:
101
105
  elif args.command == "verification-input":
102
106
  text = render_verification_input(
103
107
  Path(args.run_manifest), default_verification_input_store(),
108
+ source_paths=args.source_path,
109
+ resources=args.resource,
104
110
  )
105
111
  elif args.command == "active-context-input":
106
112
  text = render_active_context_input(
@@ -16,6 +16,26 @@ from okstra_ctl.report_execution_evidence import (
16
16
  )
17
17
  from okstra_ctl.verification_target import TARGET_FIELD_RES, read_verification_target
18
18
 
19
+
20
+ def validate_implementation_review_evidence(project: Path, manifest_path: Path) -> None:
21
+ from dataclasses import replace
22
+ from okstra_ctl.design_review_evidence import design_review_required, validate_stage_design_report
23
+ from okstra_ctl.json_boundary import load_owned_object
24
+ from okstra_ctl.paths import RunRef
25
+
26
+ manifest = load_owned_object(manifest_path, artifact="run manifest")
27
+ if manifest.get("taskType") != "final-verification" or not design_review_required(project, manifest):
28
+ return
29
+ target = read_verification_target(project, str(manifest.get("verificationTargetPath") or ""))
30
+ if target is None or set(target["reports"]) != target["stages"]:
31
+ raise ValueError("final verification requires every source implementation review report")
32
+ ref = RunRef.from_manifest(manifest_path, manifest).sibling("implementation")
33
+ for stage, location in target["reports"].items():
34
+ report = Path(location)
35
+ if not report.is_absolute():
36
+ report = project / report if location.startswith(".okstra/") else replace(ref, stage=stage).run_dir / report
37
+ validate_stage_design_report(project, report, stage, task_key=str(manifest["taskKey"]))
38
+
19
39
  _ADDED_SURFACE_NO_CALLER_RE = re.compile(r"^\s*none\b", re.IGNORECASE)
20
40
 
21
41
 
@@ -6,6 +6,16 @@ are collected and convergence finished. Phase 1-5 do not need it.
6
6
 
7
7
  # Implementation profile — Deliverable sidecar
8
8
 
9
+ For verification-input 4.0 runs, report assembly owns `verifierResults[].designReview`
10
+ and derives verifier verdicts from sealed current returns. Do not author that evidence
11
+ or remove its findings to obtain acceptance. Every configured verifier owes its own
12
+ complete function/rule accounting. On a correction round, the full stage is inspected
13
+ again and earlier blocking findings receive explicit `Design Carry` dispositions;
14
+ their history and the bases for accepted risks remain in the report. `stage-done`
15
+ requires the same accepted task/stage/base/head evidence. Enforcement is in
16
+ `design_review_evidence.py`, report assembly and stage completion; legacy inputs
17
+ retain their existing contract.
18
+
9
19
  > **When to read**: lead reads this file ONCE at the start of Phase 6 (after Phase 5.5 convergence completes, before constructing the report-writer dispatch prompt). Carries the final-report deliverable shape, the lead minor fix, lead's post-stage persistence rules, and the self-review checklist.
10
20
 
11
21
  ## Required deliverable shape (final report, in addition to the standard sections)
@@ -13,7 +23,7 @@ are collected and convergence finished. Phase 1-5 do not need it.
13
23
  - **Plan link & approval evidence**: path to the approved `final-report.md`, the exact quoted approval marker, AND the executed stage number / title quoted from the Stage Map row. For a selected-direction plan, also quote `selectedDirectionRef.optionId`, `snapshotPath`, and the validated snapshot digest; for a legacy plan, quote the effective `implementation-option` or the Recommended Option fallback.
14
24
  - **Commit list**: each commit's SHA (or short SHA), message, and the plan step(s) / TDD cycle it satisfies. A lead minor fix commit is listed too, with `planStep` `Lead minor fix (<finding ids>)`.
15
25
  - **Lead minor fixes**: when the lead fixed verifier findings in this run, pass each `implementation.leadFixes[]` entry to the report writer as recorded (§"Lead minor fix"). Omit the field when there was none.
16
- - **Correction rounds**: when this run ran correction rounds, pass one `implementation.correctionRounds[]` entry per round to the report writer — `round`, `findingIds`, `baseCommit`, `commit`, each verifier's re-verification `verifierVerdicts`, and `result` (§"Correction round"). `verifierResults` then carries the last round's verdicts. Omit the field when there was none.
26
+ - **Correction rounds**: when this run ran correction rounds, pass one `implementation.correctionRounds[]` entry per round to the report writer — `round`, `findingIds`, `baseCommit`, `commit`, each verifier's re-verification `verifierVerdicts`, and `result` (§"Correction round"). `verifierResults` then carries the last round's verdicts, and each row's `discrepancy` carries only a divergence in that verifier's last-round rerun: it stays empty when the last rerun matched. The change from an initial `FAIL` to a last-round `PASS` is recorded in `correctionRounds[].verifierVerdicts`, never in `discrepancy` — `_validate_verifier_discrepancy_is_not_passed` reads text there beside `PASS` as an unresolved divergence. The report-writer packet states this rule for every correction-round run (`report_synthesis_packet.ReportSynthesisPacket._task_instructions`). Omit the field when there was none.
17
27
  - **Diff summary**: capture `git diff --stat <base>..<captured-head>` and `git diff --numstat <base>..<captured-head>` for the full implementation stage, including after a fix run. Supply both outputs to the report writer; put each file's added/deleted counts alone in `diffSummary.files[].lines` (`+150/-0`) and one sentence on what the change in that file does in `diffSummary.files[].summary` — the report renders `summary` as the file's "what it does" column and `lines` as a separate number column. Do not substitute a fix-run aggregate or carry forward older statistics. If the captured commits are unavailable, identify the missing reference in the evidence instead of inventing counts.
18
28
  - **Change narrative scope**: `userNarrative.changeExplanation` describes the same scope as `diffSummary` — the whole stage from its base, every file the table lists. On a fix run, state what the fix run itself changed (its commits and files) as a separate sentence; never present the fix-run delta as the stage's change.
19
29
  - **Out-of-plan edits block**: every file edited that was not in the approved plan's file list, with rationale (empty block is acceptable and preferred)
@@ -45,7 +55,7 @@ are collected and convergence finished. Phase 1-5 do not need it.
45
55
 
46
56
  ## Lead minor fix (decided after convergence, before the report-writer dispatch)
47
57
 
48
- **Not in an evidence-contract run.** When the run manifest carries `verificationEvidenceVersion`, there is no lead minor fix: every fix, however small, goes through a correction round below, so the executor commits it and a new generation is sealed before the verifiers check it again. **Enforced:** `scripts/okstra_ctl/phases/implementation/validation.py` `_validate_lead_fixes` blocks any `implementation.leadFixes` entry in such a run, and `validate_settled_round_was_reverified` blocks a stage settled after correction round N without each verifier's records of generation N + 1. Runs without the field keep the rules below.
58
+ **Not in an evidence-contract run.** When the run manifest carries `verificationEvidenceVersion`, there is no lead minor fix: every fix, however small, goes through a correction round below, so the executor commits it and a new generation is sealed before the verifiers check it again. **Enforced:** `scripts/okstra_ctl/phases/implementation/validation.py` `_validate_lead_fixes` blocks any `implementation.leadFixes` entry in such a run, and `validate_settled_round_was_reverified` blocks a stage settled after correction round N without the records of generation N + 1 of each verifier that generation gives a check it may run. Runs without the field keep the rules below.
49
59
 
50
60
  When the synthesised verdict would be `FAIL` only because of verifier findings that are small and local, the lead fixes them itself in this run instead of ending it and opening a fix run. Decide after Phase 5.5 convergence, before building the report-writer dispatch prompt and before "Lead post-stage persistence" below. No worker dispatch is open then, so the edit falls inside no read-only worker's mutation audit window. Never edit while a verifier, convergence, or report-writer dispatch is running: its audit reports `readonly source changed` and discards that worker's result.
51
61
 
@@ -27,16 +27,25 @@ Do not scan holistically and stop when it "looks fine". Work the matrix exhausti
27
27
 
28
28
  ## Method — enumerate the diff, then walk every (file × applicable-rule) cell
29
29
 
30
- 1. **List every changed file:** `git diff --name-only <stage-base>..HEAD`. That list is your worklist — cover it to the end; no sampling.
30
+ Use the captured `review-rules.json` IDs and `clean-code.md` "Finding evidence
31
+ and grading" for every finding. Apply M1 and M2 to each changed function, including
32
+ named test helpers. Execution correctness does not downgrade a clear naming or
33
+ readability violation. Return a plan conflict when the authorized placement cannot
34
+ satisfy the rules; do not retain a violation solely to obey a file restriction.
35
+ Resolve conflicts by `overview.md` policy precedence: explicit repository
36
+ instructions and declared architecture, the common pack, then surrounding code
37
+ conventions. Existing violations alone do not waive an explicit rule.
38
+
39
+ 1. **List every changed file:** `git diff --name-only <stage-base>..HEAD`. Apply the shared census exclusion policy and record each exclusion with its reason; executable configuration is not excluded by extension alone. Cover the retained worklist to the end; no sampling.
31
40
  2. **Classify each file and select its rule set** from the conventions the preflight already loaded (do NOT re-derive the rules here — read them from the routed pack):
32
- - any source file → `clean-code.md`: truthful + standalone names, one identifier one meaning per file (a key parameter must not take the name a sibling signature gives the entity), plain-English summary test, single-purpose ≤50-line functions, DRY (incl. scattered domain literals + documented forks), YAGNI, no magic numbers, shallow nesting, comments explain why.
33
- - The YAGNI cell also counts callers, not just their existence: an abstraction layer this diff *introduces* — helper module, strategy / factory / builder, indirection or wrapper layer, interface or abstract base — with exactly **one** caller after the change is an inline candidate under `overview.md` core principle 2 ("name the second caller now, or inline"). Collapse it into that call site unless one of four exits applies and you record which: the approved plan declares it as a test seam or variation-point extraction, the project-context preflight projection declares hexagonal architecture and it is a port at the domain boundary, it breaks a real import cycle, or its single caller is a published package's public API. A function extracted only to get a body under the 50-line cap is not this finding.
41
+ - any file retained by the shared census exclusion policy → applicable `clean-code.md` checks: truthful + standalone names, one identifier one meaning per file (a key parameter must not take the name a sibling signature gives the entity), plain-English summary test, cohesive responsibility, manageable complexity and consistent abstraction levels, DRY (incl. scattered domain literals + documented forks), YAGNI, no magic numbers, shallow nesting, comments explain why. More than 50 effective function lines prompts closer review; length alone is not a finding or a reason to split.
42
+ - The YAGNI cell also counts callers, not just their existence: an abstraction layer this diff *introduces* — helper module, strategy / factory / builder, indirection or wrapper layer, interface or abstract base — with exactly **one** caller after the change is an inline candidate under `overview.md` core principle 2 ("name the second caller now, or inline"). Collapse it into that call site unless one of four exits applies and you record which: the approved plan declares it as a test seam or variation-point extraction, the project-context preflight projection declares hexagonal architecture and it is a port at the domain boundary, it breaks a real import cycle, or its single caller is a published package's public API. This targets reusable layers, not a local helper that names a cohesive step or separates mixed abstraction levels; line count alone does not justify extraction.
34
43
  - The YAGNI cell is a grep, not an impression: for every identifier this diff adds — and every one whose last caller it removes — search the whole repository and name the caller you found. A declaration-only, test-only, or commented-out hit is not a caller. Zero callers means delete it here (or fold an added parameter back into its single call site), unless the approved plan reserves it for a named later stage or something outside project code calls it (framework entrypoint, implemented interface method, migration hook, published-package API) — in which case record that justification in the audit note. Fixing it now is cheaper than the verifier's Static design gate, where the same finding is blocking and fails the stage (`_implementation-verifier.md` "Caller-less identifier").
35
44
  - a file that wraps a third-party / library call → `clean-code.md` "Wrapping a third-party call": the wrapper adds behaviour the library does not already provide (read the installed library source before keeping a recovery branch — a `catch` repeating the library's own retry recovers nothing), no comment names a condition the call site does not establish, and a rethrow keeps the original error as `cause`.
36
45
  - a file that decides, mutates, or persists state → `clean-code.md` "Mutation and state boundaries": decide on the direct identifier rather than a status/flag proxy, capture before-state in one snapshot ahead of the mutating boundary, update only this work's owned fields on an existing row, re-read state before calling a zero-affected-rows write success or failure, put priority-between-inputs in a named domain function, and keep error messages to what was actually observed. Also check that no state union/enum was re-declared beside an authoritative one the domain or a dependency exports.
37
46
  - test file (`*.spec.*` / `*.test.*` / `test_*.py` / `*_test.go` …) → `clean-code.md` "Testing discipline": no self-mocking of the SUT, behavioral (outcome) assertions not interaction-only, no tautological delegation assertion, no effect claimed under its own mock, shared-fixture defaults left on the ordinary path, setup values that actually separate the scenarios, every new test helper/mock used by a test in this same diff, no positional mock-argument access (`rg 'mock\.calls'`), every branch this diff adds covered by a test that fails when the branch body is deleted, assertions on the last write to a record rather than an intermediate one, and test titles naming their unit plus the single condition each case isolates.
38
- - port / adapter / domain file, when the hexagonal overlay is loaded → `architectures/hexagonal.md`: no business logic in a port body, adapter methods are I/O only (no post-fetch filtering on domain state, no `findValid*`/`findActive*` names hiding a rule), domain objects declared under the domain boundary, no changed domain file importing an ORM / framework / adapter / service (read the import list — mechanical), and a service dependency you add or modify goes through a port rather than a concrete adapter (advisory only while the project has not declared `architecture.style = hexagonal` in `.okstra/project.json` — record it with the port sketch; blocking under that declaration, so fix it in place before the commit rather than record-and-pass, exactly as `_implementation-verifier.md` re-grades this same diff. Either way, the codebase already injecting concrete classes is the debt this pays down, not a reason to skip it).
39
- - a service file, when the hexagonal overlay is loaded → `architectures/hexagonal.md` Rule H6: a decision this diff puts in a service — an `if`/`else` chain over domain fields, a business formula, a private method named for a domain concept — belongs in a domain function. Orchestration control flow, DTO mapping and calling a domain predicate are not violations.
47
+ - port / adapter / domain file, when the hexagonal overlay is loaded → `architectures/hexagonal.md`: ports declare contracts rather than implement business decisions; the domain owns policy, and adapters may execute its query specifications efficiently. Do not infer a violation from complex SQL, domain-oriented query names or post-fetch processing alone, or require `findAll` plus in-memory filtering. Check domain placement, inward dependencies and touched concrete-adapter dependencies under the policy precedence above. Apply H1–H6 when the overlay is selected by declaration or layout; H5 alone retains its undeclared-style advisory exception.
48
+ - a service file, when the hexagonal overlay is loaded → `architectures/hexagonal.md` Rule H6: inspect whether changed service code implements a business decision rather than orchestrating a domain-owned one. A private method's domain-oriented name alone is not evidence. Orchestration control flow, DTO mapping and calling a domain predicate are not violations.
40
49
  - a file that reads input from outside the process (request body, query, header, upload, message, webhook) or acts on its behalf → `clean-code.md` "Untrusted input and security": a size/count bound rejects oversized input before any check that grows faster than the input (a validator that runs every rule, such as class-validator without `stopAtFirstError`, does not stop at a failed `@ArrayMaxSize`), input reaches SQL / shell / paths / server-side fetches / templates / regexes only through parameters, allowlists or escaping, a new entry point carries the auth guard and compares the caller with the owner of an input-chosen id, no secret or personal data reaches code, logs or responses, and nothing evaluates or unsafely deserializes input.
41
50
  - every changed source file → `clean-code.md` "Trace what this change can do wrong": walk the error, partial, concurrent and selection paths this diff creates to their end — past the failures the plan lists, and including where a cleaning `try` registers its cleanup target relative to each call that can throw — and fix wherever a wrong result comes out. Name the input that produces it — if you cannot name one, there is nothing to fix here and you move on rather than restructuring code that works.
42
51
  A file can hold several roles — apply every rule set that fits it.
@@ -47,7 +56,11 @@ Do not scan holistically and stop when it "looks fine". Work the matrix exhausti
47
56
 
48
57
  End your audit-sidecar entry for this sweep with a one-line `Coverage:` footer naming each file you examined, the rule set(s) you applied to it, **and the outcome of each** — `clean` when you looked and found nothing, or `fixed <n>` when you fixed findings in place:
49
58
 
50
- `Coverage: users.service.ts [names: clean, plain-english: fixed 1], users.repository.adapter.ts [hexagonal: fixed 1, names: clean], users.service.spec.ts [testing-discipline: clean]`
59
+ Account for excluded files with their shared-census exclusion reasons in the same
60
+ footer. Examined files plus excluded files cover the complete changed-file list;
61
+ an exclusion does not claim a clean inspection.
62
+
63
+ `Coverage: users.service.ts [names: clean, plain-english: fixed 1], users.repository.adapter.ts [hexagonal: fixed 1, names: clean], users.service.spec.ts [testing-discipline: clean]; excluded: README.md [prose documentation]`
51
64
 
52
65
  `clean` is a result you assert, not a blank you leave. Naming the rule set without its outcome reads identically whether you checked it or skipped it, which is exactly what this footer exists to distinguish — the completion self-check and any reviewer read it to confirm nothing in the diff was skipped. A sweep with no footer, or a footer whose entries carry no outcome, is an unfinished sweep.
53
66
 
@@ -15,13 +15,15 @@ changed files (`git diff --name-only <stage-base>..HEAD`) and, for the per-file
15
15
  items, write the confirming evidence per file, not one global "✓". If any item
16
16
  fails, fix it or surface the violation — do not claim done on a failing item.
17
17
 
18
- - diff-review done: the `Pre-commit diff review sweep` ran over the full diff and its `Coverage:` footer is in your audit sidecar — every changed file named, with each applied rule set carrying its outcome (`clean` or `fixed <n>`). No footer, or entries with no outcome → the sweep is unfinished; do not claim done.
19
- - functions: every new/edited function ≤50 effective lines, single purpose — cite the longest function's actual line count, not "all under 50"
18
+ - diff-review done: the `Pre-commit diff review sweep` accounted for the full diff in its `Coverage:` footer — every examined file names its applied rule sets and outcomes (`clean` or `fixed <n>`), and every excluded file names its shared-census exclusion reason. Examined plus excluded files equal the changed-file list; excluded files are not clean inspections. A missing footer, inspection outcome or exclusion reason leaves the sweep unfinished.
19
+ - functions: review responsibility, cohesion, complexity and abstraction levels in every new/substantially edited function; more than 50 effective lines is an inspection signal, not a failure. Cite the concrete issue fixed or the rationale for retaining a cohesive longer function; follow any explicit repository limit
20
+ - grading: use the shared catalog IDs and `clean-code.md` "Finding evidence and grading". No unresolved current `must-fix` or `should-fix`, including M1/M2 design violations. Preserve `nit`, justified `park` and plan conflicts with their evidence; executor self-check is not independent verifier evidence.
20
21
  - file size: no source or test file this diff adds ends over 500 physical lines, and no file at 500 or fewer at the stage base ends over 500 (a file already over 500 may grow; that is advisory) — paste the output of `okstra correction file-size --base <stage-base>`; it must end `QA-RESULT: PASS`. Aim for 300: for each `FILE-SIZE-ADVISORY:` line it prints, split the file or say why not. A responsibility that would push a file over goes into its own new module or test file
21
- - conventions: applied the routed pack + project patterns (name which ones)
22
+ - conventions: name the explicit repository instructions, declared architecture, routed pack and surrounding patterns applied, in that precedence order; a surrounding pattern does not waive an explicit architecture rule
22
23
  - names & comments: names say what, comments say why; no obvious-restatement comments; no truthful-name violations
23
24
  - verification: ran the actual build/test — paste the exact command line and its real exit code / output tail, never a paraphrased "tests pass"
24
25
  - acceptance: each implemented plan step's `Acceptance:` condition is observably met — cite the RED→GREEN test (or the command output) proving it per step, not one global "acceptance met"; and each `Test case (success|boundary|failure)` the plan declared for this stage has a matching test in the diff (name the test), so declared edge/failure cases are not silently uncovered
26
+ - quality outcomes: apply the captured `clean-code.md` "Five simultaneous quality outcomes" to the actual diff. Preserve each applicable expectation, performance/resource bound, safety/security check and its evidence in the acceptance and verification results above. Name missing or waived evidence; do not infer all five outcomes from a green command or complete coverage table
25
27
  - mutation check: enumerate every branch this diff adds (`catch`, guard, early return, `else`), plus at least one test it added or changed. For each entry, break what it covers on purpose — delete the branch body, return the wrong value, skip the write — confirm a test FAILS, then restore; cite the branch (or test) and the observed failure per entry, not one global "mutation verified". A branch whose deletion leaves the suite green is untested, not covered — an untested recovery path is indistinguishable from one that cannot fire. "Verified" claimed without this check plus the real command output above is not a verified claim
26
28
  - cleanup: no dead or commented-out code left behind, and no caller-less identifier — list every identifier this diff added or whose last caller it removed, and cite the caller you grepped for each one (or the plan step / non-project-code contract point that justifies keeping it with none). "No new identifiers" is a valid answer; a global "cleaned up" is not
27
29