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
@@ -107,6 +107,9 @@ instead of a checked-out tree. This is read-only — it never creates
107
107
  directories or files. `check-coverage` reads head evidence at `--head` and explicit
108
108
  base evidence at `--base`, never the working tree, prints covered cells, missing rules and unknown cells, and exits
109
109
  1 for incomplete coverage and 2 for invalid input or completion evidence.
110
+ `census` writes the range's census to `--out`, copying the Rules table from
111
+ `--rules` and keeping IDs from `--previous-census`; it exits 1 when changed
112
+ non-Python code still needs function cells added by hand.
110
113
  """
111
114
 
112
115
 
@@ -117,7 +120,10 @@ def _build_parser() -> argparse.ArgumentParser:
117
120
  prog="okstra code-review",
118
121
  description="Resolve a code review's diff range and result file path, or check finding citations."
119
122
  )
120
- parser.add_argument("command", choices=("target", "check-lines", "check-coverage", "scope"))
123
+ parser.add_argument(
124
+ "command",
125
+ choices=("target", "check-lines", "check-coverage", "scope", "census"),
126
+ )
121
127
  parser.add_argument("--task-key", default="", help="project-id:task-group:task-id")
122
128
  parser.add_argument("--stage", type=int, default=0, help="stage number to review")
123
129
  parser.add_argument("--branch", default="", help="branch to review")
@@ -138,7 +144,11 @@ def _build_parser() -> argparse.ArgumentParser:
138
144
  parser.add_argument("--completion", action="append", default=[],
139
145
  help="check-coverage: verified reviewer completion (repeat for gap-fills)")
140
146
  parser.add_argument("--previous-head", default="", help="scope: previous reviewed commit")
141
- parser.add_argument("--previous-census", default="", help="scope: previous full census")
147
+ parser.add_argument("--previous-census", default="",
148
+ help="scope, census: previous full census")
149
+ parser.add_argument("--rules", default="",
150
+ help="census: file whose ## Rules table the census copies")
151
+ parser.add_argument("--out", default="", help="census: file to write the census to")
142
152
  parser.add_argument("--policy", action="append", default=[],
143
153
  help="scope: policy/calibration source to fingerprint (repeatable)")
144
154
  parser.add_argument("--date", default="", help="YYYY-MM-DD for branch result naming")
@@ -341,6 +351,8 @@ def main(argv: list[str] | None = None) -> int:
341
351
 
342
352
  if args.command == "scope":
343
353
  return _scope(args, Path(project_root))
354
+ if args.command == "census":
355
+ return _census(args, Path(project_root))
344
356
  if args.command == "check-coverage":
345
357
  return _check_coverage(args, Path(project_root))
346
358
  if args.command == "check-lines":
@@ -370,6 +382,30 @@ def main(argv: list[str] | None = None) -> int:
370
382
  return 0
371
383
 
372
384
 
385
+ def _census(args: argparse.Namespace, project_root: Path) -> int:
386
+ from .code_review_census import build_review_census
387
+ from .code_review_coverage import read_review_census
388
+
389
+ if not (args.base and args.head and args.rules and args.out):
390
+ print("census: pass --base, --head, --rules and --out", file=sys.stderr)
391
+ return 2
392
+ try:
393
+ result = build_review_census(
394
+ project_root, args.base, args.head, Path(args.rules),
395
+ changed_lines(project_root, args.base, args.head),
396
+ previous=Path(args.previous_census) if args.previous_census else None,
397
+ )
398
+ out = Path(args.out)
399
+ out.write_text(result.text, encoding="utf-8")
400
+ read_review_census(out)
401
+ except (OSError, ValueError, SyntaxError, StateError,
402
+ subprocess.CalledProcessError) as exc:
403
+ print(f"census: {exc}", file=sys.stderr)
404
+ return 2
405
+ print(result.text, end="")
406
+ return 1 if result.unresolved else 0
407
+
408
+
373
409
  def _scope(args: argparse.Namespace, project_root: Path) -> int:
374
410
  from .agent.invocation import AgentInvocationError
375
411
  from .code_review_scope import review_scope
@@ -16,8 +16,10 @@ import fnmatch
16
16
  import re
17
17
  from dataclasses import dataclass
18
18
  from pathlib import Path
19
+ from typing import Any, Mapping
19
20
 
20
21
  from .qa_commands import verification_command_defects
22
+ from .qa_procedures import content_digest
21
23
 
22
24
  # diff 가 건드린 표면과 대조할 capability 태그 화이트리스트.
23
25
  CAPABILITY_WHITELIST: tuple[str, ...] = ("db", "io", "http", "external")
@@ -476,6 +478,34 @@ def parse_qa_result(stdout: str) -> QaResult:
476
478
  return QaResult(overall=overall, requirements=requirements)
477
479
 
478
480
 
481
+ def execution_evidence_defect(record: Mapping[str, Any], stdout: bytes) -> str | None:
482
+ """Why an evidence-mode execution record cannot back a result; None when it can."""
483
+ if record.get("status") != "completed":
484
+ return f"status is {record.get('status')}"
485
+ stream = record.get("stdout")
486
+ if (not isinstance(stream, Mapping) or stream.get("bytes") != len(stdout)
487
+ or stream.get("digest") != content_digest(stdout)):
488
+ return "saved stdout is not the output the record observed"
489
+ return None
490
+
491
+
492
+ def qa_result_from_execution(
493
+ record: Mapping[str, Any], stdout: bytes,
494
+ ) -> QaResult | None:
495
+ """Derive one stage's result from an evidence-mode execution record.
496
+
497
+ None means no usable evidence; `execution_evidence_defect` says why.
498
+ """
499
+ if execution_evidence_defect(record, stdout) is not None:
500
+ return None
501
+ result = parse_qa_result(stdout.decode("utf-8", errors="replace"))
502
+ # The marker is the script's claim; the observed exit is the runner's. A
503
+ # signalled run records no exit code, so it is never zero here either.
504
+ if result.overall == "PASS" and record.get("exitCode") != 0:
505
+ return QaResult(overall="FAIL", requirements=result.requirements)
506
+ return result
507
+
508
+
479
509
  @dataclass
480
510
  class ConformanceVerdict:
481
511
  stage_key: str
@@ -0,0 +1,316 @@
1
+ """Select the verification execution records that decide stage conformance.
2
+
3
+ Each stage is decided by the newest sealed generation that lists it. An
4
+ implementation run takes the result from the stage QA owner only; final
5
+ verification needs a PASS from every verifier it dispatched.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from contextlib import contextmanager
10
+ from dataclasses import dataclass, field
11
+ from pathlib import Path
12
+ from typing import Any, Iterable, Iterator, Mapping
13
+
14
+ from .agent.invocation import AgentInvocationError, reserved_generation_reference
15
+ from .conformance import QaResult, execution_evidence_defect, qa_result_from_execution
16
+ from .execution_identity import ExecutionManifest, Invocation
17
+ from .execution_manifest import read_execution_manifest
18
+ from .json_boundary import JsonBoundaryError, load_owned_object
19
+ from .paths import RunRef
20
+ from .qa_commands import QA_VERIFIER_AUDIENCE_BY_TASK_TYPE
21
+ from .verification_conformance import conformance_stage
22
+ from .verification_dispatch import verification_generation_number
23
+ from .verification_evidence import (
24
+ VerificationExecutionRecord, conformance_check_owner_ref,
25
+ read_verification_execution_record,
26
+ )
27
+ from .verification_generation import (
28
+ VerificationGenerationRecord, read_verification_generation,
29
+ )
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class StageEvidence:
34
+ """`records` are the latest record files examined for this stage, including
35
+ the `rejections`: records that are no usable evidence, with the reason."""
36
+
37
+ result: QaResult | None
38
+ records: tuple[Path, ...]
39
+ rejections: Mapping[Path, str] = field(default_factory=dict)
40
+
41
+ def unusable_summary(self) -> str | None:
42
+ """Why a stage without a result has none, when its latest records were
43
+ rejected; None otherwise."""
44
+ if self.result is not None or not self.rejections:
45
+ return None
46
+ return "no usable execution record: " + "; ".join(
47
+ f"{path} ({reason})" for path, reason in self.rejections.items())
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class RunConformanceEvidence:
52
+ """`stages` are the conformance stages a bound verifier generation requires."""
53
+
54
+ stages: frozenset[int]
55
+ results: Mapping[str, StageEvidence]
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class _VerifierOutcome:
60
+ result: QaResult | None
61
+ record: Path | None = None
62
+ rejection: str | None = None
63
+
64
+
65
+ _NO_OUTCOME = _VerifierOutcome(None)
66
+
67
+
68
+ @dataclass(frozen=True)
69
+ class BoundInvocation:
70
+ """One verifier invocation and the generation its metadata binds."""
71
+
72
+ invocation: Invocation
73
+ generation_number: int
74
+ index: int
75
+ generation: VerificationGenerationRecord | None
76
+ generation_ref: dict[str, str]
77
+
78
+ def seals(self, stage: int) -> bool:
79
+ return (self.generation is not None
80
+ and stage in self.generation.get("conformanceStages", ()))
81
+
82
+
83
+ @dataclass(frozen=True)
84
+ class RunVerifiers:
85
+ """A QA-executing run's verifier invocations, newest first per role
86
+ execution, and each invocation's latest attempt."""
87
+
88
+ manifest: dict[str, Any]
89
+ ref: RunRef
90
+ verifiers: dict[str, list[BoundInvocation]]
91
+ latest_attempt: dict[str, int]
92
+
93
+
94
+ @dataclass(frozen=True)
95
+ class CheckRunRecord:
96
+ """The latest run of one check; `defect` says why it is no usable evidence
97
+ (None when it is)."""
98
+
99
+ check_run: int
100
+ path: Path
101
+ record: VerificationExecutionRecord | None
102
+ output: bytes | None
103
+ defect: str | None
104
+
105
+
106
+ @contextmanager
107
+ def evidence_read_errors() -> Iterator[None]:
108
+ """Raise an unreadable invocation or file as the ValueError evidence
109
+ collection reports."""
110
+ try:
111
+ yield
112
+ except (AgentInvocationError, OSError) as exc:
113
+ raise ValueError(str(exc)) from exc
114
+
115
+
116
+ def collect_conformance_evidence(
117
+ project: Path, manifest_path: Path, stage_keys: Iterable[str],
118
+ ) -> RunConformanceEvidence:
119
+ with evidence_read_errors():
120
+ return _collect(project.resolve(), manifest_path.resolve(), tuple(stage_keys))
121
+
122
+
123
+ def _collect(
124
+ project: Path, manifest_path: Path, stage_keys: tuple[str, ...],
125
+ ) -> RunConformanceEvidence:
126
+ run = load_run_verifiers(project, manifest_path)
127
+ owner = conformance_check_owner_ref(run.manifest)
128
+ counted = list(run.verifiers) if owner is None else [owner]
129
+ return RunConformanceEvidence(_required_stages(run.verifiers), {
130
+ key: _stage_evidence(run, counted, key) for key in stage_keys
131
+ })
132
+
133
+
134
+ def load_run_verifiers(project: Path, manifest_path: Path) -> RunVerifiers:
135
+ manifest = load_owned_object(manifest_path, artifact="run manifest")
136
+ ref = RunRef.from_manifest(manifest_path, manifest)
137
+ audience = QA_VERIFIER_AUDIENCE_BY_TASK_TYPE.get(manifest.get("taskType"))
138
+ if audience is None:
139
+ raise ValueError("verification evidence requires a QA-executing run")
140
+ execution = read_execution_manifest(manifest_path)
141
+ latest_attempt = _latest_attempts(execution)
142
+ return RunVerifiers(
143
+ manifest, ref,
144
+ _bound_verifiers(project, ref, manifest, execution, audience, latest_attempt),
145
+ latest_attempt,
146
+ )
147
+
148
+
149
+ def _stage_evidence(
150
+ run: RunVerifiers, counted: list[str], stage_key: str,
151
+ ) -> StageEvidence:
152
+ """A counted verifier with no invocation bound to the newest generation that
153
+ seals the stage leaves it without a result; an older generation's record
154
+ observed the work before the round that sealed the newer one."""
155
+ try:
156
+ stage = conformance_stage(stage_key)
157
+ except ValueError:
158
+ # expected-miss: a malformed key names no stage a generation can seal,
159
+ # so no record can exist for it.
160
+ return StageEvidence(None, ())
161
+ newest = max((binding.generation_number for bindings in run.verifiers.values()
162
+ for binding in bindings if binding.seals(stage)), default=None)
163
+ if newest is None:
164
+ return StageEvidence(None, ())
165
+ return _combine([
166
+ _verifier_result(run, role_execution_ref, newest, stage_key)
167
+ for role_execution_ref in counted
168
+ ])
169
+
170
+
171
+ def _bound_verifiers(
172
+ project: Path, ref: RunRef, manifest: Mapping[str, Any],
173
+ execution: ExecutionManifest, audience: str, latest_attempt: Mapping[str, int],
174
+ ) -> dict[str, list[BoundInvocation]]:
175
+ verifiers: dict[str, list[BoundInvocation]] = {}
176
+ for index, invocation in enumerate(execution.invocations):
177
+ if invocation.duty_id == audience:
178
+ verifiers.setdefault(invocation.role_execution_ref, []).append(_bind(
179
+ project, ref, manifest, invocation, index,
180
+ latest_attempt.get(invocation.invocation_ref, 1),
181
+ ))
182
+ for bindings in verifiers.values():
183
+ bindings.sort(key=lambda binding: (binding.generation_number, binding.index),
184
+ reverse=True)
185
+ return verifiers
186
+
187
+
188
+ def _latest_attempts(execution: ExecutionManifest) -> dict[str, int]:
189
+ latest: dict[str, int] = {}
190
+ for row in execution.attempts:
191
+ latest[row.invocation_ref] = max(row.attempt, latest.get(row.invocation_ref, 0))
192
+ return latest
193
+
194
+
195
+ def _required_stages(verifiers: Mapping[str, list[BoundInvocation]]) -> frozenset[int]:
196
+ return frozenset(
197
+ stage for bindings in verifiers.values() for binding in bindings
198
+ if binding.generation is not None
199
+ for stage in binding.generation.get("conformanceStages", ())
200
+ )
201
+
202
+
203
+ def _bind(
204
+ project: Path, ref: RunRef, manifest: Mapping[str, Any], invocation: Invocation,
205
+ index: int, attempt: int,
206
+ ) -> BoundInvocation:
207
+ """The generation the invocation's metadata binds, which must be the one its
208
+ dispatch kind seals and still have the bytes the metadata recorded."""
209
+ number = verification_generation_number(invocation.dispatch_kind)
210
+ path = ref.verification_generation(number)
211
+ relative = path.relative_to(project).as_posix()
212
+ reference = reserved_generation_reference(
213
+ project, manifest, invocation.invocation_ref, attempt,
214
+ )
215
+ if reference is None:
216
+ return BoundInvocation(invocation, number, index, None,
217
+ {"path": relative, "digest": ""})
218
+ if reference.path != relative:
219
+ raise ValueError(
220
+ f"invocation {invocation.invocation_ref} is bound to {reference.path}, "
221
+ f"not to {relative}, the generation its dispatch seals"
222
+ )
223
+ try:
224
+ generation = read_verification_generation(path, reference.digest)
225
+ except ValueError as exc:
226
+ raise ValueError(
227
+ f"generation {relative} of invocation {invocation.invocation_ref}: {exc}"
228
+ ) from exc
229
+ return BoundInvocation(invocation, number, index, generation, reference.to_payload())
230
+
231
+
232
+ def _verifier_result(
233
+ run: RunVerifiers, role_execution_ref: str, generation_number: int,
234
+ stage_key: str,
235
+ ) -> _VerifierOutcome:
236
+ bound = bound_attempt(run, role_execution_ref, generation_number)
237
+ if bound is None:
238
+ return _NO_OUTCOME
239
+ check = read_latest_check_run(run.ref, role_execution_ref, *bound,
240
+ f"conformance:{stage_key}")
241
+ if check is None:
242
+ return _NO_OUTCOME
243
+ if check.defect is not None or check.record is None or check.output is None:
244
+ return _VerifierOutcome(None, check.path, check.defect)
245
+ return _VerifierOutcome(qa_result_from_execution(check.record, check.output),
246
+ check.path)
247
+
248
+
249
+ def bound_attempt(
250
+ run: RunVerifiers, role_execution_ref: str, generation_number: int,
251
+ ) -> tuple[BoundInvocation, int] | None:
252
+ """The verifier's invocation bound to the generation, with its latest
253
+ attempt; None when it has no such invocation or attempt."""
254
+ chosen = next((binding for binding in run.verifiers.get(role_execution_ref, [])
255
+ if binding.generation is not None
256
+ and binding.generation_number == generation_number), None)
257
+ if chosen is None:
258
+ return None
259
+ attempt = run.latest_attempt.get(chosen.invocation.invocation_ref)
260
+ return None if attempt is None else (chosen, attempt)
261
+
262
+
263
+ def read_latest_check_run(
264
+ ref: RunRef, role_execution_ref: str, binding: BoundInvocation, attempt: int,
265
+ check_ref: str,
266
+ ) -> CheckRunRecord | None:
267
+ """The latest run of one check under an attempt of a bound invocation; None
268
+ when the attempt never ran the check."""
269
+ invocation_ref = binding.invocation.invocation_ref
270
+ check_run = ref.latest_verification_check_run(invocation_ref, attempt, check_ref)
271
+ if check_run is None:
272
+ return None
273
+ run_dir = ref.verification_execution_dir(invocation_ref, attempt, check_ref, check_run)
274
+ record, output, defect = _read_bound_record(run_dir, {
275
+ "invocationRef": invocation_ref, "roleExecutionRef": role_execution_ref,
276
+ "attempt": attempt, "checkRef": check_ref, "checkRun": check_run,
277
+ "verificationGeneration": binding.generation_ref,
278
+ })
279
+ return CheckRunRecord(check_run, run_dir / "record.json", record, output, defect)
280
+
281
+
282
+ def _read_bound_record(
283
+ run_dir: Path, expected: Mapping[str, object],
284
+ ) -> tuple[VerificationExecutionRecord | None, bytes | None, str | None]:
285
+ """One check run's record, its saved stdout, and why the run is no usable
286
+ evidence (None when it is); `expected` are the record fields its location
287
+ and binding determine."""
288
+ try:
289
+ record = read_verification_execution_record(run_dir / "record.json")
290
+ except (JsonBoundaryError, OSError) as exc:
291
+ return None, None, f"record is unreadable ({exc})"
292
+ if any(record[name] != value for name, value in expected.items()):
293
+ return record, None, ("record identity, attempt, check run or generation "
294
+ "differs from its location")
295
+ try:
296
+ output = (run_dir / "stdout.log").read_bytes()
297
+ except OSError as exc:
298
+ return record, None, f"saved stdout is unreadable ({exc})"
299
+ return record, output, execution_evidence_defect(record, output)
300
+
301
+
302
+ def _combine(outcomes: list[_VerifierOutcome]) -> StageEvidence:
303
+ records = tuple(outcome.record for outcome in outcomes if outcome.record is not None)
304
+ rejections = {outcome.record: outcome.rejection for outcome in outcomes
305
+ if outcome.record is not None and outcome.rejection is not None}
306
+ values = [outcome.result for outcome in outcomes]
307
+ if not values:
308
+ return StageEvidence(None, records, rejections)
309
+ for overall in ("FAIL", "MISSING"):
310
+ found = next((result for result in values
311
+ if result is not None and result.overall == overall), None)
312
+ if found is not None:
313
+ return StageEvidence(found, records, rejections)
314
+ if any(result is None for result in values):
315
+ return StageEvidence(None, records, rejections)
316
+ return StageEvidence(values[0], records, rejections)
@@ -13,7 +13,7 @@ import re
13
13
  from pathlib import Path
14
14
  from typing import Mapping, Sequence
15
15
 
16
- from .execution_identity import ExecutionManifest
16
+ from .execution_identity import Attempt, ExecutionManifest
17
17
  from .file_size_cap import FILE_LINE_LIMIT, FileSizeViolation
18
18
  from .json_boundary import load_owned_object
19
19
 
@@ -72,6 +72,23 @@ def reverify_invocation_in_scope(invocation_ref: str, scope: str | None, round_n
72
72
  return f"-{scope}-reverify-r{round_number}-" in invocation_ref
73
73
 
74
74
 
75
+ def completed_round_attempts(
76
+ manifest: ExecutionManifest, round_number: int | None, role: str,
77
+ ) -> list[Attempt]:
78
+ """Finished `ok` attempts of `role` in correction round N (None: initial)."""
79
+ roles = {row.role_execution_ref: row.role for row in manifest.role_executions}
80
+ invocations = {
81
+ row.invocation_ref for row in manifest.invocations
82
+ if correction_round(row.dispatch_kind) == round_number
83
+ and roles.get(row.role_execution_ref) == role
84
+ }
85
+ return [
86
+ row for row in manifest.attempts
87
+ if row.invocation_ref in invocations
88
+ and row.finished_at is not None and row.status == "ok"
89
+ ]
90
+
91
+
75
92
  def validate_correction_dispatch(
76
93
  manifest: ExecutionManifest, jobs: Sequence[object],
77
94
  ) -> None:
@@ -82,19 +99,8 @@ def validate_correction_dispatch(
82
99
  verifier reads a tree the fix has not reached, as the executor/verifier batch split
83
100
  already guards for the initial round.
84
101
  """
85
- roles = {row.role_execution_ref: row.role for row in manifest.role_executions}
86
- finished_ok = {
87
- row.invocation_ref for row in manifest.attempts
88
- if row.finished_at is not None and row.status == "ok"
89
- }
90
-
91
102
  def completed(round_number: int, role: str) -> bool:
92
- return any(
93
- correction_round(row.dispatch_kind) == round_number
94
- and roles.get(row.role_execution_ref) == role
95
- and row.invocation_ref in finished_ok
96
- for row in manifest.invocations
97
- )
103
+ return bool(completed_round_attempts(manifest, round_number, role))
98
104
 
99
105
  for job in jobs:
100
106
  round_number = correction_round(getattr(job, "dispatch_kind", ""))
@@ -2506,7 +2506,7 @@ def _record_wrapper_failure(
2506
2506
  and that Lead does not need to re-record it. Nothing did: no code path
2507
2507
  anywhere called the error-log writer, so every wrapper failure vanished, and
2508
2508
  with it the `instruction-set/prior-run-errors.md` digest the next run reads
2509
- and the `/okstra-inspect errors` report. The dispatcher is the only component
2509
+ and the error report. The dispatcher is the only component
2510
2510
  that holds the exit code, so it is the one that writes.
2511
2511
 
2512
2512
  Never raises. Logging is bookkeeping around a dispatch that has already
@@ -133,6 +133,7 @@ WORKER_STATUSES = frozenset(
133
133
  NON_TERMINAL_WORKER_STATUSES = frozenset({"in-progress"})
134
134
  TERMINAL_WORKER_STATUSES = WORKER_STATUSES - NON_TERMINAL_WORKER_STATUSES
135
135
  REASON_REQUIRED_STATUSES = frozenset({"timeout", "error", "not-run"})
136
+ UNSUCCESSFUL_WORKER_STATUSES = TERMINAL_WORKER_STATUSES - {"completed"}
136
137
 
137
138
 
138
139
  def generate_claude_session_id() -> str:
@@ -33,6 +33,9 @@ class VerificationSourceSnapshot:
33
33
  input_paths: frozenset[str]
34
34
  protected_files: Mapping[str, str]
35
35
  generated_files: Mapping[str, str]
36
+ # Ignored roots that held output at this capture. Unlike `generated_roots`
37
+ # they may differ between captures, so comparisons never require equality.
38
+ ignored_roots: frozenset[str] = frozenset()
36
39
 
37
40
 
38
41
  @dataclass(frozen=True)
@@ -562,9 +565,13 @@ def capture_verification_source(
562
565
  f"verification source path contains a symlink ancestor: {relative}"
563
566
  )
564
567
  files[relative] = _path_digest(path)
568
+ # A Git-ignored path is output the repository declares is not source, such
569
+ # as a build directory or a test cache; a verification command may rewrite
570
+ # it. Tracked files and explicit inputs stay protected even when ignored.
571
+ ignored = _ignored_paths(root)
565
572
  generated_files = {
566
573
  relative: digest for relative, digest in files.items()
567
- if is_generated_verification_path(relative, generated, protected)
574
+ if is_generated_verification_path(relative, generated | ignored, protected)
568
575
  }
569
576
  protected_files = {
570
577
  relative: digest for relative, digest in files.items()
@@ -574,6 +581,11 @@ def capture_verification_source(
574
581
  root=root, tracked_paths=tracked, generated_roots=generated,
575
582
  input_paths=inputs, protected_files=MappingProxyType(protected_files),
576
583
  generated_files=MappingProxyType(generated_files),
584
+ ignored_roots=frozenset(
585
+ ignored_root for ignored_root in ignored
586
+ if any(_excluded(Path(relative), frozenset({ignored_root}))
587
+ for relative in generated_files)
588
+ ),
577
589
  )
578
590
 
579
591
 
@@ -0,0 +1,21 @@
1
+ """Input documents that prepare writes into a run's brief slot."""
2
+ from __future__ import annotations
3
+
4
+ from pathlib import Path
5
+
6
+ from okstra_project.state import parse_task_key
7
+
8
+ from .phases.discussion.store import DiscussionStore
9
+ from .phases.release_handoff.entry import handoff_input_path
10
+
11
+
12
+ def names_generated_input_document(project_root: Path, task_key: str, brief: str) -> bool:
13
+ """True when ``brief`` is a release-handoff or discussion input document of the task."""
14
+ if not brief:
15
+ return False
16
+ _, task_group, task_id = parse_task_key(task_key)
17
+ generated = {
18
+ handoff_input_path(project_root, task_group, task_id),
19
+ DiscussionStore(project_root, task_key).input_path,
20
+ }
21
+ return (project_root / brief).resolve() in {path.resolve() for path in generated}
@@ -1,16 +1,9 @@
1
- """runId 빌드/파싱/세그먼트 escape, 세션명, container compose 라벨."""
1
+ """Run identifier construction, parsing, and segment escaping."""
2
2
  from __future__ import annotations
3
3
 
4
- import hashlib as _hashlib
5
4
  import re as _re
6
5
  from typing import Dict
7
6
 
8
- # leaf 규칙 모듈에서 바로 가져온다. state 를 거치면 okstra_ctl 패키지 __init__ 이
9
- # 상태 접근자 전체를 끌어와 okstra_project ↔ okstra_ctl 순환이 된다.
10
- from okstra_project.slug import slugify as _slugify
11
-
12
- # docker compose project name 길이 상한. compose 는 [a-z0-9][a-z0-9_-]* 만 허용한다.
13
- CONTAINER_PROJECT_NAME_MAX = 60
14
7
 
15
8
 
16
9
  # runId 형식: "<project-id>/<task-group>/<task-id>/<task-type>/r<run-seq>"
@@ -78,36 +71,3 @@ def _escape_segment_for_join(segment: str) -> str:
78
71
  def slugify_task_segment(value: str) -> str:
79
72
  """Match okstra.sh slugify_value for task directory segments."""
80
73
  return _re.sub(r"[^a-z0-9]+", "-", value.lower()).strip("-")
81
-
82
-
83
- def build_container_run_trace(project_id: str, group: str, task_id: str) -> str:
84
- """container 배포의 `okstra.run-trace` 라벨값을 합친다 → 'okstra-container-<slug>'.
85
-
86
- 세그먼트는 task_dir 가 쓰는 slugify_task_segment 와 동일 규칙으로 정규화해
87
- 라벨 slug 가 프로젝트 디스크 경로 slug 와 분기하지 않게 한다.
88
- """
89
- seg = slugify_task_segment
90
- return f"okstra-container-{seg(project_id)}-{seg(group)}-{seg(task_id)}"
91
-
92
-
93
- def compose_project_name(project_id: str, task_group: str, task_id: str) -> str:
94
- """docker compose project name 을 합친다(순수 계산).
95
-
96
- 세그먼트 정규화는 ``paths.task_dir`` 가 쓰는 slug 함수(okstra_project.state.
97
- slugify)와 동일 함수를 써서 라벨(이 이름이 SSOT)↔디스크 경로의 slug 가
98
- 분기하지 않게 한다. 상한(``CONTAINER_PROJECT_NAME_MAX``) 초과 시 읽기 좋은
99
- 본문을 앞에서 자르고 끝에 전체 이름의 해시 8자리를 붙인다 — 단순 prefix-cut 은
100
- task_group 만 다른 두 task-key 를 같은 이름으로 collapse 시켜(라벨 SSOT 충돌로
101
- 한 task 의 down 이 형제 task 컨테이너까지 회수) 위험하므로, 해시로 distinct 를
102
- 보장하고 상한도 항상 만족시킨다."""
103
- def seg(v: str) -> str:
104
- return _slugify(v) or "x" # 빈 슬러그 방지(compose 는 [a-z0-9] 시작 요구)
105
-
106
- proj, grp, task = seg(project_id), seg(task_group), seg(task_id)
107
- name = f"okstra-{proj}-{grp}-{task}"
108
- if len(name) <= CONTAINER_PROJECT_NAME_MAX:
109
- return name
110
- digest = _hashlib.sha1(name.encode("utf-8")).hexdigest()[:8]
111
- body_budget = CONTAINER_PROJECT_NAME_MAX - len("okstra-") - 1 - len(digest)
112
- body = f"{proj}-{grp}-{task}"[:body_budget].rstrip("-")
113
- return f"okstra-{body}-{digest}"
@@ -17,9 +17,10 @@ from .plan_item_evidence import dependency_scopes, reusable_item_ids
17
17
  from .plan_items import (
18
18
  PlanItemContractError,
19
19
  content_hash,
20
- dispatch_item_ids,
21
20
  extract_plan_items,
22
21
  planning_stage_ledger,
22
+ queue_candidate_ids,
23
+ verified_content_hashes,
23
24
  )
24
25
 
25
26
 
@@ -387,7 +388,8 @@ def _carry_unchanged_checklists(
387
388
 
388
389
  def _recompute_dispatch_queue(
389
390
  narrative: Mapping[str, Any],
390
- stage_ledger: Mapping[str, Any] | None = None,
391
+ stage_ledger: Mapping[str, Any] | None,
392
+ rows: list[dict],
391
393
  ) -> list[str]:
392
394
  """이월 뒤 남은 디스패치 큐.
393
395
 
@@ -408,7 +410,8 @@ def _recompute_dispatch_queue(
408
410
  for stage, status in (stage_ledger or {}).items()
409
411
  },
410
412
  )
411
- return dispatch_item_ids(extracted, ledger)
413
+ candidates = queue_candidate_ids(extracted, ledger, verified_content_hashes(rows))
414
+ return [item["id"] for item in extracted if item["id"] in candidates]
412
415
 
413
416
 
414
417
  def _writer_stage_rows(data: Mapping[str, Any], *, snapshot: str) -> dict[int, dict]:
@@ -483,7 +486,7 @@ def merge_v3_plan_state(
483
486
  state_items[item_id] for item_id in sorted(state_items)
484
487
  ]
485
488
  queue = _recompute_dispatch_queue(
486
- narrative, pbv.get("stageLedger"),
489
+ narrative, pbv.get("stageLedger"), pbv["planItems"],
487
490
  )
488
491
  if queue:
489
492
  pbv["dispatchQueue"] = queue