okstra 0.227.0 → 0.228.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 (74) hide show
  1. package/README.md +1 -1
  2. package/dist/cli-registry.mjs +6 -0
  3. package/dist/cli-registry.mjs.map +1 -1
  4. package/docs/architecture/storage-model.md +77 -0
  5. package/docs/cli.md +15 -3
  6. package/docs/project-structure-overview.md +12 -2
  7. package/package.json +1 -1
  8. package/runtime/BUILD.json +2 -2
  9. package/runtime/prompts/duties/code-reviewer.json +1 -0
  10. package/runtime/prompts/lead/convergence.md +5 -19
  11. package/runtime/prompts/lead/okstra-lead-contract.md +1 -1
  12. package/runtime/prompts/profiles/_coding-conventions-preflight.md +1 -1
  13. package/runtime/python/okstra_ctl/adapters/verification_inputs.py +22 -0
  14. package/runtime/python/okstra_ctl/adapters/worker_defaults.py +2 -2
  15. package/runtime/python/okstra_ctl/analysis_packet.py +52 -21
  16. package/runtime/python/okstra_ctl/approval_decisions.py +30 -1
  17. package/runtime/python/okstra_ctl/approved_plan_stage_extract.py +100 -66
  18. package/runtime/python/okstra_ctl/brief_sources.py +162 -44
  19. package/runtime/python/okstra_ctl/code_review_coverage.py +11 -1
  20. package/runtime/python/okstra_ctl/code_review_scope.py +157 -0
  21. package/runtime/python/okstra_ctl/code_review_target.py +46 -10
  22. package/runtime/python/okstra_ctl/conformance.py +9 -3
  23. package/runtime/python/okstra_ctl/design_surfaces.py +51 -19
  24. package/runtime/python/okstra_ctl/final_report_schema.py +37 -30
  25. package/runtime/python/okstra_ctl/fixed_text.py +31 -9
  26. package/runtime/python/okstra_ctl/implementation_direction.py +18 -0
  27. package/runtime/python/okstra_ctl/initial_prompt_materialization.py +59 -21
  28. package/runtime/python/okstra_ctl/json_registry.py +3 -18
  29. package/runtime/python/okstra_ctl/manager_split.py +201 -84
  30. package/runtime/python/okstra_ctl/model_io/references.py +31 -1
  31. package/runtime/python/okstra_ctl/model_io/renderers.py +30 -1
  32. package/runtime/python/okstra_ctl/model_io_cli.py +9 -0
  33. package/runtime/python/okstra_ctl/path_hints.py +13 -1
  34. package/runtime/python/okstra_ctl/paths.py +4 -0
  35. package/runtime/python/okstra_ctl/phases/final_verification/prior_blockers.py +87 -45
  36. package/runtime/python/okstra_ctl/phases/final_verification/profile.md +2 -2
  37. package/runtime/python/okstra_ctl/phases/final_verification/spec.md +10 -2
  38. package/runtime/python/okstra_ctl/phases/final_verification/validation.py +19 -11
  39. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-executor.md +3 -1
  40. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-verifier.md +3 -1
  41. package/runtime/python/okstra_ctl/phases/implementation/spec.md +14 -0
  42. package/runtime/python/okstra_ctl/phases/implementation_option_selection/authoring.py +2 -1
  43. package/runtime/python/okstra_ctl/phases/implementation_option_selection/profile.md +1 -1
  44. package/runtime/python/okstra_ctl/phases/implementation_option_selection/validation.py +53 -37
  45. package/runtime/python/okstra_ctl/phases/implementation_planning/profile.md +1 -1
  46. package/runtime/python/okstra_ctl/plan_items.py +9 -11
  47. package/runtime/python/okstra_ctl/ports/verification_inputs.py +17 -0
  48. package/runtime/python/okstra_ctl/prior_planning.py +6 -17
  49. package/runtime/python/okstra_ctl/prior_run_summary.py +35 -0
  50. package/runtime/python/okstra_ctl/qa_commands.py +66 -1
  51. package/runtime/python/okstra_ctl/qa_commands_cli.py +67 -0
  52. package/runtime/python/okstra_ctl/qa_procedures.py +235 -0
  53. package/runtime/python/okstra_ctl/registry/verification_inputs_store.py +8 -0
  54. package/runtime/python/okstra_ctl/render.py +10 -0
  55. package/runtime/python/okstra_ctl/report_assembly.py +12 -12
  56. package/runtime/python/okstra_ctl/run.py +108 -5
  57. package/runtime/python/okstra_ctl/verification_input_ref.py +80 -0
  58. package/runtime/python/okstra_ctl/verification_input_types.py +32 -0
  59. package/runtime/python/okstra_ctl/verification_inputs.py +162 -0
  60. package/runtime/python/okstra_ctl/verification_plan.py +116 -0
  61. package/runtime/python/okstra_ctl/worker_prompt_body.py +12 -6
  62. package/runtime/python/okstra_ctl/worker_prompt_contract.py +5 -1
  63. package/runtime/python/okstra_ctl/worker_prompt_headers.py +50 -1
  64. package/runtime/python/okstra_project/dirs.py +22 -0
  65. package/runtime/python/okstra_project/resolver.py +10 -0
  66. package/runtime/schemas/final-report-v3.0.schema.json +5 -1
  67. package/runtime/skills/okstra-brief-gen/SKILL.md +10 -4
  68. package/runtime/skills/okstra-code-review/SKILL.md +39 -45
  69. package/runtime/skills/okstra-code-review/references/census-rules.md +14 -2
  70. package/runtime/skills/okstra-code-review/references/review-calibration.md +31 -8
  71. package/runtime/skills/okstra-manager/SKILL.md +2 -2
  72. package/runtime/skills/okstra-setup/SKILL.md +2 -0
  73. package/runtime/skills/okstra-setup/references/project-config.md +2 -0
  74. package/runtime/validators/validate-brief.py +21 -5
@@ -0,0 +1,235 @@
1
+ """Project verification procedure paths, fingerprints, and atomic registration."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import json
6
+ import os
7
+ import tempfile
8
+ from pathlib import Path
9
+ from typing import Any, Literal, Mapping, TypedDict
10
+
11
+ from okstra_project import project_json_path
12
+ from okstra_project.dirs import OKSTRA_DIR_NAME, json_lock_path, registry_lock
13
+
14
+ from .analysis_packet import _heading_lines
15
+ from .json_boundary import load_owned_object, write_owned_object_atomic
16
+ from .qa_commands import (
17
+ QA_RELATIVE_PATH_DESCRIPTION, qa_relative_path_valid, validate_qa_commands,
18
+ )
19
+
20
+ PROCEDURE_SECTIONS = (
21
+ "Execution", "Environment", "User actions", "Success observations", "Cleanup",
22
+ )
23
+
24
+
25
+ class QaInspectionRow(TypedDict, total=False):
26
+ category: str
27
+ index: int
28
+ id: str
29
+ label: str
30
+ cmd: str
31
+ procedurePath: str
32
+ entryDigest: str
33
+ procedureDigest: str
34
+ sourceStatus: Literal[
35
+ "not-declared", "not-queried", "no-baseline", "unchanged", "changed",
36
+ ]
37
+ evidenceStatus: Literal["not-queried"]
38
+ error: str
39
+
40
+
41
+ def content_digest(value: bytes) -> str:
42
+ return "sha256:" + hashlib.sha256(value).hexdigest()
43
+
44
+
45
+ def canonical_json_digest(value: Mapping[str, Any]) -> str:
46
+ encoded = json.dumps(dict(value), sort_keys=True, separators=(",", ":"))
47
+ return content_digest(encoded.encode())
48
+
49
+
50
+ def safe_qa_path(root: Path, relative: str) -> Path:
51
+ if not qa_relative_path_valid(relative):
52
+ raise ValueError(
53
+ f"QA path must be a {QA_RELATIVE_PATH_DESCRIPTION}: {relative}"
54
+ )
55
+ path = root.resolve()
56
+ for part in Path(relative).parts:
57
+ path = path / part
58
+ if path.is_symlink():
59
+ raise ValueError(f"QA path must not contain a symlink: {relative}")
60
+ return path
61
+
62
+
63
+ def existing_qa_file(root: Path, relative: str) -> Path:
64
+ path = safe_qa_path(root, relative)
65
+ if not path.is_file():
66
+ raise ValueError(f"QA input must be an existing regular file: {relative}")
67
+ return path
68
+
69
+
70
+ def procedure_root(project: Path, source: Path, relative: str) -> Path:
71
+ return project if Path(relative).parts[:1] == (OKSTRA_DIR_NAME,) else source
72
+
73
+
74
+ def validate_procedure_sections(raw: bytes) -> None:
75
+ headings = {text[3:].rstrip("#").strip()
76
+ for _, text in _heading_lines(raw.decode("utf-8").splitlines())
77
+ if text.startswith("## ")}
78
+ missing = set(PROCEDURE_SECTIONS) - headings
79
+ if missing:
80
+ raise ValueError("procedure sections missing: " + ", ".join(sorted(missing)))
81
+
82
+
83
+ def read_validated_procedure(path: Path) -> bytes:
84
+ raw = path.read_bytes()
85
+ validate_procedure_sections(raw)
86
+ return raw
87
+
88
+
89
+ def source_digest(source: Path, relatives: list[str]) -> str:
90
+ return canonical_json_digest({
91
+ relative: content_digest(existing_qa_file(source, relative).read_bytes())
92
+ for relative in sorted(relatives)
93
+ })
94
+
95
+
96
+ def load_qa_config(project: Path) -> dict[str, Any]:
97
+ config = load_owned_object(project_json_path(project), artifact="project config")
98
+ errors = validate_qa_commands(config.get("qaCommands"))
99
+ if errors:
100
+ raise ValueError("; ".join(errors))
101
+ return config
102
+
103
+
104
+ def inspect_commands(project: Path, source: Path) -> list[QaInspectionRow]:
105
+ config = load_qa_config(project)
106
+ rows: list[QaInspectionRow] = []
107
+ for category, entries in (config.get("qaCommands") or {}).items():
108
+ for index, entry in enumerate(entries):
109
+ row: QaInspectionRow = {
110
+ **entry, "category": category, "index": index,
111
+ "entryDigest": canonical_json_digest(entry),
112
+ "sourceStatus": (
113
+ "not-queried" if entry.get("sourcePaths") else "not-declared"
114
+ ),
115
+ "evidenceStatus": "not-queried",
116
+ }
117
+ try:
118
+ relative = entry.get("procedurePath")
119
+ if relative:
120
+ root = procedure_root(project, source, relative)
121
+ raw = read_validated_procedure(existing_qa_file(root, relative))
122
+ row["procedureDigest"] = content_digest(raw)
123
+ if entry.get("sourcePaths"):
124
+ observed = source_digest(source, entry["sourcePaths"])
125
+ baseline = entry.get("sourceBaselineDigest")
126
+ row["sourceStatus"] = "no-baseline" if not baseline else (
127
+ "unchanged" if observed == baseline else "changed"
128
+ )
129
+ except (OSError, ValueError) as exc:
130
+ row["error"] = str(exc)
131
+ rows.append(row)
132
+ return rows
133
+
134
+
135
+ def _store_procedure(project: Path, relative: str, raw: bytes) -> None:
136
+ target = safe_qa_path(project, relative)
137
+ target.parent.mkdir(parents=True, exist_ok=True)
138
+ descriptor, name = tempfile.mkstemp(prefix=".procedure-", dir=target.parent)
139
+ temporary = Path(name)
140
+ try:
141
+ with os.fdopen(descriptor, "wb") as handle:
142
+ handle.write(raw)
143
+ handle.flush()
144
+ os.fsync(handle.fileno())
145
+ try:
146
+ os.link(temporary, target)
147
+ except FileExistsError:
148
+ if existing_qa_file(project, relative).read_bytes() != raw:
149
+ raise ValueError("procedure digest path contains different bytes")
150
+ finally:
151
+ temporary.unlink(missing_ok=True)
152
+
153
+
154
+ def read_registration_input(
155
+ project: Path, source: Path, category: str, entry: Mapping[str, Any],
156
+ procedure: Path,
157
+ ) -> tuple[dict[str, Any], bytes, bool]:
158
+ candidate = dict(entry)
159
+ errors = validate_qa_commands({category: [candidate]})
160
+ if errors or not candidate.get("id"):
161
+ raise ValueError("; ".join(errors) or "registration requires an id")
162
+ absolute = procedure.absolute()
163
+ if ".." in absolute.parts:
164
+ raise ValueError("procedure input must not contain traversal")
165
+ relative = None
166
+ roots = (project.absolute(), project.resolve(), source.absolute(), source.resolve())
167
+ for root in sorted(roots, key=lambda value: len(value.parts), reverse=True):
168
+ if absolute.is_relative_to(root):
169
+ absolute = existing_qa_file(root, absolute.relative_to(root).as_posix())
170
+ break
171
+ selected_roots = (project.resolve(), source.resolve())
172
+ for root in sorted(
173
+ selected_roots, key=lambda value: len(value.parts), reverse=True,
174
+ ):
175
+ if absolute.is_relative_to(root):
176
+ relative = absolute.relative_to(root).as_posix()
177
+ selected = procedure_root(project, source, relative)
178
+ path = existing_qa_file(selected, relative)
179
+ break
180
+ else:
181
+ external_relative = absolute.relative_to(absolute.anchor).as_posix()
182
+ path = existing_qa_file(Path(absolute.anchor), external_relative)
183
+ raw = read_validated_procedure(path)
184
+ external = relative is None
185
+ if external:
186
+ digest = content_digest(raw).split(":", 1)[1]
187
+ relative = (
188
+ f"{OKSTRA_DIR_NAME}/verification/procedures/{candidate['id']}/{digest}.md"
189
+ )
190
+ candidate["procedurePath"] = relative
191
+ if candidate.get("sourcePaths"):
192
+ candidate["sourceBaselineDigest"] = source_digest(
193
+ source, candidate["sourcePaths"]
194
+ )
195
+ return candidate, raw, external
196
+
197
+
198
+ def register_command(
199
+ project: Path, source: Path, category: str, entry: Mapping[str, Any],
200
+ procedure: Path, *, expected_digest: str | None = None,
201
+ ) -> str:
202
+ candidate, raw, external = read_registration_input(
203
+ project, source, category, entry, procedure
204
+ )
205
+ with registry_lock(json_lock_path(project_json_path(project))):
206
+ config = load_qa_config(project)
207
+ qa = config.get("qaCommands") or {}
208
+ config["qaCommands"] = qa
209
+ found = [(key, index, row) for key, rows in qa.items()
210
+ for index, row in enumerate(rows) if row.get("id") == candidate["id"]]
211
+ if found:
212
+ old_category, index, old = found[0]
213
+ if expected_digest != canonical_json_digest(old):
214
+ raise ValueError(
215
+ "existing QA entry digest mismatch; refresh before updating"
216
+ )
217
+ if category != old_category:
218
+ raise ValueError("registration cannot move an id to another category")
219
+ candidate = {**old, **candidate}
220
+ qa[category][index] = candidate
221
+ else:
222
+ if expected_digest is not None:
223
+ raise ValueError(
224
+ "expected QA entry digest supplied but id does not exist"
225
+ )
226
+ qa.setdefault(category, []).append(candidate)
227
+ errors = validate_qa_commands(qa)
228
+ if errors:
229
+ raise ValueError("; ".join(errors))
230
+ if external:
231
+ _store_procedure(project, candidate["procedurePath"], raw)
232
+ write_owned_object_atomic(
233
+ project_json_path(project), config, artifact="project config"
234
+ )
235
+ return canonical_json_digest(candidate)
@@ -0,0 +1,8 @@
1
+ from __future__ import annotations
2
+
3
+ from ..adapters.verification_inputs import JsonVerificationInputStore
4
+ from ..ports.verification_inputs import VerificationInputStore
5
+
6
+
7
+ def default_verification_input_store() -> VerificationInputStore:
8
+ return JsonVerificationInputStore()
@@ -48,6 +48,9 @@ from .ports.worker_dispatch import WorkerDispatchRequest
48
48
  from .registry.host_registry import default_host_registry
49
49
  from .registry.provider_registry import default_provider_registry
50
50
  from .path_hints import compact_active_run_context, hydrate_run_context
51
+ from .verification_input_ref import (
52
+ VerificationInputReference, artifact_fields, retain_recorded_reference,
53
+ )
51
54
  from .paths import task_timeline_file
52
55
  from .json_boundary import JsonBoundaryError, load_owned_object, write_owned_object_atomic
53
56
  from .mcp_servers import load_declarations as load_mcp_declarations
@@ -1709,7 +1712,13 @@ def render_run_manifest(run_manifest_path: str, ctx: dict) -> None:
1709
1712
  else {}
1710
1713
  )
1711
1714
  except JsonBoundaryError:
1715
+ if VerificationInputReference.from_context(ctx) is not None:
1716
+ raise
1712
1717
  existing_run_manifest = {}
1718
+ manifest_input_ref = retain_recorded_reference(
1719
+ existing_run_manifest if run_manifest_exists else None,
1720
+ VerificationInputReference.from_context(ctx),
1721
+ )
1713
1722
  task_manifest_path = Path(ctx.get("TASK_MANIFEST_PATH", ""))
1714
1723
  task_manifest = {}
1715
1724
  if task_manifest_path.exists():
@@ -1855,6 +1864,7 @@ def render_run_manifest(run_manifest_path: str, ctx: dict) -> None:
1855
1864
  "verificationTargetPath": ctx.get("VERIFICATION_TARGET_RELATIVE_PATH", ""),
1856
1865
  "verificationTargetDigest": ctx.get("VERIFICATION_TARGET_DIGEST", ""),
1857
1866
  "workerResultsDirectoryPath": ctx.get("WORKER_RESULTS_RELATIVE_PATH", ""),
1867
+ **artifact_fields(manifest_input_ref),
1858
1868
  "reportTemplatePath": ctx.get("FINAL_REPORT_TEMPLATE_RELATIVE_PATH", ""),
1859
1869
  "validatorScriptPath": ctx.get("RUN_VALIDATOR_RELATIVE_PATH", ""),
1860
1870
  "leadSessionId": ctx.get("CLAUDE_SESSION_ID", ""),
@@ -27,7 +27,10 @@ from .report_synthesis_packet import (
27
27
  )
28
28
  from .conformance import strip_stage_declaration_label
29
29
  from .coverage_census import census_warning_rows, read_census_state
30
- from .design_surfaces import DesignSurfaceError, detect_design_surfaces
30
+ from .design_surfaces import (
31
+ DesignSurfaceError,
32
+ detect_design_surfaces_in_unvalidated_plan,
33
+ )
31
34
  from .design_prep import (
32
35
  DesignPrepError,
33
36
  canonicalize_request_paths,
@@ -251,7 +254,7 @@ def _carried_clarification_row(source: Mapping[str, Any]) -> dict[str, Any]:
251
254
  key: source[key]
252
255
  for key in (
253
256
  "id", "ticketId", "kind", "statement", "expectedForm", "blocks",
254
- "origin", "userConfirmation", "userInput", "options",
257
+ "origin", "userConfirmation", "userInput", "options", "candidateRef",
255
258
  )
256
259
  if key in source
257
260
  }
@@ -440,7 +443,7 @@ def _clarification_row(
440
443
  key: source[key]
441
444
  for key in (
442
445
  "id", "ticketId", "kind", "statement", "expectedForm", "blocks",
443
- "origin", "userConfirmation", "options",
446
+ "origin", "userConfirmation", "options", "candidateRef",
444
447
  )
445
448
  if key in source
446
449
  }
@@ -697,18 +700,15 @@ def validate_plan_draft(
697
700
 
698
701
 
699
702
  def _design_surface_errors(draft: Mapping[str, Any]) -> list[str]:
700
- """`plan-items prepare` 가 돌릴 설계 표면 탐지기를 초안 단계에서 미리 돌린다.
703
+ """Run the design-surface detector that `plan-items prepare` runs, on the draft.
701
704
 
702
- 탐지 실패는 서사를 고쳐야 풀리는데, 교정 원장 대조가 이를 몰라 ok 를 낸 뒤
703
- prepare 에서야 드러났다.
705
+ Only a narrative edit resolves a detection failure, so it must surface in the
706
+ draft check, where the writer can still correct it in the same run.
704
707
  """
705
- planning = draft.get("implementationPlanning")
706
- if not isinstance(planning, Mapping) or not planning.get("stages"):
707
- return []
708
708
  try:
709
- detect_design_surfaces(planning)
710
- except (DesignSurfaceError, TypeError, AttributeError) as exc:
711
- return [f"implementationPlanning: design-surface detection failed: {exc}"]
709
+ detect_design_surfaces_in_unvalidated_plan(draft.get("implementationPlanning"))
710
+ except DesignSurfaceError as exc:
711
+ return [f"implementationPlanning: {exc}"]
712
712
  return []
713
713
 
714
714
 
@@ -95,7 +95,18 @@ from .implementation_direction import (
95
95
  validate_task_artifact_path,
96
96
  write_selected_direction_snapshot,
97
97
  )
98
- from .qa_commands import format_errors as _format_qa_errors, validate_qa_commands
98
+ from .qa_commands import (
99
+ QA_COMMAND_EXECUTING_TASK_TYPES,
100
+ format_errors as _format_qa_errors,
101
+ validate_qa_commands,
102
+ )
103
+ from .paths import RunRef
104
+ from .qa_procedures import safe_qa_path
105
+ from .verification_input_ref import (
106
+ VerificationInputReference, retain_recorded_reference,
107
+ )
108
+ from .ports.verification_inputs import VerificationInputStore
109
+ from .registry.verification_inputs_store import default_verification_input_store
99
110
  from .material import (
100
111
  build_analysis_material,
101
112
  direct_work_context,
@@ -107,6 +118,7 @@ from .final_report_schema import load_schema_version
107
118
  from .final_report_paths import (
108
119
  final_report_data_path as _final_report_data_path,
109
120
  final_report_markdown_path as _final_report_markdown_path,
121
+ is_report_record_path,
110
122
  require_approved_plan_record as _require_approved_plan_record_path,
111
123
  )
112
124
  from .lead_events import LeadEvent, append_lead_event
@@ -1648,9 +1660,6 @@ def _validate_analysis_prepare_inputs(project_root: Path, inp: PrepareInputs) ->
1648
1660
 
1649
1661
 
1650
1662
 
1651
- QA_COMMAND_EXECUTING_TASK_TYPES = ("implementation", "final-verification")
1652
-
1653
-
1654
1663
  def validate_project_qa_commands(task_type: str, project_root: Path) -> None:
1655
1664
  """`qaCommands` 를 실행하는 phase 진입에서 변경성 토큰 선언을 막는다.
1656
1665
 
@@ -3386,6 +3395,99 @@ def _write_run_inputs_once(
3386
3395
  )
3387
3396
 
3388
3397
 
3398
+ def _load_recorded_run_manifest_strict(
3399
+ project_root: Path, manifest_path: str,
3400
+ ) -> dict[str, object] | None:
3401
+ relative = Path(manifest_path).relative_to(project_root).as_posix()
3402
+ manifest = safe_qa_path(project_root, relative)
3403
+ if not manifest.exists():
3404
+ return None
3405
+ return load_owned_object(manifest, artifact="run manifest")
3406
+
3407
+
3408
+ def _verification_input_source(
3409
+ ctx: dict, reference: VerificationInputReference | None,
3410
+ ) -> Path | None:
3411
+ source_key = ("EXECUTOR_WORKTREE_PATH" if ctx["TASK_TYPE"] == "implementation"
3412
+ else "VERIFICATION_WORKTREE_PATH")
3413
+ source_path = ctx.get(source_key, "")
3414
+ if not source_path and reference is None:
3415
+ return None
3416
+ if not source_path or not Path(source_path).is_dir():
3417
+ raise ValueError("verification source worktree is unavailable")
3418
+ return Path(source_path).resolve()
3419
+
3420
+
3421
+ def _validate_recorded_verification_inputs(
3422
+ project_root: Path, source: Path, run_ref: RunRef,
3423
+ reference: VerificationInputReference, store: VerificationInputStore,
3424
+ approved_plan: Path | None,
3425
+ ) -> None:
3426
+ expected_relative = run_ref.verification_inputs.relative_to(project_root).as_posix()
3427
+ if reference.relative_path != expected_relative:
3428
+ raise ValueError(
3429
+ f"verification input reference path {reference.relative_path!r} "
3430
+ f"does not match this run's {expected_relative!r}"
3431
+ )
3432
+ path = safe_qa_path(project_root, expected_relative)
3433
+ stored = store.read(path, reference.digest)
3434
+ if stored["sourceRoot"] != str(source):
3435
+ raise ValueError(
3436
+ "verification input source root does not match the selected worktree"
3437
+ )
3438
+ frozen_plan = stored.get("approvedPlan")
3439
+ if frozen_plan is not None:
3440
+ if approved_plan is None:
3441
+ raise ValueError(
3442
+ f"snapshot was frozen with approved plan {frozen_plan['path']!r}; "
3443
+ "no .data.json approved plan is selected"
3444
+ )
3445
+ selected = str(approved_plan.resolve())
3446
+ if frozen_plan["path"] != selected:
3447
+ raise ValueError(
3448
+ f"selected approved plan {selected!r} "
3449
+ f"does not match frozen {frozen_plan['path']!r}"
3450
+ )
3451
+
3452
+
3453
+ def _prepare_verification_input_reference(
3454
+ ctx: dict, store: VerificationInputStore,
3455
+ ) -> None:
3456
+ if ctx["TASK_TYPE"] not in QA_COMMAND_EXECUTING_TASK_TYPES:
3457
+ return
3458
+ try:
3459
+ project_root = Path(ctx["PROJECT_ROOT"]).resolve()
3460
+ run_ref = RunRef.from_run_dir(
3461
+ Path(ctx["RUN_DIR"]), seq=int(ctx["RUN_MANIFESTS_SEQ"]),
3462
+ )
3463
+ recorded = _load_recorded_run_manifest_strict(
3464
+ project_root, ctx["RUN_MANIFEST_PATH"],
3465
+ )
3466
+ reference = retain_recorded_reference(
3467
+ recorded, VerificationInputReference.from_context(ctx),
3468
+ )
3469
+ if recorded is not None and reference is None:
3470
+ return
3471
+ source = _verification_input_source(ctx, reference)
3472
+ if source is None:
3473
+ return
3474
+ plan_path = ctx.get("APPROVED_PLAN_PATH")
3475
+ approved_plan = Path(plan_path) if plan_path else None
3476
+ if approved_plan is not None and not is_report_record_path(approved_plan):
3477
+ approved_plan = None
3478
+ if reference is None:
3479
+ reference = store.freeze(
3480
+ project_root, source, run_ref, approved_plan=approved_plan,
3481
+ )
3482
+ else:
3483
+ _validate_recorded_verification_inputs(
3484
+ project_root, source, run_ref, reference, store, approved_plan,
3485
+ )
3486
+ ctx.update(reference.to_context(project_root))
3487
+ except (OSError, ValueError) as exc:
3488
+ raise PrepareError(f"verification inputs preparation failed: {exc}") from exc
3489
+
3490
+
3389
3491
  def _persist_pre_dispatch_run_manifest(ctx: dict) -> None:
3390
3492
  """Publish and re-read the complete invocation authority before prompts."""
3391
3493
  render_run_manifest(ctx["RUN_MANIFEST_PATH"], ctx)
@@ -4414,7 +4516,6 @@ def prepare_task_bundle(inp: PrepareInputs) -> PrepareOutputs:
4414
4516
  project_root, assignment_plan, inp.brief_path,
4415
4517
  ),
4416
4518
  })
4417
- refresh_run_context_snapshot(ctx)
4418
4519
  if lead_runtime == "codex":
4419
4520
  ctx["CLAUDE_RESUME_COMMAND_PATH"] = ""
4420
4521
  ctx["CLAUDE_RESUME_COMMAND_RELATIVE_PATH"] = ""
@@ -4444,6 +4545,8 @@ def prepare_task_bundle(inp: PrepareInputs) -> PrepareOutputs:
4444
4545
  _write_bundle_artifacts(
4445
4546
  inp, ctx, project_root, lead_runtime, claude_session_id,
4446
4547
  )
4548
+ _prepare_verification_input_reference(ctx, default_verification_input_store())
4549
+ refresh_run_context_snapshot(ctx)
4447
4550
  _prepare_agent_contract(inp, ctx, workspace_root, models)
4448
4551
 
4449
4552
  # ---- write instruction-set scaffolding ----
@@ -0,0 +1,80 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from pathlib import Path, PurePosixPath
5
+ from typing import Mapping
6
+
7
+ from okstra_project.dirs import OKSTRA_DIR_NAME
8
+
9
+ from .qa_commands import qa_relative_path_valid
10
+
11
+ _ARTIFACT_PATH = "verificationInputsPath"
12
+ _ARTIFACT_DIGEST = "verificationInputsDigest"
13
+ _CONTEXT_PATH = "VERIFICATION_INPUTS_RELATIVE_PATH"
14
+ _CONTEXT_DIGEST = "VERIFICATION_INPUTS_DIGEST"
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class VerificationInputReference:
19
+ relative_path: str
20
+ digest: str
21
+
22
+ @classmethod
23
+ def from_artifact_fields(
24
+ cls, payload: Mapping[str, object],
25
+ ) -> VerificationInputReference | None:
26
+ return cls._read(payload, _ARTIFACT_PATH, _ARTIFACT_DIGEST)
27
+
28
+ @classmethod
29
+ def from_context(
30
+ cls, context: Mapping[str, object],
31
+ ) -> VerificationInputReference | None:
32
+ return cls._read(context, _CONTEXT_PATH, _CONTEXT_DIGEST)
33
+
34
+ @classmethod
35
+ def _read(
36
+ cls, payload: Mapping[str, object], path_key: str, digest_key: str,
37
+ ) -> VerificationInputReference | None:
38
+ if path_key not in payload and digest_key not in payload:
39
+ return None
40
+ relative_path = payload.get(path_key)
41
+ digest = payload.get(digest_key)
42
+ if (not isinstance(relative_path, str)
43
+ or not qa_relative_path_valid(relative_path)
44
+ or PurePosixPath(relative_path).parts[0] != OKSTRA_DIR_NAME
45
+ or not isinstance(digest, str) or not digest.strip()):
46
+ raise ValueError(
47
+ "verification input reference requires a project-artifact path "
48
+ "and a non-blank digest"
49
+ )
50
+ return cls(relative_path, digest)
51
+
52
+ def to_artifact_fields(self) -> dict[str, str]:
53
+ return {_ARTIFACT_PATH: self.relative_path, _ARTIFACT_DIGEST: self.digest}
54
+
55
+ def to_context(self, project_root: Path) -> dict[str, str]:
56
+ return {
57
+ _CONTEXT_PATH: self.relative_path,
58
+ _CONTEXT_DIGEST: self.digest,
59
+ "VERIFICATION_INPUTS_PATH": str(project_root / self.relative_path),
60
+ }
61
+
62
+
63
+ def artifact_fields(ref: VerificationInputReference | None) -> dict[str, str]:
64
+ return ref.to_artifact_fields() if ref is not None else {}
65
+
66
+
67
+ def artifact_fields_from_context(context: Mapping[str, object]) -> dict[str, str]:
68
+ return artifact_fields(VerificationInputReference.from_context(context))
69
+
70
+
71
+ def retain_recorded_reference(
72
+ recorded_manifest: Mapping[str, object] | None,
73
+ provided: VerificationInputReference | None,
74
+ ) -> VerificationInputReference | None:
75
+ recorded = VerificationInputReference.from_artifact_fields(recorded_manifest or {})
76
+ if recorded_manifest is not None and recorded is None and provided is not None:
77
+ raise ValueError("recorded run manifest has no verification input reference")
78
+ if (recorded is not None and provided is not None and recorded != provided):
79
+ raise ValueError("verification input reference is immutable")
80
+ return recorded or provided
@@ -0,0 +1,32 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Literal, TypedDict
4
+
5
+ INPUT_SCHEMA_VERSION: Literal["1.0"] = "1.0"
6
+ INPUT_KIND: Literal["verification-inputs"] = "verification-inputs"
7
+ PLAN_INPUT_SCHEMA_VERSION: Literal["2.0"] = "2.0"
8
+
9
+
10
+ class FrozenProcedure(TypedDict):
11
+ body: str
12
+ digest: str
13
+
14
+
15
+ class FrozenVerificationPlan(TypedDict):
16
+ path: str
17
+ digest: str
18
+ reportSchemaVersion: Literal["2.0", "3.0"]
19
+ validationChecklist: list[dict[str, Any]]
20
+ conformance: list[dict[str, Any]]
21
+
22
+
23
+ class _OptionalVerificationPlan(TypedDict, total=False):
24
+ approvedPlan: FrozenVerificationPlan
25
+
26
+
27
+ class VerificationInputs(_OptionalVerificationPlan):
28
+ schemaVersion: Literal["1.0", "2.0"]
29
+ kind: Literal["verification-inputs"]
30
+ sourceRoot: str
31
+ qaCommands: dict[str, list[dict[str, Any]]]
32
+ procedures: dict[str, FrozenProcedure]