okstra 0.228.2 → 0.230.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 (124) 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 +179 -13
  9. package/docs/architecture.md +13 -14
  10. package/docs/contributor-change-matrix.md +5 -5
  11. package/docs/project-structure-overview.md +16 -21
  12. package/package.json +1 -2
  13. package/runtime/BUILD.json +2 -2
  14. package/runtime/bin/lib/okstra/interactive.sh +2 -1
  15. package/runtime/bin/okstra-provider-exec.py +53 -4
  16. package/runtime/prompts/duties/code-reviewer.json +5 -2
  17. package/runtime/prompts/launch.template.md +5 -5
  18. package/runtime/prompts/lead/convergence.md +4 -4
  19. package/runtime/prompts/lead/okstra-lead-contract.md +14 -13
  20. package/runtime/prompts/lead/phase-routing.md +1 -1
  21. package/runtime/prompts/lead/report-writer.md +3 -3
  22. package/runtime/prompts/lead/team-contract.md +3 -3
  23. package/runtime/python/okstra_ctl/agent/invocation.py +142 -5
  24. package/runtime/python/okstra_ctl/agent/prompt_cli/materialize.py +31 -1
  25. package/runtime/python/okstra_ctl/cmux.py +4 -2
  26. package/runtime/python/okstra_ctl/code_review_census.py +194 -0
  27. package/runtime/python/okstra_ctl/code_review_coverage.py +18 -5
  28. package/runtime/python/okstra_ctl/code_review_scope.py +11 -7
  29. package/runtime/python/okstra_ctl/code_review_target.py +79 -25
  30. package/runtime/python/okstra_ctl/conformance.py +61 -0
  31. package/runtime/python/okstra_ctl/conformance_evidence.py +235 -0
  32. package/runtime/python/okstra_ctl/correction_round.py +19 -13
  33. package/runtime/python/okstra_ctl/dispatch_core.py +1 -1
  34. package/runtime/python/okstra_ctl/dispatch_state.py +1 -0
  35. package/runtime/python/okstra_ctl/execution_mutation_audit.py +100 -2
  36. package/runtime/python/okstra_ctl/generated_input.py +21 -0
  37. package/runtime/python/okstra_ctl/ids.py +1 -41
  38. package/runtime/python/okstra_ctl/initial_prompt_materialization.py +30 -0
  39. package/runtime/python/okstra_ctl/interactive_cli.py +5 -0
  40. package/runtime/python/okstra_ctl/locks.py +28 -1
  41. package/runtime/python/okstra_ctl/model_io/renderers.py +17 -1
  42. package/runtime/python/okstra_ctl/paths.py +84 -31
  43. package/runtime/python/okstra_ctl/phases/catalog.py +3 -0
  44. package/runtime/python/okstra_ctl/phases/change_impact_analysis/spec.md +2 -2
  45. package/runtime/python/okstra_ctl/phases/discussion/spec.md +63 -63
  46. package/runtime/python/okstra_ctl/phases/discussion/wizard.py +2 -11
  47. package/runtime/python/okstra_ctl/phases/error_analysis/report_assets/error-analysis-input.template.md +1 -1
  48. package/runtime/python/okstra_ctl/phases/error_analysis/spec.md +2 -2
  49. package/runtime/python/okstra_ctl/phases/feature_analysis/spec.md +1 -1
  50. package/runtime/python/okstra_ctl/phases/final_verification/profile.md +4 -4
  51. package/runtime/python/okstra_ctl/phases/final_verification/report_assets/final-verification-input.template.md +1 -1
  52. package/runtime/python/okstra_ctl/phases/final_verification/spec.md +4 -4
  53. package/runtime/python/okstra_ctl/phases/implementation/host-rules.md +1 -1
  54. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-deliverable.md +2 -2
  55. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-executor.md +1 -1
  56. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-verifier.md +4 -4
  57. package/runtime/python/okstra_ctl/phases/implementation/report_assets/implementation-input.template.md +1 -1
  58. package/runtime/python/okstra_ctl/phases/implementation/spec.md +4 -4
  59. package/runtime/python/okstra_ctl/phases/implementation_option_selection/spec.md +2 -2
  60. package/runtime/python/okstra_ctl/phases/implementation_planning/instructions/plan-body-verification.md +11 -11
  61. package/runtime/python/okstra_ctl/phases/implementation_planning/plan_body.py +14 -0
  62. package/runtime/python/okstra_ctl/phases/implementation_planning/profile.md +4 -4
  63. package/runtime/python/okstra_ctl/phases/implementation_planning/report_assets/implementation-planning-input.template.md +1 -1
  64. package/runtime/python/okstra_ctl/phases/implementation_planning/spec.md +1 -1
  65. package/runtime/python/okstra_ctl/phases/project_analysis/spec.md +2 -2
  66. package/runtime/python/okstra_ctl/phases/release_handoff/entry.py +7 -3
  67. package/runtime/python/okstra_ctl/phases/release_handoff/report_assets/release-handoff-input.template.md +1 -1
  68. package/runtime/python/okstra_ctl/phases/release_handoff/spec.md +4 -4
  69. package/runtime/python/okstra_ctl/phases/technical_verification/spec.md +1 -1
  70. package/runtime/python/okstra_ctl/process_group.py +26 -3
  71. package/runtime/python/okstra_ctl/qa_commands.py +7 -2
  72. package/runtime/python/okstra_ctl/qa_procedures.py +60 -17
  73. package/runtime/python/okstra_ctl/recap.py +1 -2
  74. package/runtime/python/okstra_ctl/render.py +10 -2
  75. package/runtime/python/okstra_ctl/report_finalize.py +3 -3
  76. package/runtime/python/okstra_ctl/report_synthesis_packet.py +5 -0
  77. package/runtime/python/okstra_ctl/run.py +24 -20
  78. package/runtime/python/okstra_ctl/stage_command_commits.py +143 -0
  79. package/runtime/python/okstra_ctl/verification_capture.py +291 -0
  80. package/runtime/python/okstra_ctl/verification_conformance.py +182 -0
  81. package/runtime/python/okstra_ctl/verification_dispatch.py +130 -0
  82. package/runtime/python/okstra_ctl/verification_evidence.py +652 -0
  83. package/runtime/python/okstra_ctl/verification_generation.py +248 -0
  84. package/runtime/python/okstra_ctl/verification_input_ref.py +9 -0
  85. package/runtime/python/okstra_ctl/verification_input_types.py +23 -2
  86. package/runtime/python/okstra_ctl/verification_inputs.py +161 -23
  87. package/runtime/python/okstra_ctl/verification_invocation.py +139 -0
  88. package/runtime/python/okstra_ctl/verification_target.py +20 -5
  89. package/runtime/python/okstra_ctl/wizard/registry.py +2 -1
  90. package/runtime/python/okstra_ctl/wizard/render.py +2 -1
  91. package/runtime/python/okstra_ctl/wizard/sources.py +14 -3
  92. package/runtime/python/okstra_ctl/wizard/steps_identity.py +2 -1
  93. package/runtime/python/okstra_ctl/worker_runner.py +1 -1
  94. package/runtime/python/okstra_ctl/worktree_lock_cli.py +70 -17
  95. package/runtime/python/okstra_ctl/worktree_registry.py +4 -0
  96. package/runtime/skills/okstra-code-review/SKILL.md +84 -48
  97. package/runtime/skills/okstra-code-review/references/census-rules.md +10 -4
  98. package/runtime/skills/okstra-code-review/references/review-calibration.md +7 -4
  99. package/runtime/skills/okstra-explain-flow/SKILL.md +1 -1
  100. package/runtime/skills/okstra-run/SKILL.md +6 -6
  101. package/runtime/skills/okstra-schedule-gen/SKILL.md +3 -3
  102. package/runtime/skills/okstra-setup/SKILL.md +2 -3
  103. package/runtime/validators/validate-run.py +118 -52
  104. package/docs/cli.md +0 -1060
  105. package/docs/container.md +0 -100
  106. package/docs/follow-ups/2026-07-10-final-report-option-3.md +0 -51
  107. package/docs/performance-improvement-plan-v2.md +0 -369
  108. package/runtime/python/okstra_ctl/container.py +0 -702
  109. package/runtime/python/okstra_ctl/rollup.py +0 -241
  110. package/runtime/python/okstra_ctl/usage_report.py +0 -362
  111. package/runtime/skills/okstra-container-build/SKILL.md +0 -139
  112. package/runtime/skills/okstra-inspect/SKILL.md +0 -100
  113. package/runtime/skills/okstra-inspect/facets/cost.md +0 -84
  114. package/runtime/skills/okstra-inspect/facets/error-zip.md +0 -41
  115. package/runtime/skills/okstra-inspect/facets/errors.md +0 -69
  116. package/runtime/skills/okstra-inspect/facets/history.md +0 -86
  117. package/runtime/skills/okstra-inspect/facets/logs.md +0 -89
  118. package/runtime/skills/okstra-inspect/facets/recap.md +0 -167
  119. package/runtime/skills/okstra-inspect/facets/report.md +0 -57
  120. package/runtime/skills/okstra-inspect/facets/run-audit.md +0 -34
  121. package/runtime/skills/okstra-inspect/facets/status.md +0 -163
  122. package/runtime/skills/okstra-inspect/facets/time.md +0 -57
  123. package/runtime/skills/okstra-rollup/SKILL.md +0 -75
  124. package/runtime/skills/okstra-usage/SKILL.md +0 -71
@@ -0,0 +1,235 @@
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 dataclasses import dataclass, field
10
+ from pathlib import Path
11
+ from typing import Iterable, Mapping
12
+
13
+ from .agent.invocation import AgentInvocationError
14
+ from .conformance import QaResult, execution_evidence_defect, qa_result_from_execution
15
+ from .execution_identity import ExecutionManifest, Invocation
16
+ from .execution_manifest import read_execution_manifest
17
+ from .json_boundary import JsonBoundaryError, load_owned_object
18
+ from .paths import RunRef
19
+ from .qa_commands import QA_VERIFIER_AUDIENCE_BY_TASK_TYPE
20
+ from .qa_procedures import content_digest
21
+ from .verification_conformance import conformance_stage
22
+ from .verification_dispatch import verification_generation_number
23
+ from .verification_evidence import (
24
+ conformance_check_owner_ref, read_verification_execution_record,
25
+ )
26
+ from .verification_generation import (
27
+ VerificationGenerationRecord, read_verification_generation,
28
+ )
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class StageEvidence:
33
+ """`records` are the latest record files examined for this stage, including
34
+ the `rejections`: records that are no usable evidence, with the reason."""
35
+
36
+ result: QaResult | None
37
+ records: tuple[Path, ...]
38
+ rejections: Mapping[Path, str] = field(default_factory=dict)
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class RunConformanceEvidence:
43
+ """`stages` are the conformance stages a bound verifier generation requires."""
44
+
45
+ stages: frozenset[int]
46
+ results: Mapping[str, StageEvidence]
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class _VerifierOutcome:
51
+ result: QaResult | None
52
+ record: Path | None = None
53
+ rejection: str | None = None
54
+
55
+
56
+ _NO_OUTCOME = _VerifierOutcome(None)
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class _BoundInvocation:
61
+ """One verifier invocation and the generation its dispatch kind seals."""
62
+
63
+ invocation: Invocation
64
+ generation_number: int
65
+ index: int
66
+ generation: VerificationGenerationRecord | None
67
+ generation_ref: dict[str, str]
68
+
69
+ def seals(self, stage: int) -> bool:
70
+ return (self.generation is not None
71
+ and stage in self.generation.get("conformanceStages", ()))
72
+
73
+
74
+ def collect_conformance_evidence(
75
+ project: Path, manifest_path: Path, stage_keys: Iterable[str],
76
+ ) -> RunConformanceEvidence:
77
+ try:
78
+ return _collect(project.resolve(), manifest_path.resolve(), tuple(stage_keys))
79
+ except (AgentInvocationError, OSError) as exc:
80
+ raise ValueError(str(exc)) from exc
81
+
82
+
83
+ def _collect(
84
+ project: Path, manifest_path: Path, stage_keys: tuple[str, ...],
85
+ ) -> RunConformanceEvidence:
86
+ manifest = load_owned_object(manifest_path, artifact="run manifest")
87
+ ref = RunRef.from_manifest(manifest_path, manifest)
88
+ audience = QA_VERIFIER_AUDIENCE_BY_TASK_TYPE.get(manifest.get("taskType"))
89
+ if audience is None:
90
+ raise ValueError("verification evidence requires a QA-executing run")
91
+ execution = read_execution_manifest(manifest_path)
92
+ verifiers = _bound_verifiers(project, ref, execution, audience)
93
+ owner = conformance_check_owner_ref(manifest)
94
+ counted = list(verifiers) if owner is None else [owner]
95
+ latest_attempt = _latest_attempts(execution)
96
+ return RunConformanceEvidence(_required_stages(verifiers), {
97
+ key: _stage_evidence(ref, verifiers, counted, key, latest_attempt)
98
+ for key in stage_keys
99
+ })
100
+
101
+
102
+ def _stage_evidence(
103
+ ref: RunRef, verifiers: Mapping[str, list[_BoundInvocation]],
104
+ counted: list[str], stage_key: str, latest_attempt: Mapping[str, int],
105
+ ) -> StageEvidence:
106
+ """A counted verifier with no invocation bound to the newest generation that
107
+ seals the stage leaves it without a result; an older generation's record
108
+ observed the work before the round that sealed the newer one."""
109
+ try:
110
+ stage = conformance_stage(stage_key)
111
+ except ValueError:
112
+ # expected-miss: a malformed key names no stage a generation can seal,
113
+ # so no record can exist for it.
114
+ return StageEvidence(None, ())
115
+ newest = max((binding.generation_number for bindings in verifiers.values()
116
+ for binding in bindings if binding.seals(stage)), default=None)
117
+ if newest is None:
118
+ return StageEvidence(None, ())
119
+ return _combine([
120
+ _verifier_result(ref, role_execution_ref, verifiers.get(role_execution_ref, []),
121
+ newest, stage_key, latest_attempt)
122
+ for role_execution_ref in counted
123
+ ])
124
+
125
+
126
+ def _bound_verifiers(
127
+ project: Path, ref: RunRef, execution: ExecutionManifest, audience: str,
128
+ ) -> dict[str, list[_BoundInvocation]]:
129
+ """Each verifier's invocations, newest first."""
130
+ verifiers: dict[str, list[_BoundInvocation]] = {}
131
+ for index, invocation in enumerate(execution.invocations):
132
+ if invocation.duty_id == audience:
133
+ verifiers.setdefault(invocation.role_execution_ref, []).append(
134
+ _bind(project, ref, invocation, index),
135
+ )
136
+ for bindings in verifiers.values():
137
+ bindings.sort(key=lambda binding: (binding.generation_number, binding.index),
138
+ reverse=True)
139
+ return verifiers
140
+
141
+
142
+ def _latest_attempts(execution: ExecutionManifest) -> dict[str, int]:
143
+ latest: dict[str, int] = {}
144
+ for row in execution.attempts:
145
+ latest[row.invocation_ref] = max(row.attempt, latest.get(row.invocation_ref, 0))
146
+ return latest
147
+
148
+
149
+ def _required_stages(verifiers: Mapping[str, list[_BoundInvocation]]) -> frozenset[int]:
150
+ return frozenset(
151
+ stage for bindings in verifiers.values() for binding in bindings
152
+ if binding.generation is not None
153
+ for stage in binding.generation.get("conformanceStages", ())
154
+ )
155
+
156
+
157
+ def _bind(
158
+ project: Path, ref: RunRef, invocation: Invocation, index: int,
159
+ ) -> _BoundInvocation:
160
+ number = verification_generation_number(invocation.dispatch_kind)
161
+ path = ref.verification_generation(number)
162
+ relative = path.relative_to(project).as_posix()
163
+ if not path.is_file():
164
+ return _BoundInvocation(invocation, number, index, None,
165
+ {"path": relative, "digest": ""})
166
+ digest = content_digest(path.read_bytes())
167
+ return _BoundInvocation(invocation, number, index,
168
+ read_verification_generation(path, digest),
169
+ {"path": relative, "digest": digest})
170
+
171
+
172
+ def _verifier_result(
173
+ ref: RunRef, role_execution_ref: str, bindings: list[_BoundInvocation],
174
+ generation_number: int, stage_key: str, latest_attempt: Mapping[str, int],
175
+ ) -> _VerifierOutcome:
176
+ chosen = next((binding for binding in bindings if binding.generation is not None
177
+ and binding.generation_number == generation_number), None)
178
+ if chosen is None:
179
+ return _NO_OUTCOME
180
+ invocation_ref = chosen.invocation.invocation_ref
181
+ attempt = latest_attempt.get(invocation_ref)
182
+ if attempt is None:
183
+ return _NO_OUTCOME
184
+ check_ref = f"conformance:{stage_key}"
185
+ check_run = ref.latest_verification_check_run(invocation_ref, attempt, check_ref)
186
+ if check_run is None:
187
+ return _NO_OUTCOME
188
+ run_dir = ref.verification_execution_dir(
189
+ invocation_ref, attempt, check_ref, check_run,
190
+ )
191
+ expected = {
192
+ "invocationRef": invocation_ref, "roleExecutionRef": role_execution_ref,
193
+ "attempt": attempt, "checkRef": check_ref, "checkRun": check_run,
194
+ "verificationGeneration": chosen.generation_ref,
195
+ }
196
+ record_path = run_dir / "record.json"
197
+ result, rejection = _recorded_result(run_dir, expected)
198
+ return _VerifierOutcome(result, record_path, rejection)
199
+
200
+
201
+ def _recorded_result(
202
+ run_dir: Path, expected: Mapping[str, object],
203
+ ) -> tuple[QaResult | None, str | None]:
204
+ try:
205
+ record = read_verification_execution_record(run_dir / "record.json")
206
+ except (JsonBoundaryError, OSError) as exc:
207
+ return None, f"record is unreadable ({exc})"
208
+ if any(record[name] != value for name, value in expected.items()):
209
+ return None, ("record identity, attempt, check run or generation differs "
210
+ "from its location")
211
+ try:
212
+ output = (run_dir / "stdout.log").read_bytes()
213
+ except OSError as exc:
214
+ return None, f"saved stdout is unreadable ({exc})"
215
+ defect = execution_evidence_defect(record, output)
216
+ if defect is not None:
217
+ return None, defect
218
+ return qa_result_from_execution(record, output), None
219
+
220
+
221
+ def _combine(outcomes: list[_VerifierOutcome]) -> StageEvidence:
222
+ records = tuple(outcome.record for outcome in outcomes if outcome.record is not None)
223
+ rejections = {outcome.record: outcome.rejection for outcome in outcomes
224
+ if outcome.record is not None and outcome.rejection is not None}
225
+ values = [outcome.result for outcome in outcomes]
226
+ if not values:
227
+ return StageEvidence(None, records, rejections)
228
+ for overall in ("FAIL", "MISSING"):
229
+ found = next((result for result in values
230
+ if result is not None and result.overall == overall), None)
231
+ if found is not None:
232
+ return StageEvidence(found, records, rejections)
233
+ if any(result is None for result in values):
234
+ return StageEvidence(None, records, rejections)
235
+ 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:
@@ -8,8 +8,10 @@ import subprocess
8
8
  from collections.abc import Mapping, Sequence
9
9
  from dataclasses import dataclass
10
10
  from pathlib import Path
11
+ from types import MappingProxyType
11
12
  from typing import Any
12
13
 
14
+ from .qa_procedures import existing_qa_file, safe_qa_path
13
15
  from .worktree.cleanliness import nested_worktree_excludes
14
16
  from .write_policy import WritePolicy
15
17
 
@@ -23,6 +25,24 @@ def assert_compatible_batch(policies: Sequence[WritePolicy]) -> None:
23
25
  _validate_batch(tuple(policies))
24
26
 
25
27
 
28
+ @dataclass(frozen=True)
29
+ class VerificationSourceSnapshot:
30
+ root: Path
31
+ tracked_paths: frozenset[str]
32
+ generated_roots: frozenset[str]
33
+ input_paths: frozenset[str]
34
+ protected_files: Mapping[str, str]
35
+ generated_files: Mapping[str, str]
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class VerificationSourceChanges:
40
+ protected_changes: tuple[str, ...]
41
+ generated_changes: tuple[str, ...]
42
+ unclassified_paths: tuple[str, ...]
43
+ tracked_paths_changed: bool
44
+
45
+
26
46
  @dataclass(frozen=True)
27
47
  class MutationSnapshot:
28
48
  root: Path
@@ -503,6 +523,83 @@ def source_content_snapshot(root: Path, excluded: frozenset[str] = frozenset())
503
523
  return _content_snapshot(root, excluded | _non_source_paths(root))
504
524
 
505
525
 
526
+ def _verification_paths(root: Path, paths: frozenset[str]) -> frozenset[str]:
527
+ return frozenset(
528
+ safe_qa_path(root, relative).relative_to(root).as_posix()
529
+ for relative in paths
530
+ )
531
+
532
+
533
+ def is_generated_verification_path(
534
+ relative: str, generated_roots: frozenset[str], protected_roots: frozenset[str],
535
+ ) -> bool:
536
+ return (_excluded(Path(relative), generated_roots)
537
+ and not _excluded(Path(relative), protected_roots))
538
+
539
+
540
+ def capture_verification_source(
541
+ root: Path, *, generated_roots: frozenset[str], input_paths: frozenset[str],
542
+ ) -> VerificationSourceSnapshot:
543
+ root = root.resolve()
544
+ tracked = _tracked_paths(root)
545
+ if tracked is None:
546
+ raise ValueError("verification source tracked paths are unavailable")
547
+ generated = _verification_paths(root, generated_roots)
548
+ inputs = frozenset(
549
+ existing_qa_file(root, relative).relative_to(root).as_posix()
550
+ for relative in input_paths
551
+ )
552
+ nested = _nested_worktree_paths(root)
553
+ files = _content_snapshot(root, nested | {_OKSTRA_ARTIFACT_SUBTREE})
554
+ protected = frozenset(
555
+ relative for relative in tracked if not _excluded(Path(relative), nested)
556
+ ) | inputs
557
+ for relative in protected - files.keys():
558
+ path = root / relative
559
+ if path.is_file() or path.is_symlink():
560
+ if any((root / parent).is_symlink() for parent in Path(relative).parents):
561
+ raise ValueError(
562
+ f"verification source path contains a symlink ancestor: {relative}"
563
+ )
564
+ files[relative] = _path_digest(path)
565
+ generated_files = {
566
+ relative: digest for relative, digest in files.items()
567
+ if is_generated_verification_path(relative, generated, protected)
568
+ }
569
+ protected_files = {
570
+ relative: digest for relative, digest in files.items()
571
+ if relative not in generated_files
572
+ }
573
+ return VerificationSourceSnapshot(
574
+ root=root, tracked_paths=tracked, generated_roots=generated,
575
+ input_paths=inputs, protected_files=MappingProxyType(protected_files),
576
+ generated_files=MappingProxyType(generated_files),
577
+ )
578
+
579
+
580
+ def compare_verification_sources(
581
+ before: VerificationSourceSnapshot, after: VerificationSourceSnapshot,
582
+ ) -> VerificationSourceChanges:
583
+ if before.root != after.root:
584
+ raise ValueError("verification source root changed")
585
+ if (before.generated_roots != after.generated_roots
586
+ or before.input_paths != after.input_paths):
587
+ raise ValueError("verification source classification changed")
588
+ return VerificationSourceChanges(
589
+ protected_changes=tuple(sorted(_changed_keys(
590
+ before.protected_files, after.protected_files,
591
+ ))),
592
+ generated_changes=tuple(sorted(_changed_keys(
593
+ before.generated_files, after.generated_files,
594
+ ))),
595
+ unclassified_paths=tuple(sorted(
596
+ set(after.protected_files) - before.protected_files.keys()
597
+ - before.generated_files.keys()
598
+ )),
599
+ tracked_paths_changed=before.tracked_paths != after.tracked_paths,
600
+ )
601
+
602
+
506
603
  def _content_snapshot(root: Path, excluded: frozenset[str]) -> dict[str, str]:
507
604
  """감사 대상 트리의 내용 다이제스트. `excluded` 는 정책이 선언한 생성
508
605
  경로와 레포가 무시하는 경로를 합친 접두사 집합이다."""
@@ -560,8 +657,9 @@ def _path_digest(path: Path) -> str:
560
657
 
561
658
 
562
659
  def _excluded(path: Path, excluded: frozenset[str]) -> bool:
563
- relative = path.as_posix()
564
- return any(relative == item or relative.startswith(item + "/") for item in excluded)
660
+ return path.as_posix() in excluded or any(
661
+ parent.as_posix() in excluded for parent in path.parents[:-1]
662
+ )
565
663
 
566
664
 
567
665
  def _non_source_paths(root: Path) -> frozenset[str]:
@@ -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}"
@@ -25,6 +25,8 @@ from .agent.invocation import (
25
25
  verify_agent_invocation,
26
26
  )
27
27
  from .path_hints import hydrate_active_run_context
28
+ from .verification_dispatch import VerificationDispatchError, seal_dispatch_generation
29
+ from .verification_invocation import VerificationGenerationReference
28
30
  from .report_inputs import report_narrative_path, uses_report_contract_v3
29
31
  from .report_synthesis_packet import (
30
32
  ReportSynthesisPacketError,
@@ -190,6 +192,7 @@ class _PromptItem:
190
192
  resources: tuple["_PromptResource", ...] = ()
191
193
  temp_path: Path | None = None
192
194
  stage_extract: str = ""
195
+ verification_generation: VerificationGenerationReference | None = None
193
196
 
194
197
 
195
198
  @dataclass(frozen=True)
@@ -496,6 +499,12 @@ def _prepare_prompt_item(
496
499
  if item.existed:
497
500
  _validate_existing_prompt(context, prepared_item)
498
501
  return prepared_item
502
+ # A published prompt's metadata already names its generation and
503
+ # `verify_agent_invocation` checks that binding; sealing again on reuse would
504
+ # recapture a tree the verifier's own run may have changed.
505
+ prepared_item = replace(
506
+ prepared_item, verification_generation=_seal_generation(context, item),
507
+ )
499
508
  temp_path: Path | None = None
500
509
  try:
501
510
  item.final_path.parent.mkdir(parents=True, exist_ok=True)
@@ -540,9 +549,28 @@ def _prepare_prompt_item(
540
549
  resources=resources,
541
550
  temp_path=temp_path,
542
551
  stage_extract=item.stage_extract,
552
+ verification_generation=prepared_item.verification_generation,
543
553
  )
544
554
 
545
555
 
556
+ def _seal_generation(
557
+ context: _MaterializationContext,
558
+ item: _PromptItem,
559
+ ) -> VerificationGenerationReference | None:
560
+ try:
561
+ return seal_dispatch_generation(
562
+ context.project_root, context.request.run_manifest_path, context.manifest,
563
+ context.active_context, audience=item.plan.duty_audience,
564
+ dispatch_kind="initial",
565
+ )
566
+ except VerificationDispatchError as exc:
567
+ raise InitialPromptMaterializationError(
568
+ "required_input_missing" if exc.missing_executor_result
569
+ else "validation_failed",
570
+ f"verification generation: {exc}",
571
+ ) from exc
572
+
573
+
546
574
  def _with_prompt_resources(
547
575
  item: _PromptItem,
548
576
  resources: tuple[_PromptResource, ...],
@@ -556,6 +584,7 @@ def _with_prompt_resources(
556
584
  resources=resources,
557
585
  temp_path=item.temp_path,
558
586
  stage_extract=item.stage_extract,
587
+ verification_generation=item.verification_generation,
559
588
  )
560
589
 
561
590
 
@@ -710,6 +739,7 @@ def _agent_invocation_request(
710
739
  duty_id=identity.duty_id if identity is not None else None,
711
740
  invocation_ref=invocation_id if identity is not None else None,
712
741
  attempt=1,
742
+ verification_generation=item.verification_generation,
713
743
  )
714
744
 
715
745
 
@@ -15,6 +15,7 @@ from pathlib import Path
15
15
 
16
16
  from . import next_phase
17
17
  from .ids import slugify_task_segment
18
+ from .generated_input import names_generated_input_document
18
19
  from .implementation_outcome import reconcile_implementation_outcome
19
20
  from .json_boundary import JsonBoundaryError, load_owned_object
20
21
  from .paths import RunRef, task_dir
@@ -109,6 +110,8 @@ def _autofill(args: argparse.Namespace) -> int:
109
110
  task_type = ""
110
111
  if args.need_brief:
111
112
  brief = (data.get("taskBriefPath") or "").strip()
113
+ if names_generated_input_document(Path(args.project_root), args.task_key, brief):
114
+ brief = ""
112
115
  if args.need_type:
113
116
  # 포인터 판정은 파이썬이 갖는다 — `ready` 가 아니면 빈 문자열이라
114
117
  # 셸이 센티널 목록을 따로 들고 있을 이유가 없다.
@@ -195,6 +198,8 @@ def main(argv: list[str] | None = None) -> int:
195
198
 
196
199
  autofill = sub.add_parser("autofill")
197
200
  autofill.add_argument("--manifest", required=True)
201
+ autofill.add_argument("--project-root", required=True)
202
+ autofill.add_argument("--task-key", required=True)
198
203
  autofill.add_argument("--need-brief", action="store_true")
199
204
  autofill.add_argument("--need-type", action="store_true")
200
205
  autofill.set_defaults(handler=_autofill)
@@ -4,6 +4,7 @@ from __future__ import annotations
4
4
  import contextlib
5
5
  import fcntl
6
6
  import hashlib
7
+ from collections.abc import Callable, Iterator
7
8
  from pathlib import Path
8
9
 
9
10
  from .ids import _escape_segment_for_join, _safe_fs_segment
@@ -85,6 +86,32 @@ def worktree_exec_lock(home, worktree, *, on_wait=None):
85
86
  잠그지 못할 때 어떻게 할지는 호출자가 정한다.
86
87
  """
87
88
  lockfile = worktree_exec_lock_path(home, worktree)
89
+ with _exclusive_lock(lockfile, on_wait):
90
+ yield lockfile
91
+
92
+
93
+ def resource_exec_lock_path(home: str | Path, resource_key: str) -> Path:
94
+ """`<home>/.locks/resource-exec/<key hash>.lock`, shared by every worktree."""
95
+ key = hashlib.sha256(resource_key.encode("utf-8")).hexdigest()
96
+ return Path(home) / ".locks" / "resource-exec" / f"{key[:32]}.lock"
97
+
98
+
99
+ @contextlib.contextmanager
100
+ def resource_exec_lock(
101
+ home: str | Path, resource_key: str, *,
102
+ on_wait: Callable[[Path], None] | None = None,
103
+ ) -> Iterator[Path]:
104
+ """Serialize checks that use one fixed resource (a port, a test database)
105
+ that worktree isolation cannot separate."""
106
+ lockfile = resource_exec_lock_path(home, resource_key)
107
+ with _exclusive_lock(lockfile, on_wait):
108
+ yield lockfile
109
+
110
+
111
+ @contextlib.contextmanager
112
+ def _exclusive_lock(
113
+ lockfile: Path, on_wait: Callable[[Path], None] | None,
114
+ ) -> Iterator[None]:
88
115
  lockfile.parent.mkdir(parents=True, exist_ok=True)
89
116
  with lockfile.open("a") as f:
90
117
  try:
@@ -94,6 +121,6 @@ def worktree_exec_lock(home, worktree, *, on_wait=None):
94
121
  on_wait(lockfile)
95
122
  fcntl.flock(f.fileno(), fcntl.LOCK_EX)
96
123
  try:
97
- yield lockfile
124
+ yield
98
125
  finally:
99
126
  fcntl.flock(f.fileno(), fcntl.LOCK_UN)