okstra 0.231.1 → 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 (126) hide show
  1. package/README.md +12 -0
  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 +127 -0
  20. package/docs/architecture.md +7 -0
  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/profiles/_coding-conventions-preflight.md +41 -6
  43. package/runtime/python/okstra_ctl/agent/invocation.py +121 -36
  44. package/runtime/python/okstra_ctl/agent/prompt_cli/cli.py +6 -0
  45. package/runtime/python/okstra_ctl/agent/prompt_cli/materialize.py +30 -4
  46. package/runtime/python/okstra_ctl/agent/standalone.py +3 -0
  47. package/runtime/python/okstra_ctl/analysis_packet.py +2 -19
  48. package/runtime/python/okstra_ctl/attempt_evidence.py +10 -0
  49. package/runtime/python/okstra_ctl/code_review_census.py +71 -7
  50. package/runtime/python/okstra_ctl/code_review_coverage.py +4 -274
  51. package/runtime/python/okstra_ctl/code_review_integrity.py +154 -0
  52. package/runtime/python/okstra_ctl/code_review_invocation.py +212 -0
  53. package/runtime/python/okstra_ctl/code_review_scope.py +36 -9
  54. package/runtime/python/okstra_ctl/code_review_target.py +85 -11
  55. package/runtime/python/okstra_ctl/consumers.py +12 -9
  56. package/runtime/python/okstra_ctl/design_review.py +207 -0
  57. package/runtime/python/okstra_ctl/design_review_evidence.py +297 -0
  58. package/runtime/python/okstra_ctl/doctor.py +8 -25
  59. package/runtime/python/okstra_ctl/doyouknow/__init__.py +9 -0
  60. package/runtime/python/okstra_ctl/doyouknow/cli.py +91 -0
  61. package/runtime/python/okstra_ctl/doyouknow/config.py +58 -0
  62. package/runtime/python/okstra_ctl/doyouknow/contracts.py +184 -0
  63. package/runtime/python/okstra_ctl/doyouknow/identity.py +22 -0
  64. package/runtime/python/okstra_ctl/doyouknow/paths.py +22 -0
  65. package/runtime/python/okstra_ctl/doyouknow/pending.py +72 -0
  66. package/runtime/python/okstra_ctl/doyouknow/registration.py +260 -0
  67. package/runtime/python/okstra_ctl/doyouknow/source_contracts.py +128 -0
  68. package/runtime/python/okstra_ctl/doyouknow/source_store.py +172 -0
  69. package/runtime/python/okstra_ctl/doyouknow/sources/io.py +36 -0
  70. package/runtime/python/okstra_ctl/doyouknow/sources/manager.py +261 -0
  71. package/runtime/python/okstra_ctl/doyouknow/sources/memory.py +179 -0
  72. package/runtime/python/okstra_ctl/doyouknow/sources/task.py +95 -0
  73. package/runtime/python/okstra_ctl/doyouknow/store.py +260 -0
  74. package/runtime/python/okstra_ctl/doyouknow/sync.py +58 -0
  75. package/runtime/python/okstra_ctl/execution_mutation_audit.py +18 -2
  76. package/runtime/python/okstra_ctl/file_size_cap.py +3 -4
  77. package/runtime/python/okstra_ctl/json_boundary.py +21 -2
  78. package/runtime/python/okstra_ctl/jsonl.py +21 -0
  79. package/runtime/python/okstra_ctl/manager_cli.py +26 -0
  80. package/runtime/python/okstra_ctl/manager_registration.py +29 -0
  81. package/runtime/python/okstra_ctl/manager_sync.py +3 -22
  82. package/runtime/python/okstra_ctl/model_io/renderers.py +13 -2
  83. package/runtime/python/okstra_ctl/model_io_cli.py +7 -1
  84. package/runtime/python/okstra_ctl/phases/final_verification/validation.py +20 -0
  85. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-deliverable.md +10 -0
  86. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-diff-review.md +19 -6
  87. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-self-check.md +5 -3
  88. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-verifier.md +38 -10
  89. package/runtime/python/okstra_ctl/phases/implementation/report_assets/implementation.template.html +13 -0
  90. package/runtime/python/okstra_ctl/phases/implementation/spec.md +25 -0
  91. package/runtime/python/okstra_ctl/phases/implementation/validation.py +6 -0
  92. package/runtime/python/okstra_ctl/phases/implementation_planning/authoring.py +4 -0
  93. package/runtime/python/okstra_ctl/phases/implementation_planning/profile.md +1 -1
  94. package/runtime/python/okstra_ctl/report_assembly.py +15 -0
  95. package/runtime/python/okstra_ctl/report_narrative.py +3 -0
  96. package/runtime/python/okstra_ctl/report_synthesis_packet.py +11 -2
  97. package/runtime/python/okstra_ctl/review_policy.py +359 -0
  98. package/runtime/python/okstra_ctl/review_verdicts.py +291 -0
  99. package/runtime/python/okstra_ctl/run.py +24 -1
  100. package/runtime/python/okstra_ctl/stage_done.py +11 -0
  101. package/runtime/python/okstra_ctl/standalone_review_audit.py +28 -0
  102. package/runtime/python/okstra_ctl/verification_generation.py +23 -1
  103. package/runtime/python/okstra_ctl/verification_input_types.py +15 -1
  104. package/runtime/python/okstra_ctl/verification_inputs.py +28 -6
  105. package/runtime/python/okstra_ctl/verification_invocation.py +7 -1
  106. package/runtime/python/okstra_ctl/verification_target.py +2 -0
  107. package/runtime/python/okstra_ctl/worker_prompt_headers.py +24 -9
  108. package/runtime/python/okstra_ctl/worker_runner.py +66 -10
  109. package/runtime/python/okstra_ctl/write_policy.py +34 -1
  110. package/runtime/python/okstra_project/__init__.py +2 -0
  111. package/runtime/python/okstra_project/dirs.py +18 -0
  112. package/runtime/python/okstra_project/state.py +25 -20
  113. package/runtime/schemas/doyouknow-config-v1.schema.json +20 -0
  114. package/runtime/schemas/doyouknow-v1.schema.json +65 -0
  115. package/runtime/schemas/final-report-v2.0.schema.json +157 -0
  116. package/runtime/schemas/final-report-v3.0.schema.json +157 -0
  117. package/runtime/schemas/memory-entry-contract-v1.json +11 -0
  118. package/runtime/schemas/record-secret-patterns.json +41 -0
  119. package/runtime/skills/okstra-code-review/SKILL.md +71 -123
  120. package/runtime/skills/okstra-code-review/references/census-rules.md +29 -105
  121. package/runtime/skills/okstra-code-review/references/review-calibration.md +34 -54
  122. package/runtime/skills/okstra-manager/SKILL.md +7 -0
  123. package/runtime/skills/okstra-memory/SKILL.md +7 -0
  124. package/runtime/templates/implementation-worker-preamble.md +4 -9
  125. package/runtime/templates/worker-prompt-preamble.md +4 -12
  126. package/runtime/validators/validate-run.py +14 -2
@@ -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)
@@ -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
 
@@ -204,22 +204,49 @@ The final report keeps both — executor's `Validation evidence` AND each verifi
204
204
 
205
205
  ### Static design & test-quality review (gate — runs after the command re-run, before the verdict)
206
206
 
207
+ When the dispatch supplies Frozen Design Review, its census is the assigned worklist.
208
+ Return the binding lines, grouped Coverage Verdicts and Design Findings format it
209
+ specifies. Do not substitute file-level summaries or the executor's self-check for
210
+ function-level M1/M2/M3 judgments. Missing accounting remains incomplete.
211
+
212
+ When Verification inputs contains a Frozen Review Policy, apply its captured
213
+ rule sources, architecture declaration and `review-rules.json` metadata instead
214
+ of current project settings and installed rules. Read them through the
215
+ verification-input projection. Original paths identify provenance, not a live
216
+ baseline. Select applicable resources with the router below. Legacy inputs
217
+ without this policy continue to use the lookup below.
218
+ For the captured policy, repeat `--source-path <repository-relative-path>` for
219
+ the relevant changed files in one `okstra model-io verification-input
220
+ --run-manifest <run-manifest>` call. Read complete selected rule bodies, not only
221
+ the available-resource index, and do not clip normative lines.
222
+
223
+ Apply the captured `clean-code.md` "Five simultaneous quality outcomes" to the
224
+ actual diff: correctness, coding principles, performance, safety and security
225
+ retain their applicable acceptance conditions. Reuse declared bounds and shared
226
+ execution evidence. A necessary missing bound or check remains unverified;
227
+ neither a green command nor complete grouped rows establish all five outcomes.
228
+
229
+ Resolve conflicts by `overview.md` policy precedence: explicit repository
230
+ instructions and declared architecture, the common pack, then surrounding code
231
+ conventions. Cite the governing instruction for an exception; an existing code
232
+ pattern alone does not waive an explicit architecture rule.
233
+
207
234
  Re-running commands proves the diff *builds and passes*; it does NOT prove the diff is *well-designed*. Lint/test green is necessary but not sufficient — self-mocked tests, interaction-only assertions, and untruthful names all survive a green pipeline. This gate is the filter for exactly those defects, so the executor's design errors are caught here instead of in post-merge PR review. It is a real gate, not a checklist: it enumerates the full diff and a blocking hit forces `FAIL`. This blocking-check taxonomy is the **gate counterpart** of the executor's `Pre-commit diff review sweep` (`_implementation-diff-review.md`) prevention pass — the same defect families, different action (executor fixes in place; verifier fails the verdict). Both lists are inlined on purpose: each sidecar is delivered stand-alone into a flat CLI prompt (lazy-read, not INCLUDE-expanded), so neither can factor the taxonomy into a shared fragment.
208
235
 
209
- - **Scope (no silent sampling).** Enumerate every changed source/test file via `git diff --name-only <base>...HEAD` and review each one. Skipping a changed file silently is a `contract-violated` outcome. If a file's language has no reference and is not covered by the agnostic checks below, record `design-review skipped: <file> (language=<x> no reference)` — never pass it silently.
210
- - **Load the same conventions the executor used via the routed pack.** Use this worker prompt's `**Coding preflight pack:**` anchor header as the absolute path to the installed routed pack. Read `overview.md` first, then `clean-code.md`, then apply the router's three ordered stages: language, framework, architecture. In each stage, iterate every rule, treat a rule as matched when any listed condition is true, and accumulate every matching resource — including `frameworks/node-server.md` for server-side Node work and `architectures/hexagonal.md` for ports-and-adapters / NestJS-hex layouts. Degrade to the agnostic checks below when the resolved pack is unreadable, and record either `coding-conventions: resources=<...>` or `coding-conventions: resource-unavailable → applied <project rules + agnostic principles>`. The verifier does NOT inline language rules — it loads the same situation-specific resources as the executor preflight.
211
- - **Load the project's review rule packs.** Run the project-context projection above and union its `Project Review Rule Packs` entries with exact `SKILL.md` paths cited by the task brief's `Source Material` / `Reporter Confirmations`. Read only those files and the `references/*.md` files they directly name. Do not search parent directories or host skill catalogs. Apply the rules as an overlay on this static review, but do NOT dispatch extra reviewer agents unless the task explicitly configured them. Record `project-review-rules: <paths read>`, `project-review-rules: declared <path> unreadable`, or `project-review-rules: none declared or cited` in the worker result — an unreadable declared pack is a recorded gap, not a skip.
212
- - **Declared architecture style promotes the placement overlay from advisory to binding.** Take `Architecture style` from that projection and record `architecture-style: <hexagonal|layered|none>` in the worker result next to the `coding-conventions:` line. A declared `hexagonal` counts the overlay as loaded even when none of the router's Stage 3 layout signals matched, so the **Hexagonal** blocking check below applies in full, and the concrete-adapter injection listed under Advisory findings is promoted to a blocking finding → verdict `FAIL`, not a `should-fix`. A declared `layered` has no pack resource; its binding invariant is direction — an upper layer may import a lower one, never the reverse — so a changed file whose import list reaches back up a layer, or around a layer boundary, is a blocking placement violation cited `path:line` from that import list. The `layered` half is worker judgement: no machine check reads layer names, so a missed reverse dependency is a missed finding, not a validator failure. A `none` or absent projected style leaves Stage 3 detection-driven and the placement items advisory. **Enforced:** `scripts/okstra_project/resolver.py` `resolve_architecture` reads the same stored field for the planning-side rule in `scripts/okstra_ctl/phases/implementation_planning/plan_body.py` `_validate_variation_point_analysis`, and `_validate_verifier_fail_blocks_verdict` keeps the resulting `FAIL` from being dropped during synthesis.
236
+ - **Scope (no silent sampling).** Enumerate every changed file via `git diff --name-only <base>...HEAD`, apply the shared census exclusion policy and review every retained file, including executable configuration. Record each exclusion and its reason; extension alone does not establish one. Skipping a retained changed file silently is a `contract-violated` outcome. If a file's language has no reference and is not covered by the agnostic checks below, record `design-review skipped: <file> (language=<x> no reference)` — never pass it silently.
237
+ - **Load the executor's selected frozen conventions.** Use the captured projection above when available and record `coding-conventions: resources=<...>`. Only legacy inputs without that policy use the `**Coding preflight pack:**` installed path and its router, including every matching language/framework/architecture resource. A missing required captured source is blocked input; never replace it with live content. For unreadable legacy resources only, retain the agnostic checks and record `coding-conventions: resource-unavailable → applied <project rules + agnostic principles>`.
238
+ - **Load the project's review rule packs.** Union the policy's standing standards with exact `SKILL.md` paths cited by the task brief's `Source Material` / `Reporter Confirmations`. With a frozen policy, use their captured bodies and directly named captured `references/*.md` bodies from the verification-input projection. A cited pack or reference missing from that capture is blocked input to report for recapture; do not omit it or read live originals. Only unfrozen legacy inputs run project-context for `Project Review Rule Packs` and read those declared files and their directly named references. Do not search parent directories or host skill catalogs. Apply the rules as an overlay on this static review, but do NOT dispatch extra reviewer agents unless the task explicitly configured them. Record `project-review-rules: <paths read>`, `project-review-rules: declared <path> unreadable`, or `project-review-rules: none declared or cited` in the worker result — an unreadable declared pack is a recorded gap, not a skip.
239
+ - **Declared architecture style selects the placement overlay.** Take `Architecture style` from the captured projection, or the legacy project-context projection, and record `architecture-style: <hexagonal|layered|none|undeclared>` beside `coding-conventions:`. A declared `hexagonal` selects H1–H6 even without layout signals and makes H5's otherwise-advisory concrete-adapter item binding. A declared `layered` selects no pack resource; its invariant is upper-to-lower dependency direction and variation points on layer boundaries. Cite changed reverse dependencies from their imports. Explicit `none` selects no overlay; only absent or `undeclared` style uses layout detection. An inferred hexagonal overlay retains each rule's criteria and severity, including H5's undeclared-style advisory exception. Apply policy precedence and shared grading; an established current blocking finding requires `FAIL`. `review_policy.py` selects the declared overlay and `_validate_verifier_fail_blocks_verdict` prevents a recorded `FAIL` from being dropped during synthesis; neither proves boundary interpretation.
213
240
  - **Blocking checks (any hit → verdict `FAIL`, cited `path:line` + rule name, recommended fix recorded — the verifier does NOT apply it):**
214
241
  - **Security (every changed file that reads input from outside the process or acts on its behalf — `clean-code.md` "Untrusted input and security"):** work that grows faster than the input — pairwise uniqueness, nested scans, a backtracking regex, input-driven recursion — reachable before a size/count bound has rejected oversized input (read the validation framework's configuration: class-validator without `stopAtFirstError` still runs `@ArrayUnique` after `@ArrayMaxSize` fails, and a byte-size body limit does not bound element count); input concatenated into SQL, a shell command, a file path, a server-side fetch target, a template or a regex; a new route / handler / resolver without the project's auth guard, or a lookup by an input-chosen id that never compares the caller with the owner; a secret, full token, password or personal data written to source, logs, an error message or a response; `eval`, dynamic code, or unsafe deserialization applied to input. Cite the input that triggers it and its effect — for unbounded work, the input size and the measured or derived cost.
215
242
  - **New duplication / DRY:** two or more newly added or meaningfully modified blocks implement the same helper stack, transform, or domain rule. Literal copy-paste is always blocking; semantically equivalent transforms across services are blocking unless the approved plan explicitly justified keeping them separate. The comparison is not limited to this diff: a newly added block that is byte-identical to a block already in the repository — base code, or a copy an earlier stage landed — is the same blocking finding, cited at both the new `path:line` and the existing one, because `final-verification` grades that cross-stage copy as an Acceptance Blocker and a per-stage `clean` only defers it. Test helpers and test support code count. Recommend the shared module location.
216
243
  - **Self-mocking:** a test for `Foo` stubs/spies a method on the `Foo` instance under test (`jest.spyOn(sut, ...)`, `spyOn(FooService.prototype, ...)` in `foo.*.spec.*`, `vi.mocked(sut)` + stub). Mocking injected collaborators is fine.
217
244
  - **Interaction-only assertion:** a test whose only/primary assertion is `toHaveBeenCalled*` / `toHaveBeenCalledTimes` on an internal helper or a non-side-effecting collaborator, with no assertion on the returned value / resulting state / persisted row / emitted event.
218
245
  - **Tautological delegation assertion:** a test asserts the SUT result equals a direct call to the same pure helper/collaborator that the SUT delegates to, instead of asserting an independent literal value or observable state.
219
- - **Untruthful name:** a read-named function (`get*` / `find*` / `load*`) that writes/inserts/mutates; an adapter or repository name encoding the caller's use-case (`*ForInit`) or hiding a domain rule (`findValid*` / `findActive*`).
220
- - **Wrong-result trace (every changed source file):** follow the paths this diff creates or alters to their end — error, partial, concurrent, selection — and name the input or state that produces a wrong result (`clean-code.md` §"Trace what this change can do wrong"). This one is an obligation, not a pattern: the defects that reach production are usually ordinary code with no name on this list. The bar is also the noise filter — a finding names the failing input; an alternative structure, a guard for a state no caller reaches, or a "consider extracting" is an improvement and verdicts `clean`. The failure modes the plan lists are the floor of this trace, not its ceiling: a verdict scoped to "the modeled failures" is not a verdict on the file. For every `try` whose `catch` / `finally` cleans up, check at each call inside it that can throw (a property write, a read, a call that starts other work) whether the thing to clean up is already registered at that point; when the diff moves or restructures existing code, compare that order with the base version and cite the base `path:line` when it changed. A failure the test fakes cannot produce (a throwing setter or read the fake does not model) is recorded as unverified with the failure named, never folded into `clean`. **The unit is the changed source file**: record `clean` or findings for each one, list every file you excluded with its reason (lockfiles, generated code, pure config), and close the section with `general: <N> files — all verdicted, <M> excluded`.
221
- - **Business rules in an application service (only when the hexagonal overlay is loaded):** changed service code that decides a business outcome inline — an `if`/`else` chain over domain fields, a business formula in arithmetic, a private method named for a domain concept — instead of calling a domain function (`architectures/hexagonal.md` Rule H6). Orchestration control flow, DTO mapping, and calling a domain predicate are not violations. Blocking when the embedded rule is substantial: money, permissions, a state machine.
222
- - **Hexagonal (only when the overlay is loaded):** business logic inside a port body; an adapter method that is not pure I/O (post-fetch JS filtering on domain state, domain-rule evaluation); a domain object declared outside the `domain/` boundary; a changed file under the domain folder importing an ORM / DB layer, a framework or its DI decorators, or anything under adapters / infrastructure / services (read the import list — this verdict is mechanical, not a judgment). **The routed pack's project-convention latitude does not reach this cell.** `architectures/hexagonal.md` lets a documented convention resolve conflicts in the project's favour elsewhere in that overlay; here the import list decides, and "matches existing convention" is not an answer to it (see that file's §"How far a project convention reaches"). A run that resolved exactly this finding as project convention returned `clean` and the team's PR review flagged the same import.
246
+ - **Untruthful name:** a read-named function (`get*` / `find*` / `load*`) that performs caller-visible mutations its name does not disclose, or an undefined or misleading business term. Inspect the port contract and governing policy before judging a domain-oriented query name; `findValid*` / `findActive*` and complex SQL alone do not establish a violation.
247
+ - **Wrong-result trace (every changed source file):** follow the paths this diff creates or alters to their end — error, partial, concurrent, selection — and name the input or state that produces a wrong result (`clean-code.md` §"Trace what this change can do wrong"). This one is an obligation, not a pattern: the defects that reach production are usually ordinary code with no name on this list. The bar is also the noise filter — a finding names the failing input; an alternative structure, a guard for a state no caller reaches, or a "consider extracting" is an improvement and verdicts `clean`. The failure modes the plan lists are the floor of this trace, not its ceiling: a verdict scoped to "the modeled failures" is not a verdict on the file. For every `try` whose `catch` / `finally` cleans up, check at each call inside it that can throw (a property write, a read, a call that starts other work) whether the thing to clean up is already registered at that point; when the diff moves or restructures existing code, compare that order with the base version and cite the base `path:line` when it changed. A failure the test fakes cannot produce (a throwing setter or read the fake does not model) is recorded as unverified with the failure named, never folded into `clean`. **The unit is the changed source file**: record `clean` or findings for each one, list every excluded file and its reason under the shared census exclusion policy, and close the section with `general: <N> files — all verdicted, <M> excluded`. Configuration that controls executable behavior is reviewed under that policy rather than excluded by extension alone.
248
+ - **Business rules in an application service (only when the hexagonal overlay is loaded):** changed service code that implements a business decision instead of orchestrating a domain-owned one (`architectures/hexagonal.md` Rule H6). Inspect the implementation and governing rule; a private method's domain-oriented name alone is not evidence. Orchestration control flow, DTO mapping and calling a domain predicate are not violations. Apply shared grading when declaration or layout selects the overlay; a substantial embedded rule such as money, permissions or a state machine remains blocking.
249
+ - **Hexagonal (only when the overlay is loaded):** executable business decisions inside a port body; business policy invented or changed in an adapter rather than owned by the domain; misplaced domain objects or outward domain dependencies contrary to the applicable architecture. An adapter may translate domain-owned query specifications into efficient SQL, including compound predicates and joins. Complex SQL, a domain-oriented query name or post-fetch processing alone is not a violation; do not require `findAll` plus in-memory filtering. Inspect the governing policy, port contract and imports, and apply `overview.md` precedence and H1–H6 whether declaration or layout selected the overlay. Existing code conventions alone cannot waive an applicable boundary. Grade established current violations with the shared rubric; H5 alone retains its undeclared-style advisory exception.
223
250
  - **gitignored file committed to the branch:** any path in the `git diff --name-only <base>...HEAD` enumeration that `.gitignore` excludes — enumerate them by piping that list through `git check-ignore --stdin --no-index`. A committed ignored file means the executor bulk-added (`git add .`/`-A`) or force-staged (`git add -f`) it, leaking build output, scratch files, or verification artifacts into the eventual PR. This explicitly includes `.okstra/` paths (and `.project-docs/` when the legacy symlink is present): `.okstra/**` is gitignored, so a committed okstra file (qa scripts, conformance results) is always this defect. Cite each path; recommend `git rm --cached <path>` to untrack it while keeping the file on disk. Conformance/qa evidence belongs in the carry sidecar / verifier result, never in git history.
224
251
  - **Real-IO test in source tree:** a changed/added test under the project source test tree — `src/**`, `test/**`, `tests/**`, `**/__test__/**`, `**/__tests__/**`, `*.spec.*`, `*.test.*` — that opens a **real** DB connection / DSN, makes a real `fetch` / `axios` / `http` request, or otherwise hits real external IO without mocking the injected collaborator (a live handle, not a stub/spy). Real-IO tests MUST live under `<task_root>/qa/scripts/` per the executor's *Real-IO test isolation* rule — a live-IO test in source silently breaks the project's CI suite and violates the artifact-home rule. Cite the test file + the real-IO line; recommend moving it to `<task_root>/qa/scripts/` (or declaring it as a Tier 3 conformance script). Mock-only unit tests in source are NOT a hit.
225
252
  - **Proxy-based identity decision:** a move / ownership / re-parenting decision taken from a status field or flag while the source and destination identifiers were available and never compared. Cite the condition and the identifiers it should have compared, and show the opposite case the condition also reads true for.
@@ -231,10 +258,11 @@ Re-running commands proves the diff *builds and passes*; it does NOT prove the d
231
258
  - **Positional mock-argument access:** `mock.calls[<n>][<m>]` (or the framework equivalent) used to inspect arguments instead of an intent-revealing `toHaveBeenCalledWith` / explicit-absence assertion. Detect with `rg 'mock\.calls'` over the changed test files.
232
259
  - **Non-separating test data:** two scenarios whose setup values and assertions are identical, so a wrong implementation passes both; or new test tooling added in this diff (mock, state setter, repository branch) that no test calls.
233
260
  - **Effect claimed under its own mock:** a test presented as covering an effect whose producing path is replaced by a mock inside that same test. The mock's presence in the harness is not evidence the branch behind it works.
234
- - **Single-caller abstraction (KISS):** an abstraction layer this diff introduces — a helper module, a strategy / factory / builder, an indirection or wrapper layer, an interface or abstract base — that has exactly one caller after the change, where inlining it at that call site would be simpler. The rule is `overview.md` core principle 2: name the second caller now, or inline. Four exits are legitimate and each must **cite its evidence**: the approved plan declares it (a `testSeams[]` boundary or a variation-point extraction — cite the plan step); the project declares `architecture.style = hexagonal` and this is a port at the domain boundary (a port with one adapter is the normal shape, not a violation); it breaks a real import cycle (name both modules); or its single caller is the public API of a published package. Absent one of those, cite `path:line` and recommend the inlined shape. Do NOT raise this on a function extracted purely to bring a body under the 50-line cap — that is principle 5 doing its job — nor on a pre-existing abstraction this diff merely edits.
261
+ - **Single-caller abstraction (KISS):** an abstraction layer this diff introduces — a helper module, a strategy / factory / builder, an indirection or wrapper layer, an interface or abstract base — that has exactly one caller after the change, where inlining it at that call site would be simpler. The rule is `overview.md` core principle 2: name the second caller now, or inline. Four exits are legitimate and each must **cite its evidence**: the approved plan declares it (a `testSeams[]` boundary or a variation-point extraction — cite the plan step); the project declares `architecture.style = hexagonal` and this is a port at the domain boundary (a port with one adapter is the normal shape, not a violation); it breaks a real import cycle (name both modules); or its single caller is the public API of a published package. Absent one of those, cite `path:line` and recommend the inlined shape. This targets reusable layers, not a local helper that names a cohesive step or separates mixed abstraction levels, nor a pre-existing abstraction this diff merely edits. Line count alone does not justify extraction.
235
262
  - **File-size limit (every verifier, not only the stage QA owner):** run `okstra correction file-size --base <base>` from the worktree cwd and log it in the `Read-only command log`. Each `FILE-SIZE:<path>:501 <before>-><after>` line it prints is a blocking finding cited exactly as printed — a new file over 500 lines, or a file the diff took from 500 or fewer past 500. A file already over 500 at the stage base that the diff grows is not blocking; the command prints it as an advisory line. Recommended fix: move whole responsibilities into new modules or test files beside it. The command writes nothing and its result is the same for every verifier, so the finding converges and the lead sends it to a correction round. Each `FILE-SIZE-ADVISORY:<path>:301` line (the 300-line target: a new file over 300, a file the diff took past 300, or a file already over 300 the diff grew, including one already over 500) goes under the advisory findings below, not here. Do not judge size yourself: a file it does not print is not a finding (lockfiles, data, Markdown, fixtures, snapshots, generated files and languages without a coding preflight are exempt by `scripts/okstra_ctl/file_size_cap.py` `capped_path`).
236
263
  - **Caller-less identifier (YAGNI / orphan):** an identifier this diff leaves with zero callers — either newly added and never called (a speculative parameter, an optional config object, a "future-proof" hook, an exported helper whose only caller is hypothetical), or pre-existing code orphaned because this diff removed its last caller. Grep the identifier across the whole repository rather than the diff alone; a hit inside its own declaration, its own test, or a commented-out line is not a caller. Two exits are legitimate and must be **stated with their evidence**, never assumed: an identifier the approved plan reserves for a named later stage (cite the plan step), and a contract point something other than project code calls (a framework entrypoint, an implemented interface method, a migration hook, the public API of a published package — cite the caller or the registration). Anything else is work no requirement asked for: recommend deleting it, or folding an added parameter back into its single call site. A caller-less identifier is the one YAGNI violation that survives a green pipeline unchanged, which is why it grades here rather than as a recommendation.
237
- - **Advisory findings (recorded as recommendations; verdict MAY still PASS):** each `FILE-SIZE-ADVISORY:` line from the file-size command (a file over the 300-line target but within 500), function >50 effective lines, a single body mixing read+write stages, weak readability, a missing-but-non-critical outcome assertion, weak-but-not-misleading names, priority-between-inputs policy inlined in a service condition instead of a named domain function, an error message asserting a cause the code never observed, a memory / concurrency / batching change with no test pinning the bound it claims, or (hexagonal overlay only) a service dependency this diff adds or modifies that injects a concrete adapter instead of a port — record it with the port sketch; advisory only while the project has not declared `architecture.style = hexagonal`, since that declaration — and only that one — promotes exactly this item to blocking per the declared-style bullet above, while a declared `layered` binds dependency direction instead and leaves this item advisory; an existing convention of concrete injections does not convert this one to `clean`, it is the debt the rule pays down. These land in the verifier result as `should-fix` / `nit` recommendations, not as a `FAIL`.
264
+ - **Shared grading:** use the captured catalog and `clean-code.md` "Finding evidence and grading". A clear M1/M2 violation (misleading name, mixed responsibility, excessive complexity or mixed abstraction levels) can be `should-fix` / `now` and forces `FAIL` even when commands pass. More than 50 effective function lines prompts inspection; it does not establish a violation or force a split. Name the rule, source and design consequence; a preferred alternative alone is not a finding. Apply the same evidence test to state policy, unobserved error causes and missing resource-bound tests rather than automatically downgrading them. Restrictive plan placement returns a plan conflict, never permission to pass a current violation.
265
+ - **Nonblocking findings:** `nit`, justified `park`, and size-only target advisories may accompany `PASS`. An already oversized file's size advisory does not exempt its added responsibilities from S3/M2. Architecture-specific latitude follows the declared style and the applicable project rule; record its cited basis. Do not demand unrelated legacy cleanup.
238
266
  - **Output.** Every finding — blocking or advisory — is a structured item in the verifier's worker result (`path:line`, rule, severity, suggested fix) so it carries into Phase 5.5 convergence and the final report. Each item, advisory items included, carries an item id as `prompts/profiles/_common-contract.md` "Cross-worker traceability" defines it for worker output. The lead cites a finding by that id, and `okstra convergence seed` refuses a cited id that does not occur in the result, so an unnumbered item cannot enter convergence and drops out of the report. This is a guideline: nothing parses a verifier result for missing ids. A blocking hit sets the verifier verdict to `FAIL` with the rule cited, using the same verdict machinery as the Discrepancy rule above. The Okstra lead MUST NOT silently downgrade a cited blocking finding to advisory during synthesis; an override requires a concrete cited reason, exactly as for the Discrepancy rule.
239
267
 
240
268
  ### Fix-run incremental scope (applies when the profile carries a "Fix-Run Carry" block)