okstra 0.229.0 → 0.231.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 (150) hide show
  1. package/README.md +1 -5
  2. package/dist/cli-registry.mjs +0 -18
  3. package/dist/cli-registry.mjs.map +1 -1
  4. package/dist/commands/lifecycle/doctor.mjs +0 -15
  5. package/dist/commands/lifecycle/doctor.mjs.map +1 -1
  6. package/dist/lib/skill-catalog.mjs +4 -4
  7. package/dist/lib/skill-catalog.mjs.map +1 -1
  8. package/docs/architecture/storage-model.md +168 -18
  9. package/docs/architecture.md +15 -14
  10. package/docs/coding-rules.md +15 -0
  11. package/docs/contributor-change-matrix.md +5 -5
  12. package/docs/project-structure-overview.md +13 -19
  13. package/package.json +2 -3
  14. package/runtime/BUILD.json +2 -2
  15. package/runtime/bin/lib/okstra/interactive.sh +2 -1
  16. package/runtime/prompts/coding-preflight/clean-code.md +8 -0
  17. package/runtime/prompts/coding-preflight/overview.md +1 -0
  18. package/runtime/prompts/launch.template.md +7 -5
  19. package/runtime/prompts/lead/convergence.md +4 -4
  20. package/runtime/prompts/lead/okstra-lead-contract.md +19 -18
  21. package/runtime/prompts/lead/phase-routing.md +1 -1
  22. package/runtime/prompts/lead/report-writer.md +3 -3
  23. package/runtime/prompts/lead/team-contract.md +3 -3
  24. package/runtime/prompts/profiles/_coding-conventions-preflight.md +2 -0
  25. package/runtime/python/okstra_ctl/agent/invocation.py +190 -9
  26. package/runtime/python/okstra_ctl/agent/prompt_cli/materialize.py +31 -1
  27. package/runtime/python/okstra_ctl/blocking_checks.py +10 -0
  28. package/runtime/python/okstra_ctl/cmux.py +4 -2
  29. package/runtime/python/okstra_ctl/code_review_census.py +194 -0
  30. package/runtime/python/okstra_ctl/code_review_coverage.py +3 -1
  31. package/runtime/python/okstra_ctl/code_review_scope.py +9 -6
  32. package/runtime/python/okstra_ctl/code_review_target.py +38 -2
  33. package/runtime/python/okstra_ctl/conformance.py +30 -0
  34. package/runtime/python/okstra_ctl/conformance_evidence.py +316 -0
  35. package/runtime/python/okstra_ctl/correction_round.py +19 -13
  36. package/runtime/python/okstra_ctl/dispatch_core.py +1 -1
  37. package/runtime/python/okstra_ctl/dispatch_state.py +1 -0
  38. package/runtime/python/okstra_ctl/execution_mutation_audit.py +13 -1
  39. package/runtime/python/okstra_ctl/generated_input.py +21 -0
  40. package/runtime/python/okstra_ctl/ids.py +1 -41
  41. package/runtime/python/okstra_ctl/incremental_carry.py +7 -4
  42. package/runtime/python/okstra_ctl/initial_prompt_materialization.py +30 -0
  43. package/runtime/python/okstra_ctl/interactive_cli.py +5 -0
  44. package/runtime/python/okstra_ctl/locks.py +28 -1
  45. package/runtime/python/okstra_ctl/model_io/renderers.py +7 -0
  46. package/runtime/python/okstra_ctl/paths.py +90 -33
  47. package/runtime/python/okstra_ctl/phases/catalog.py +3 -0
  48. package/runtime/python/okstra_ctl/phases/change_impact_analysis/spec.md +2 -2
  49. package/runtime/python/okstra_ctl/phases/discussion/spec.md +63 -63
  50. package/runtime/python/okstra_ctl/phases/discussion/wizard.py +2 -11
  51. package/runtime/python/okstra_ctl/phases/error_analysis/report_assets/error-analysis-input.template.md +1 -1
  52. package/runtime/python/okstra_ctl/phases/error_analysis/spec.md +2 -2
  53. package/runtime/python/okstra_ctl/phases/feature_analysis/spec.md +1 -1
  54. package/runtime/python/okstra_ctl/phases/final_verification/profile.md +5 -4
  55. package/runtime/python/okstra_ctl/phases/final_verification/report_assets/final-verification-input.template.md +1 -1
  56. package/runtime/python/okstra_ctl/phases/final_verification/report_assets/final-verification.template.html +8 -0
  57. package/runtime/python/okstra_ctl/phases/final_verification/spec.md +5 -4
  58. package/runtime/python/okstra_ctl/phases/final_verification/validation.py +53 -0
  59. package/runtime/python/okstra_ctl/phases/implementation/host-rules.md +6 -2
  60. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-deliverable.md +4 -2
  61. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-executor.md +1 -1
  62. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-verifier.md +23 -7
  63. package/runtime/python/okstra_ctl/phases/implementation/report_assets/implementation-input.template.md +1 -1
  64. package/runtime/python/okstra_ctl/phases/implementation/report_assets/implementation.template.html +1 -1
  65. package/runtime/python/okstra_ctl/phases/implementation/spec.md +6 -4
  66. package/runtime/python/okstra_ctl/phases/implementation/validation.py +152 -30
  67. package/runtime/python/okstra_ctl/phases/implementation_option_selection/spec.md +2 -2
  68. package/runtime/python/okstra_ctl/phases/implementation_planning/authoring.py +16 -22
  69. package/runtime/python/okstra_ctl/phases/implementation_planning/instructions/plan-body-verification.md +12 -12
  70. package/runtime/python/okstra_ctl/phases/implementation_planning/plan_body.py +14 -0
  71. package/runtime/python/okstra_ctl/phases/implementation_planning/profile.md +4 -4
  72. package/runtime/python/okstra_ctl/phases/implementation_planning/report_assets/implementation-planning-input.template.md +1 -1
  73. package/runtime/python/okstra_ctl/phases/implementation_planning/spec.md +1 -1
  74. package/runtime/python/okstra_ctl/phases/implementation_planning/wizard.py +11 -4
  75. package/runtime/python/okstra_ctl/phases/project_analysis/spec.md +2 -2
  76. package/runtime/python/okstra_ctl/phases/release_handoff/entry.py +7 -3
  77. package/runtime/python/okstra_ctl/phases/release_handoff/operations.py +4 -5
  78. package/runtime/python/okstra_ctl/phases/release_handoff/profile.md +1 -1
  79. package/runtime/python/okstra_ctl/phases/release_handoff/report_assets/release-handoff-input.template.md +1 -1
  80. package/runtime/python/okstra_ctl/phases/release_handoff/spec.md +4 -4
  81. package/runtime/python/okstra_ctl/phases/technical_verification/spec.md +1 -1
  82. package/runtime/python/okstra_ctl/plan_items.py +28 -0
  83. package/runtime/python/okstra_ctl/process_group.py +26 -3
  84. package/runtime/python/okstra_ctl/qa_commands.py +5 -1
  85. package/runtime/python/okstra_ctl/recap.py +1 -2
  86. package/runtime/python/okstra_ctl/render.py +25 -2
  87. package/runtime/python/okstra_ctl/report_assembly.py +102 -1
  88. package/runtime/python/okstra_ctl/report_execution_evidence.py +220 -0
  89. package/runtime/python/okstra_ctl/report_finalize.py +3 -3
  90. package/runtime/python/okstra_ctl/report_inputs.py +28 -0
  91. package/runtime/python/okstra_ctl/report_narrative.py +12 -3
  92. package/runtime/python/okstra_ctl/report_synthesis_packet.py +5 -0
  93. package/runtime/python/okstra_ctl/run.py +40 -20
  94. package/runtime/python/okstra_ctl/stage_close.py +52 -6
  95. package/runtime/python/okstra_ctl/stage_command_commits.py +143 -0
  96. package/runtime/python/okstra_ctl/stage_fix_carry.py +21 -1
  97. package/runtime/python/okstra_ctl/stage_integrate.py +90 -25
  98. package/runtime/python/okstra_ctl/verification_capture.py +291 -0
  99. package/runtime/python/okstra_ctl/verification_conformance.py +28 -9
  100. package/runtime/python/okstra_ctl/verification_dispatch.py +136 -0
  101. package/runtime/python/okstra_ctl/verification_evidence.py +671 -0
  102. package/runtime/python/okstra_ctl/verification_generation.py +34 -16
  103. package/runtime/python/okstra_ctl/verification_input_ref.py +9 -0
  104. package/runtime/python/okstra_ctl/verification_input_types.py +2 -0
  105. package/runtime/python/okstra_ctl/verification_inputs.py +83 -2
  106. package/runtime/python/okstra_ctl/verification_invocation.py +140 -0
  107. package/runtime/python/okstra_ctl/verification_target.py +10 -3
  108. package/runtime/python/okstra_ctl/wizard/engine.py +23 -0
  109. package/runtime/python/okstra_ctl/wizard/registry.py +2 -1
  110. package/runtime/python/okstra_ctl/wizard/render.py +2 -1
  111. package/runtime/python/okstra_ctl/wizard/sources.py +14 -3
  112. package/runtime/python/okstra_ctl/wizard/steps_identity.py +2 -1
  113. package/runtime/python/okstra_ctl/wizard/steps_plan.py +6 -2
  114. package/runtime/python/okstra_ctl/worker_runner.py +1 -1
  115. package/runtime/python/okstra_ctl/worktree/git_ops.py +8 -1
  116. package/runtime/python/okstra_ctl/worktree/rebase.py +5 -2
  117. package/runtime/python/okstra_ctl/worktree_lock_cli.py +70 -17
  118. package/runtime/python/okstra_ctl/worktree_registry.py +4 -0
  119. package/runtime/schemas/final-report-v3.0.schema.json +184 -1
  120. package/runtime/skills/okstra-code-review/SKILL.md +7 -5
  121. package/runtime/skills/okstra-code-review/references/census-rules.md +2 -2
  122. package/runtime/skills/okstra-explain-flow/SKILL.md +1 -1
  123. package/runtime/skills/okstra-run/SKILL.md +11 -7
  124. package/runtime/skills/okstra-schedule-gen/SKILL.md +3 -3
  125. package/runtime/skills/okstra-setup/SKILL.md +2 -3
  126. package/runtime/templates/reports/html/i18n/en.json +7 -0
  127. package/runtime/templates/reports/html/i18n/ko.json +7 -0
  128. package/runtime/validators/validate-run.py +130 -20
  129. package/runtime/validators/validate-workflow.sh +1 -1
  130. package/docs/cli.md +0 -1060
  131. package/docs/container.md +0 -100
  132. package/docs/follow-ups/2026-07-10-final-report-option-3.md +0 -51
  133. package/docs/performance-improvement-plan-v2.md +0 -369
  134. package/runtime/python/okstra_ctl/container.py +0 -702
  135. package/runtime/python/okstra_ctl/rollup.py +0 -241
  136. package/runtime/python/okstra_ctl/usage_report.py +0 -362
  137. package/runtime/skills/okstra-container-build/SKILL.md +0 -139
  138. package/runtime/skills/okstra-inspect/SKILL.md +0 -100
  139. package/runtime/skills/okstra-inspect/facets/cost.md +0 -84
  140. package/runtime/skills/okstra-inspect/facets/error-zip.md +0 -41
  141. package/runtime/skills/okstra-inspect/facets/errors.md +0 -69
  142. package/runtime/skills/okstra-inspect/facets/history.md +0 -86
  143. package/runtime/skills/okstra-inspect/facets/logs.md +0 -89
  144. package/runtime/skills/okstra-inspect/facets/recap.md +0 -167
  145. package/runtime/skills/okstra-inspect/facets/report.md +0 -57
  146. package/runtime/skills/okstra-inspect/facets/run-audit.md +0 -34
  147. package/runtime/skills/okstra-inspect/facets/status.md +0 -163
  148. package/runtime/skills/okstra-inspect/facets/time.md +0 -57
  149. package/runtime/skills/okstra-rollup/SKILL.md +0 -75
  150. package/runtime/skills/okstra-usage/SKILL.md +0 -71
@@ -2,7 +2,7 @@
2
2
  from __future__ import annotations
3
3
 
4
4
  import contextlib
5
- from dataclasses import dataclass
5
+ from dataclasses import dataclass, replace
6
6
  from datetime import datetime, timezone
7
7
  import fcntl
8
8
  import hashlib
@@ -15,6 +15,10 @@ import tempfile
15
15
  from typing import Any, Iterator, Literal, Mapping, get_args
16
16
 
17
17
  from ..domain.role import RoleCatalogError, role_for_duty
18
+ from ..verification_invocation import (
19
+ VerificationGenerationReference, read_invocation_generation,
20
+ select_verification_generation_header_lines, verification_generation_headers,
21
+ )
18
22
  from ..json_boundary import (
19
23
  JsonBoundaryError,
20
24
  external_invocation_json_source,
@@ -185,6 +189,7 @@ class AgentInvocationRequest:
185
189
  # Republish a prompt this invocation id already wrote, but only while no
186
190
  # dispatch has used it. See `_publish_or_reuse`.
187
191
  replace_undispatched: bool = False
192
+ verification_generation: VerificationGenerationReference | None = None
188
193
 
189
194
 
190
195
  @dataclass(frozen=True)
@@ -641,6 +646,7 @@ def prepare_agent_invocation(
641
646
  request: AgentInvocationRequest,
642
647
  ) -> PreparedAgentInvocation:
643
648
  """Materialize one immutable prompt and its adjacent completion metadata."""
649
+ request = _bind_generation_request(request)
644
650
  _validate_request(request)
645
651
  materialized = _materialize(request)
646
652
  if materialized.reservation_root is None:
@@ -707,7 +713,7 @@ def materialize_retry_invocation(
707
713
  retry_metadata_path = retry_prompt_path.with_name(
708
714
  retry_prompt_path.name + ".meta.json"
709
715
  )
710
- retry_invocation_id = f"{metadata['invocationId']}-attempt-{attempt}"
716
+ retry_invocation_id = _attempt_invocation_id(identity.invocation_ref, attempt)
711
717
  retry_metadata = dict(metadata)
712
718
  retry_metadata["invocationId"] = retry_invocation_id
713
719
  retry_metadata["attempt"] = attempt
@@ -748,7 +754,7 @@ def materialize_retry_invocation(
748
754
  }
749
755
  with _exclusive_lock(reservation_root / "publish.lock"):
750
756
  _publish_or_reuse_exact(
751
- reservation_root / f"{retry_invocation_id}.json",
757
+ _reservation_path(reservation_root, retry_invocation_id),
752
758
  _pretty_json(reservation),
753
759
  )
754
760
  with _exclusive_lock(_prompt_lock_path(retry_prompt_path)):
@@ -811,12 +817,14 @@ def _retry_prompt_bytes(
811
817
 
812
818
  def compose_agent_prompt(request: AgentInvocationRequest) -> str:
813
819
  """Render and validate a prompt candidate without publishing artifacts."""
820
+ request = _bind_generation_request(request)
814
821
  _validate_request(request)
815
822
  return _materialize(request).prompt_bytes.decode("utf-8")
816
823
 
817
824
 
818
825
  def compose_unbound_run_prompt(request: AgentInvocationRequest) -> bytes:
819
826
  """Compose v2 run prompt bytes before a dynamic role identity is reserved."""
827
+ request = _bind_generation_request(request)
820
828
  _validate_common_request(request)
821
829
  _validate_unbound_v2_run_request(request)
822
830
  common = load_common_duty_contract(request.duty_root)
@@ -1172,6 +1180,58 @@ def _materialize(request: AgentInvocationRequest) -> _MaterializedInvocation:
1172
1180
  )
1173
1181
 
1174
1182
 
1183
+ def _bind_generation_request(request: AgentInvocationRequest) -> AgentInvocationRequest:
1184
+ try:
1185
+ manifest = _load_request_manifest(request)
1186
+ reference = _typed_generation_reference(request)
1187
+ _require_sealed_generation(
1188
+ request.project_root, request.run_manifest_path, manifest,
1189
+ reference, request.audience,
1190
+ )
1191
+ return _with_generation_anchors(request, reference)
1192
+ except (OSError, ValueError) as exc:
1193
+ raise AgentInvocationError(str(exc)) from exc
1194
+
1195
+
1196
+ def _load_request_manifest(request: AgentInvocationRequest) -> dict[str, object]:
1197
+ if request.run_manifest_path is None:
1198
+ return {}
1199
+ _project_relative(request.run_manifest_path, request.project_root, must_exist=True)
1200
+ return _load_json_object(request.run_manifest_path, "run manifest")
1201
+
1202
+
1203
+ def _typed_generation_reference(
1204
+ request: AgentInvocationRequest,
1205
+ ) -> VerificationGenerationReference | None:
1206
+ reference = request.verification_generation
1207
+ if reference is not None and not isinstance(
1208
+ reference, VerificationGenerationReference,
1209
+ ):
1210
+ raise ValueError("verification generation reference is invalid")
1211
+ return reference
1212
+
1213
+
1214
+ def _with_generation_anchors(
1215
+ request: AgentInvocationRequest,
1216
+ reference: VerificationGenerationReference | None,
1217
+ ) -> AgentInvocationRequest:
1218
+ anchors = request.instruction.anchor_lines
1219
+ existing = select_verification_generation_header_lines(anchors)
1220
+ if reference is None:
1221
+ if existing:
1222
+ raise ValueError(
1223
+ "verification generation anchors require a bound generation"
1224
+ )
1225
+ return request
1226
+ headers = verification_generation_headers(reference)
1227
+ if existing and existing != headers:
1228
+ raise ValueError("verification generation anchors conflict with reference")
1229
+ return replace(request, instruction=replace(
1230
+ request.instruction,
1231
+ anchor_lines=anchors if existing else (*anchors, *headers),
1232
+ ))
1233
+
1234
+
1175
1235
  def _validate_request(request: AgentInvocationRequest) -> None:
1176
1236
  _validate_common_request(request)
1177
1237
  if request.run_manifest_path is None:
@@ -1448,7 +1508,7 @@ def _invocation_digests(
1448
1508
  }
1449
1509
 
1450
1510
 
1451
- def _metadata_payload(
1511
+ def _base_metadata_payload(
1452
1512
  request: AgentInvocationRequest,
1453
1513
  duty: DutyContract,
1454
1514
  digests: Mapping[str, str],
@@ -1495,7 +1555,18 @@ def _metadata_payload(
1495
1555
  )
1496
1556
  },
1497
1557
  "digests": dict(digests),
1558
+ **({"verificationGeneration": request.verification_generation.to_payload()}
1559
+ if request.verification_generation is not None else {}),
1498
1560
  }
1561
+ return payload
1562
+
1563
+
1564
+ def _metadata_payload(
1565
+ request: AgentInvocationRequest,
1566
+ duty: DutyContract,
1567
+ digests: Mapping[str, str],
1568
+ ) -> dict[str, object]:
1569
+ payload = _base_metadata_payload(request, duty, digests)
1499
1570
  if _request_identity_version(request) == 2:
1500
1571
  manifest = _load_json_object(request.run_manifest_path, "run manifest")
1501
1572
  identity = invocation_execution_identity_from_manifest(
@@ -1624,7 +1695,7 @@ def _publish_or_reuse_reservation(materialized: _MaterializedInvocation) -> None
1624
1695
  reservation = materialized.reservation
1625
1696
  if root is None or reservation is None:
1626
1697
  return
1627
- path = root / f"{materialized.prepared.invocation_id}.json"
1698
+ path = _reservation_path(root, materialized.prepared.invocation_id)
1628
1699
  if path.exists():
1629
1700
  if _read_json_if_object(path) != reservation:
1630
1701
  raise AgentInvocationError(
@@ -1901,9 +1972,108 @@ def _verify_prompt_file(
1901
1972
  errors.extend(_verify_instruction_digest(metadata, body))
1902
1973
  errors.extend(_verify_model_header(metadata, body))
1903
1974
  errors.extend(_verify_execution_delivery(metadata, path, body))
1975
+ errors.extend(_verify_generation_reference(metadata, project_root, body))
1904
1976
  return errors
1905
1977
 
1906
1978
 
1979
+ def _verify_generation_reference(
1980
+ metadata: Mapping[str, object], project_root: Path, prompt_bytes: bytes,
1981
+ ) -> list[str]:
1982
+ try:
1983
+ reference = metadata_generation_reference(metadata)
1984
+ manifest_path, manifest = _metadata_run_manifest(metadata, project_root)
1985
+ _require_sealed_generation(
1986
+ project_root, manifest_path, manifest, reference, metadata["audience"],
1987
+ )
1988
+ return _prompt_generation_header_errors(prompt_bytes, reference)
1989
+ except (AgentInvocationError, OSError, ValueError) as exc:
1990
+ return [str(exc)]
1991
+
1992
+
1993
+ def metadata_generation_reference(
1994
+ metadata: Mapping[str, object],
1995
+ ) -> VerificationGenerationReference | None:
1996
+ if "verificationGeneration" not in metadata:
1997
+ return None
1998
+ return VerificationGenerationReference.from_payload(
1999
+ metadata["verificationGeneration"],
2000
+ )
2001
+
2002
+
2003
+ def reserved_generation_reference(
2004
+ project_root: Path, manifest: Mapping[str, object], invocation_ref: str,
2005
+ attempt: int,
2006
+ ) -> VerificationGenerationReference | None:
2007
+ """The generation the metadata of one reserved v2 attempt is bound to; None
2008
+ when the run reserved no such attempt or bound it to no generation.
2009
+
2010
+ The reservation names the metadata, so a reader does not take a generation
2011
+ file on the strength of the path its dispatch kind computes.
2012
+ """
2013
+ contract = manifest.get("agentContract")
2014
+ if not isinstance(contract, Mapping):
2015
+ return None
2016
+ root = _project_path(
2017
+ project_root, contract.get("invocationReservationRootPath"), must_exist=False,
2018
+ )
2019
+ path = _reservation_path(root, _attempt_invocation_id(invocation_ref, attempt))
2020
+ if not path.is_file():
2021
+ return None
2022
+ reservation = _load_json_object(path, "invocation reservation")
2023
+ metadata = _load_json_object(
2024
+ _project_path(project_root, reservation.get("metadataPath"), must_exist=True),
2025
+ "agent invocation metadata",
2026
+ )
2027
+ for payload in (reservation, metadata):
2028
+ if (payload.get("invocationRef"), payload.get("attempt")) != (
2029
+ invocation_ref, attempt):
2030
+ raise AgentInvocationError(
2031
+ f"invocation reservation {path} names another invocation attempt"
2032
+ )
2033
+ return metadata_generation_reference(metadata)
2034
+
2035
+
2036
+ def _attempt_invocation_id(invocation_ref: str, attempt: int) -> str:
2037
+ """A v2 attempt's invocation id. The first attempt's id is the invocation
2038
+ reference (`_validate_v2_run_identity`), and every retry derives from it so
2039
+ a reader holding only the reference finds the attempt's reservation."""
2040
+ return invocation_ref if attempt == 1 else f"{invocation_ref}-attempt-{attempt}"
2041
+
2042
+
2043
+ def _reservation_path(root: Path, invocation_id: str) -> Path:
2044
+ return root / f"{invocation_id}.json"
2045
+
2046
+
2047
+ def _metadata_run_manifest(
2048
+ metadata: Mapping[str, object], project_root: Path,
2049
+ ) -> tuple[Path | None, dict[str, object]]:
2050
+ value = metadata["contractSource"].get("runManifestPath")
2051
+ if not value:
2052
+ return None, {}
2053
+ manifest_path = _project_path(project_root, value, must_exist=True)
2054
+ return manifest_path, _load_json_object(manifest_path, "run manifest")
2055
+
2056
+
2057
+ def _prompt_generation_header_errors(
2058
+ prompt_bytes: bytes, reference: VerificationGenerationReference | None,
2059
+ ) -> list[str]:
2060
+ prefix, _ = _split_prompt(prompt_bytes.decode("utf-8"))
2061
+ actual = select_verification_generation_header_lines(prefix.splitlines())
2062
+ expected = verification_generation_headers(reference) if reference else ()
2063
+ if actual != expected:
2064
+ return ["verification generation reference differs from prompt"]
2065
+ return []
2066
+
2067
+
2068
+ def _require_sealed_generation(
2069
+ project_root: Path, manifest_path: Path | None, manifest: Mapping[str, object],
2070
+ reference: VerificationGenerationReference | None, audience: str,
2071
+ ) -> None:
2072
+ read_invocation_generation(
2073
+ project_root, manifest_path, manifest, reference, audience,
2074
+ )
2075
+
2076
+
1907
2077
  def _execution_delivery_lines(
1908
2078
  metadata: Mapping[str, object], metadata_path: Path,
1909
2079
  ) -> tuple[str, ...]:
@@ -2289,7 +2459,7 @@ def _verify_reservation(
2289
2459
  contract["invocationReservationRootPath"],
2290
2460
  must_exist=True,
2291
2461
  )
2292
- path = root / f"{metadata['invocationId']}.json"
2462
+ path = _reservation_path(root, metadata["invocationId"])
2293
2463
  actual = _load_json_object(path, "invocation reservation")
2294
2464
  except (AgentInvocationError, KeyError):
2295
2465
  return ["invocation reservation is missing or invalid"]
@@ -2323,12 +2493,20 @@ def _verify_reservation(
2323
2493
 
2324
2494
  def _metadata_schema_is_exact(metadata: Mapping[str, object]) -> bool:
2325
2495
  schema = metadata.get("schemaVersion")
2496
+ present_optional_keys = set(metadata) & {"verificationGeneration"}
2497
+ has_generation = "verificationGeneration" in metadata
2498
+ if has_generation:
2499
+ generation = metadata["verificationGeneration"]
2500
+ try:
2501
+ VerificationGenerationReference.from_payload(generation)
2502
+ except ValueError:
2503
+ return False
2326
2504
  if schema == 1:
2327
- if set(metadata) != _TOP_LEVEL_KEYS:
2505
+ if set(metadata) != _TOP_LEVEL_KEYS | present_optional_keys:
2328
2506
  return False
2329
2507
  elif schema == "2.0":
2330
2508
  if (
2331
- set(metadata) != _V2_TOP_LEVEL_KEYS
2509
+ set(metadata) != _V2_TOP_LEVEL_KEYS | present_optional_keys
2332
2510
  or metadata.get("executionIdentityVersion") != 2
2333
2511
  or not all(
2334
2512
  isinstance(metadata.get(key), str) and metadata[key]
@@ -2360,13 +2538,16 @@ def _metadata_schema_is_exact(metadata: Mapping[str, object]) -> bool:
2360
2538
  return False
2361
2539
  if any(not isinstance(item, dict) or set(item) != {"kind", "path"} for item in sources):
2362
2540
  return False
2363
- return _digest_paths(metadata) == {
2541
+ expected_digests = {
2364
2542
  "digests.catalogDigest",
2365
2543
  "digests.assignmentDigest",
2366
2544
  "digests.dutyDigest",
2367
2545
  "digests.instructionDigest",
2368
2546
  "digests.promptDigest",
2369
2547
  }
2548
+ if has_generation:
2549
+ expected_digests.add("verificationGeneration.digest")
2550
+ return _digest_paths(metadata) == expected_digests
2370
2551
 
2371
2552
 
2372
2553
  def _model_assignment_projection(payload: object) -> dict[str, object] | None:
@@ -25,6 +25,7 @@ from ..invocation import (
25
25
  agent_model_assignment_from_payload,
26
26
  digest_duty_catalog,
27
27
  invocation_execution_identity_from_manifest,
28
+ metadata_generation_reference,
28
29
  prepare_agent_invocation,
29
30
  compose_agent_prompt,
30
31
  compose_unbound_run_prompt,
@@ -93,6 +94,8 @@ from .inputs import (
93
94
  _relative,
94
95
  )
95
96
  from .run_identity import _validate_run_identity
97
+ from ...verification_dispatch import seal_dispatch_generation
98
+ from ...verification_invocation import VerificationGenerationReference
96
99
 
97
100
 
98
101
  _AUDIENCES = frozenset(get_args(AgentAudience))
@@ -307,6 +310,10 @@ def _materialize_run(
307
310
  active_context = hydrate_active_run_context(
308
311
  _read_json_object(active_context_path, "active run context")
309
312
  )
313
+ metadata_path = prompt_path.with_name(prompt_path.name + ".meta.json")
314
+ generation = _reuse_or_seal_verifier_generation(
315
+ args, project_root, manifest_path, manifest, active_context, metadata_path,
316
+ )
310
317
  prompt_rel = _relative(project_root, prompt_path)
311
318
  result_rel = _relative(project_root, result_path)
312
319
  audit_rel = _relative(project_root, audit_source_path)
@@ -390,7 +397,7 @@ def _materialize_run(
390
397
  run_manifest_path=manifest_path,
391
398
  duty_root=duty_root,
392
399
  prompt_path=prompt_path,
393
- metadata_path=prompt_path.with_name(prompt_path.name + ".meta.json"),
400
+ metadata_path=metadata_path,
394
401
  dispatch_kind=args.dispatch_kind,
395
402
  participant_ref=identity.participant_ref if identity is not None else None,
396
403
  role_execution_ref=(
@@ -400,6 +407,7 @@ def _materialize_run(
400
407
  invocation_ref=args.invocation_id if identity is not None else None,
401
408
  attempt=1,
402
409
  replace_undispatched=args.replace_undispatched,
410
+ verification_generation=generation,
403
411
  )
404
412
  if is_reverify:
405
413
  candidate = compose_unbound_run_prompt(request).decode("utf-8") if dynamic_source else compose_agent_prompt(request)
@@ -427,6 +435,28 @@ def _materialize_run(
427
435
  _RESOURCE_AUDIENCES = frozenset({"implementation-executor", "implementation-verifier"})
428
436
 
429
437
 
438
+ def _reuse_or_seal_verifier_generation(
439
+ args: argparse.Namespace, project_root: Path, manifest_path: Path,
440
+ manifest: Mapping[str, Any], active_context: Mapping[str, Any],
441
+ metadata_path: Path,
442
+ ) -> VerificationGenerationReference | None:
443
+ # A rerun over a published prompt reuses the generation its metadata binds;
444
+ # sealing again would recapture a tree the verifier's own run may have changed.
445
+ try:
446
+ if metadata_path.is_file():
447
+ published = metadata_generation_reference(
448
+ _read_json_object(metadata_path, "invocation metadata"),
449
+ )
450
+ if published is not None:
451
+ return published
452
+ return seal_dispatch_generation(
453
+ project_root, manifest_path, manifest, active_context,
454
+ audience=args.audience, dispatch_kind=args.dispatch_kind,
455
+ )
456
+ except ValueError as exc:
457
+ raise AgentPromptCliError(f"verification generation: {exc}") from exc
458
+
459
+
430
460
  def _implementation_anchors(
431
461
  project_root: Path, manifest_path: Path, worker_id: str,
432
462
  ) -> list[str]:
@@ -235,6 +235,16 @@ _BLOCKING: tuple[tuple[str, str], ...] = (
235
235
  "verifierResults 가 마지막 라운드의 verdict 가 아니면 release_gate.py 와 "
236
236
  "stage_fix_carry.py 가 다른 라운드의 판정으로 stage 를 정착시키거나 fix run 을 연다.",
237
237
  ),
238
+ # An evidence-contract run's checks are the execution records the runner
239
+ # observed (`report_execution_evidence.py`).
240
+ (
241
+ "execution-evidence BLOCKING:",
242
+ "The report shows a check result that is not the verifier's current "
243
+ "execution record (another invocation, attempt, check, check run or "
244
+ "generation, changed bytes, or an incomplete record shown as executed), "
245
+ "so the stage and release gates read a verification this run did not "
246
+ "observe.",
247
+ ),
238
248
  (
239
249
  "implementation run declares stage-",
240
250
  "stage 캐리 사이드카가 디스크에 없다 — consumers.py 의 "
@@ -222,7 +222,7 @@ class PaneGeometry:
222
222
  columns: int
223
223
  rows: int
224
224
  x: int
225
- y: int
225
+ y: float
226
226
  cell_width_points: int
227
227
  width_points: float = 0.0
228
228
  ref: str = ""
@@ -1023,7 +1023,9 @@ def _pane_geometry(entry: dict[str, Any]) -> PaneGeometry:
1023
1023
  columns=int(entry.get("columns", 0)),
1024
1024
  rows=int(entry.get("rows", 0)),
1025
1025
  x=int(frame.get("x", 0)),
1026
- y=int(frame.get("y", 0)),
1026
+ # `_overlaps_vertically` adds a fractional height to y. A truncated y
1027
+ # puts a pane flush below the lead inside the lead's rows.
1028
+ y=float(frame.get("y") or 0),
1027
1029
  cell_width_points=int(entry.get("cell_width_points", 0)),
1028
1030
  width_points=float(frame.get("width") or 0),
1029
1031
  ref=str(entry.get("ref", "")),
@@ -0,0 +1,194 @@
1
+ """Build a code-review census from a diff, so membership stays mechanical."""
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ import re
6
+ import subprocess
7
+ from dataclasses import dataclass
8
+ from pathlib import Path, PurePosixPath
9
+
10
+ from .code_review_coverage import read_review_census
11
+
12
+ _GROUPS = ("structural", "semantic", "state-and-tests", "general")
13
+ _FILE_GROUPS = {
14
+ "source": ("structural", "state-and-tests", "general"),
15
+ "test": ("state-and-tests",),
16
+ }
17
+ _ALWAYS_CENSUSED = ("skills/", "prompts/", "agents/", "templates/")
18
+ _LOCKFILES = {
19
+ "package-lock.json", "yarn.lock", "pnpm-lock.yaml", "poetry.lock",
20
+ "Cargo.lock", "uv.lock", "Gemfile.lock", "composer.lock",
21
+ }
22
+ _GENERATED_ROOTS = ("dist/", "runtime/", "build/")
23
+ _DATA_SUFFIXES = {".json", ".yml", ".yaml", ".toml", ".ini", ".cfg", ".csv"}
24
+ _PROSE_SUFFIXES = {".md", ".markdown", ".rst", ".txt"}
25
+ _UNPARSED_CODE_SUFFIXES = {
26
+ ".js", ".mjs", ".cjs", ".ts", ".mts", ".cts", ".tsx", ".jsx", ".sh", ".bash",
27
+ ".go", ".rs", ".java", ".kt", ".kts", ".rb", ".php", ".swift", ".c", ".h",
28
+ ".cc", ".cpp", ".hpp", ".cs", ".scala",
29
+ }
30
+ _TEST_PATH = re.compile(
31
+ r"(^|/)(tests?|spec|__tests__)/|(^|/)test_[^/]+\.py$|_test\.[^/]+$"
32
+ r"|\.(test|spec)\.[^/]+$"
33
+ )
34
+ _POSITION = re.compile(r":\d+(?::\d+)?(?= )")
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class CensusResult:
39
+ text: str
40
+ unresolved: tuple[str, ...]
41
+
42
+
43
+ def build_review_census(
44
+ repo: Path, base: str, head: str, rules_source: Path,
45
+ changed: dict[str, set[int]], *, previous: Path | None = None,
46
+ ) -> CensusResult:
47
+ rules = _rules_section(rules_source.read_text(encoding="utf-8"))
48
+ files = _changed_files(repo, base, head)
49
+ cells: list[tuple[str, str]] = []
50
+ exclusions: list[tuple[str, str]] = []
51
+ unresolved: list[str] = []
52
+ functions: list[str] = []
53
+ for path, binary in files:
54
+ reason = _exclusion(path, binary)
55
+ if reason:
56
+ exclusions.append((path, reason))
57
+ continue
58
+ kind = "test" if _TEST_PATH.search(path) else "source"
59
+ cells.extend((path, group) for group in _FILE_GROUPS[kind])
60
+ if kind == "test" or path not in changed:
61
+ continue
62
+ suffix = PurePosixPath(path).suffix
63
+ if suffix == ".py":
64
+ functions.extend(_changed_functions(repo, head, path, changed[path]))
65
+ elif suffix in _UNPARSED_CODE_SUFFIXES:
66
+ unresolved.append(path)
67
+ cells.extend((target, "semantic") for target in functions)
68
+ ordered = sorted(cells, key=lambda cell: _GROUPS.index(cell[1]))
69
+ ids, retired, new = _assign_ids(ordered, previous)
70
+ text = _render(rules, ordered, ids, exclusions, files, unresolved, retired, new,
71
+ previous is not None)
72
+ return CensusResult(text, tuple(unresolved))
73
+
74
+
75
+ def _rules_section(text: str) -> str:
76
+ start = text.find("## Rules")
77
+ if start < 0:
78
+ raise ValueError("rules source has no ## Rules table")
79
+ end = text.find("\n## ", start + 1)
80
+ return text[start:] if end < 0 else text[start:end + 1]
81
+
82
+
83
+ def _changed_files(repo: Path, base: str, head: str) -> list[tuple[str, bool]]:
84
+ listed = subprocess.run(
85
+ ["git", "-C", str(repo), "diff", "--numstat", "-z", "-M", "--no-ext-diff",
86
+ f"{base}..{head}", "--"],
87
+ capture_output=True, check=True,
88
+ ).stdout.decode("utf-8", "surrogateescape").split("\0")
89
+ files: list[tuple[str, bool]] = []
90
+ entries = iter(listed)
91
+ for entry in entries:
92
+ if not entry:
93
+ continue
94
+ added, _, rest = entry.partition("\t")
95
+ _deleted, _, path = rest.partition("\t")
96
+ if not path:
97
+ next(entries)
98
+ path = next(entries)
99
+ files.append((path, added == "-"))
100
+ return files
101
+
102
+
103
+ def _exclusion(path: str, binary: bool) -> str | None:
104
+ if path.startswith(_ALWAYS_CENSUSED):
105
+ return None
106
+ name = PurePosixPath(path).name
107
+ suffix = PurePosixPath(path).suffix.lower()
108
+ if name in _LOCKFILES or name.endswith(".sum"):
109
+ return "lockfile"
110
+ if path.startswith(_GENERATED_ROOTS):
111
+ return "generated build output"
112
+ if binary:
113
+ return "binary file"
114
+ if suffix in _DATA_SUFFIXES:
115
+ return "configuration or data without executable project code"
116
+ if suffix in _PROSE_SUFFIXES:
117
+ return "prose documentation without executable or agent-directive content"
118
+ return None
119
+
120
+
121
+ def _changed_functions(
122
+ repo: Path, head: str, path: str, lines: set[int],
123
+ ) -> list[str]:
124
+ source = subprocess.run(
125
+ ["git", "-C", str(repo), "show", f"{head}:{path}"],
126
+ capture_output=True, check=True,
127
+ ).stdout.decode("utf-8")
128
+ touched: list[str] = []
129
+
130
+ def visit(node: ast.AST, prefix: str) -> None:
131
+ for child in ast.iter_child_nodes(node):
132
+ if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
133
+ start = min([child.lineno, *(d.lineno for d in child.decorator_list)])
134
+ if lines.intersection(range(start, (child.end_lineno or start) + 1)):
135
+ touched.append(f"{path}:{child.lineno} {prefix}{child.name}")
136
+ visit(child, f"{prefix}{child.name}.")
137
+ elif isinstance(child, ast.ClassDef):
138
+ visit(child, f"{prefix}{child.name}.")
139
+
140
+ visit(ast.parse(source, filename=path), "")
141
+ return touched
142
+
143
+
144
+ def _identity(target: str, group: str) -> tuple[str, str]:
145
+ return _POSITION.sub("", target, count=1), group
146
+
147
+
148
+ def _assign_ids(
149
+ cells: list[tuple[str, str]], previous: Path | None,
150
+ ) -> tuple[list[str], list[str], list[str]]:
151
+ known: dict[tuple[str, str], str] = {}
152
+ highest = 0
153
+ if previous is not None:
154
+ old = read_review_census(previous)
155
+ for identity, cell in old.cells.items():
156
+ known[_identity(cell.target, cell.group)] = identity
157
+ highest = max(highest, int(identity.removeprefix("C-CR-")))
158
+ ids: list[str] = []
159
+ new: list[str] = []
160
+ for target, group in cells:
161
+ identity = known.pop(_identity(target, group), None)
162
+ if identity is None:
163
+ highest += 1
164
+ identity = f"C-CR-{highest:04d}"
165
+ new.append(identity)
166
+ ids.append(identity)
167
+ return ids, sorted(known.values()), new
168
+
169
+
170
+ def _render(
171
+ rules: str, cells: list[tuple[str, str]], ids: list[str],
172
+ exclusions: list[tuple[str, str]], files: list[tuple[str, bool]],
173
+ unresolved: list[str], retired: list[str], new: list[str], has_previous: bool,
174
+ ) -> str:
175
+ rows = [rules.rstrip("\n"), "", "## Cells"]
176
+ rows += ["| Cell | Target | Group |", "|---|---|---|"]
177
+ rows += [f"| {cell_id} | {target} | {group} |"
178
+ for cell_id, (target, group) in zip(ids, cells)]
179
+ rows += ["", "## Exclusions"]
180
+ rows += [f"- `{path}`: {reason}." for path, reason in exclusions] or ["- none"]
181
+ censused = len({target.partition(":")[0] for target, _ in cells})
182
+ rows += [
183
+ "", "## Accounting",
184
+ f"- Changed files: {len(files)}; censused: {censused}; "
185
+ f"excluded: {len(exclusions)}",
186
+ "- Unresolved function boundaries: " + (", ".join(unresolved) or "-"),
187
+ ]
188
+ if has_previous:
189
+ rows += [
190
+ "", "## Changes from previous census",
191
+ "- Retired: " + (", ".join(retired) or "-"),
192
+ "- New: " + (", ".join(new) or "-"),
193
+ ]
194
+ return "\n".join(rows) + "\n"
@@ -26,7 +26,9 @@ class ReviewCensus:
26
26
 
27
27
 
28
28
  def _table_fields(line: str) -> list[str]:
29
- return [field.strip() for field in line.strip().strip("|").split("|")]
29
+ # Markdown writes a literal pipe inside a table cell as `\|`.
30
+ fields = re.split(r"(?<!\\)\|", line.strip().strip("|"))
31
+ return [field.strip().replace("\\|", "|") for field in fields]
30
32
 
31
33
 
32
34
  def read_review_census(path: Path) -> ReviewCensus:
@@ -111,8 +111,8 @@ def review_scope(
111
111
  return full("rule catalog changed")
112
112
  verdicts = check_review_coverage(root, previous_census, completions, prior.commit,
113
113
  base=base_commit)
114
- if verdicts.missing or verdicts.unknown:
115
- return full("previous review coverage is incomplete")
114
+ if verdicts.unknown:
115
+ return full("previous review names unknown cells")
116
116
  try:
117
117
  dependencies = _prior_inputs(
118
118
  root, completions, old,
@@ -139,16 +139,19 @@ def _partition(
139
139
  known = set().union(*dependencies.values()) if dependencies else set()
140
140
  unknown = changed - known
141
141
  carry = []
142
+ # A changed path outside every recorded inventory reopens only the cells that
143
+ # list it; reviewers still search the delta for effects the inventory missed.
142
144
  for identity, cell in census.cells.items():
143
145
  sources = dependencies.get(identity, set())
144
146
  target = cell.target.partition(":")[0]
145
- if (not unknown and old.cells.get(identity) == cell and target in sources
147
+ if (old.cells.get(identity) == cell and target in sources
146
148
  and not changed.intersection(sources)
147
149
  and verdicts.get(identity, ("missing", ""))[0] in ("clean", "n/a")):
148
150
  carry.append(identity)
149
- reason = ("unmapped changed inputs: " + ", ".join(sorted(unknown))) if unknown else (
150
- "review changed dependencies and prior findings; attest carry boundaries"
151
- )
151
+ reason = "review changed dependencies, prior findings and unverified cells"
152
+ if unknown:
153
+ reason += "; search unmapped changed inputs: " + ", ".join(sorted(unknown))
154
+ reason += "; attest carry boundaries"
152
155
  carry_ids = set(carry)
153
156
  return ReviewScope(
154
157
  baseline,