okstra 0.230.0 → 0.231.1

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 (75) hide show
  1. package/README.md +3 -3
  2. package/docs/architecture/storage-model.md +67 -6
  3. package/docs/architecture.md +6 -2
  4. package/docs/coding-rules.md +15 -0
  5. package/docs/project-structure-overview.md +2 -1
  6. package/package.json +2 -2
  7. package/runtime/BUILD.json +2 -2
  8. package/runtime/prompts/coding-preflight/clean-code.md +8 -0
  9. package/runtime/prompts/coding-preflight/overview.md +1 -0
  10. package/runtime/prompts/launch.template.md +2 -0
  11. package/runtime/prompts/lead/convergence.md +3 -3
  12. package/runtime/prompts/lead/okstra-lead-contract.md +7 -7
  13. package/runtime/prompts/lead/report-writer.md +1 -1
  14. package/runtime/prompts/lead/team-contract.md +1 -1
  15. package/runtime/prompts/profiles/_clarification-recommendation.md +3 -2
  16. package/runtime/prompts/profiles/_coding-conventions-preflight.md +2 -0
  17. package/runtime/python/okstra_ctl/agent/invocation.py +48 -4
  18. package/runtime/python/okstra_ctl/approval_decisions.py +16 -0
  19. package/runtime/python/okstra_ctl/blocking_checks.py +10 -0
  20. package/runtime/python/okstra_ctl/business_flow/invocation.py +35 -3
  21. package/runtime/python/okstra_ctl/conformance_evidence.py +148 -67
  22. package/runtime/python/okstra_ctl/convergence.py +112 -20
  23. package/runtime/python/okstra_ctl/convergence_engine.py +1 -0
  24. package/runtime/python/okstra_ctl/convergence_provenance.py +27 -11
  25. package/runtime/python/okstra_ctl/correction_round.py +6 -1
  26. package/runtime/python/okstra_ctl/dispatch_checkpoints.py +28 -5
  27. package/runtime/python/okstra_ctl/dispatch_core.py +3 -11
  28. package/runtime/python/okstra_ctl/execution_mutation_audit.py +13 -1
  29. package/runtime/python/okstra_ctl/incremental_carry.py +7 -4
  30. package/runtime/python/okstra_ctl/paths.py +19 -4
  31. package/runtime/python/okstra_ctl/phases/final_verification/profile.md +1 -0
  32. package/runtime/python/okstra_ctl/phases/final_verification/report_assets/final-verification.template.html +8 -0
  33. package/runtime/python/okstra_ctl/phases/final_verification/spec.md +1 -0
  34. package/runtime/python/okstra_ctl/phases/final_verification/validation.py +53 -0
  35. package/runtime/python/okstra_ctl/phases/implementation/host-rules.md +5 -1
  36. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-deliverable.md +3 -1
  37. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-verifier.md +20 -4
  38. package/runtime/python/okstra_ctl/phases/implementation/report_assets/implementation.template.html +1 -1
  39. package/runtime/python/okstra_ctl/phases/implementation/spec.md +2 -0
  40. package/runtime/python/okstra_ctl/phases/implementation/validation.py +230 -30
  41. package/runtime/python/okstra_ctl/phases/implementation_planning/authoring.py +16 -22
  42. package/runtime/python/okstra_ctl/phases/implementation_planning/instructions/plan-body-verification.md +2 -2
  43. package/runtime/python/okstra_ctl/phases/implementation_planning/wizard.py +11 -4
  44. package/runtime/python/okstra_ctl/phases/release_handoff/operations.py +4 -5
  45. package/runtime/python/okstra_ctl/phases/release_handoff/profile.md +1 -1
  46. package/runtime/python/okstra_ctl/plan_items.py +28 -0
  47. package/runtime/python/okstra_ctl/render.py +15 -0
  48. package/runtime/python/okstra_ctl/report_assembly.py +102 -1
  49. package/runtime/python/okstra_ctl/report_execution_evidence.py +220 -0
  50. package/runtime/python/okstra_ctl/report_inputs.py +28 -0
  51. package/runtime/python/okstra_ctl/report_narrative.py +12 -3
  52. package/runtime/python/okstra_ctl/report_prose_keys.py +7 -0
  53. package/runtime/python/okstra_ctl/report_synthesis_packet.py +8 -0
  54. package/runtime/python/okstra_ctl/run.py +16 -0
  55. package/runtime/python/okstra_ctl/stage_close.py +52 -6
  56. package/runtime/python/okstra_ctl/stage_fix_carry.py +21 -1
  57. package/runtime/python/okstra_ctl/stage_integrate.py +90 -25
  58. package/runtime/python/okstra_ctl/team.py +3 -1
  59. package/runtime/python/okstra_ctl/verification_dispatch.py +8 -2
  60. package/runtime/python/okstra_ctl/verification_evidence.py +26 -7
  61. package/runtime/python/okstra_ctl/verification_generation.py +12 -4
  62. package/runtime/python/okstra_ctl/verification_inputs.py +10 -0
  63. package/runtime/python/okstra_ctl/verification_invocation.py +2 -1
  64. package/runtime/python/okstra_ctl/wizard/engine.py +23 -0
  65. package/runtime/python/okstra_ctl/wizard/steps_plan.py +6 -2
  66. package/runtime/python/okstra_ctl/worker_dispatch.py +3 -1
  67. package/runtime/python/okstra_ctl/worktree/git_ops.py +8 -1
  68. package/runtime/python/okstra_ctl/worktree/rebase.py +5 -2
  69. package/runtime/python/okstra_ctl/wrapper_status.py +16 -0
  70. package/runtime/schemas/final-report-v3.0.schema.json +184 -1
  71. package/runtime/skills/okstra-run/SKILL.md +5 -1
  72. package/runtime/templates/reports/html/i18n/en.json +7 -0
  73. package/runtime/templates/reports/html/i18n/ko.json +7 -0
  74. package/runtime/validators/validate-run.py +27 -11
  75. package/runtime/validators/validate-workflow.sh +1 -1
@@ -3,9 +3,23 @@ from __future__ import annotations
3
3
 
4
4
  import re
5
5
  from collections.abc import Callable, Mapping
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
6
8
  from typing import Any
7
9
 
10
+ from ...agent.invocation import AgentInvocationError, reserved_generation_reference
8
11
  from ...correction_round import correction_round
12
+ from ...json_boundary import load_owned_object
13
+ from ...report_execution_evidence import (
14
+ EXECUTION_EVIDENCE_BLOCKING, collect_report_evidence, omitted_records, reference_errors,
15
+ )
16
+ from ...paths import RunRef
17
+ from ...qa_procedures import safe_qa_path
18
+ from ...registry.verification_inputs_store import default_verification_input_store
19
+ from ...verification_dispatch import generation_sealed_after_round
20
+ from ...verification_evidence import roster_verifier_role_execution_ref
21
+ from ...verification_generation import read_verification_generation
22
+ from ...worker_prompt_policy import stage_qa_owner
9
23
 
10
24
  _PASSING_VERDICT_TOKENS = frozenset({"accepted", "conditional-accept"})
11
25
  _CHECKLIST_ID_RE = re.compile(r"\bVC-\d{3,}\b")
@@ -192,13 +206,18 @@ def _lead_fix_rows(implementation: dict) -> list[dict]:
192
206
  return [row for row in implementation.get("leadFixes") or [] if isinstance(row, dict)]
193
207
 
194
208
 
195
- def lead_fixed_verifiers(implementation: dict) -> frozenset[str]:
209
+ def lead_fixed_verifiers(
210
+ implementation: dict, *, evidence_contract: bool = False,
211
+ ) -> frozenset[str]:
196
212
  """정착된 stage 에서 통과한 리드 수정이 답한 FAIL 검증자 이름.
197
213
 
198
214
  stage 가 `withheld` 이면 리드 수정은 아무것도 해소하지 않는다 — 다음 run 은
199
215
  그 FAIL 행을 그대로 fix-run carry 로 받아야 한다.
216
+
217
+ An evidence-contract run settles a FAIL only through a correction round, so
218
+ its lead fixes answer none.
200
219
  """
201
- if not _stage_settled(implementation):
220
+ if evidence_contract or not _stage_settled(implementation):
202
221
  return frozenset()
203
222
  return frozenset(
204
223
  str(name)
@@ -208,43 +227,78 @@ def lead_fixed_verifiers(implementation: dict) -> frozenset[str]:
208
227
  )
209
228
 
210
229
 
211
- def _validate_lead_fixes(data: dict, failures: list[str]) -> None:
230
+ def _validate_lead_fixes(
231
+ data: dict, failures: list[str], *, evidence_contract: bool = False,
232
+ ) -> None:
212
233
  """리드 수정 기록과, FAIL 이 남은 채 정착된 stage 를 검사한다.
213
234
 
214
235
  `_implementation-deliverable.md` "Lead minor fix": 검증자 FAIL 이 있는 stage 를
215
236
  `done` 으로 정착시킬 수 있는 길은 재실행 검사가 전부 통과한 리드 수정뿐이다.
216
237
  finding 단위 대응은 검사하지 않는다 — `verifierResults[]` 에 구조화된 finding
217
238
  id 가 없어 계산할 수 없다. 검증자 행 단위(`verifiers`)까지만 본다.
239
+
240
+ An evidence-contract run has no lead-fix path: its `commands` are written by
241
+ the lead, and the fix commit was never sealed into a generation a verifier
242
+ re-checked.
218
243
  """
219
244
  implementation = data.get("implementation")
220
245
  if not isinstance(implementation, dict):
221
246
  return
222
247
  fixes = _lead_fix_rows(implementation)
223
- for index, row in enumerate(fixes):
224
- ids = ", ".join(str(item) for item in row.get("findingIds") or []) or "no finding id"
225
- label = f"implementation.leadFixes[{index}] ({ids})"
226
- commands = [cmd for cmd in row.get("commands") or [] if isinstance(cmd, dict)]
227
- failed = [cmd for cmd in commands if cmd.get("exitCode") != 0]
228
- if row.get("result") == "pass" and (failed or not commands):
229
- evidence = (
230
- f"`{str(failed[0].get('command'))[:120]}` exited {failed[0].get('exitCode')}"
231
- if failed else "no re-run command is recorded"
232
- )
233
- failures.append(
234
- f"{_LEAD_FIX_BLOCKING} {label} records `result: pass` but {evidence}. "
235
- "A lead fix passes only when every re-run check exits 0; otherwise "
236
- "record `result: fail` and withhold the stage."
237
- )
238
- lines = row.get("changedLines")
239
- if isinstance(lines, int) and lines > LEAD_FIX_LINE_LIMIT:
240
- failures.append(
241
- f"{_LEAD_FIX_BLOCKING} {label} changed {lines} lines; a lead minor fix "
242
- f"is limited to {LEAD_FIX_LINE_LIMIT}. A larger change belongs to a fix "
243
- "run, where the verifiers review it."
244
- )
245
- if not _stage_settled(implementation):
246
- return
247
- unsettled = [index for index, row in enumerate(fixes) if row.get("result") != "pass"]
248
+ if evidence_contract:
249
+ _reject_evidence_contract_lead_fixes(fixes, failures)
250
+ else:
251
+ for index, row in enumerate(fixes):
252
+ _check_lead_fix(index, row, failures)
253
+ if _stage_settled(implementation):
254
+ _check_settled_stage(data, implementation, fixes, evidence_contract, failures)
255
+
256
+
257
+ def _reject_evidence_contract_lead_fixes(fixes: list[dict], failures: list[str]) -> None:
258
+ for index, _row in enumerate(fixes):
259
+ failures.append(
260
+ f"{_LEAD_FIX_BLOCKING} implementation.leadFixes[{index}] records a lead "
261
+ "fix in an evidence-contract run. Its re-run commands are self-written "
262
+ "and its commit was never sealed into a generation a verifier "
263
+ "re-checked; send the fix through a correction round instead."
264
+ )
265
+
266
+
267
+ def _check_lead_fix(index: int, row: dict, failures: list[str]) -> None:
268
+ ids = ", ".join(str(item) for item in row.get("findingIds") or []) or "no finding id"
269
+ label = f"implementation.leadFixes[{index}] ({ids})"
270
+ commands = [cmd for cmd in row.get("commands") or [] if isinstance(cmd, dict)]
271
+ failed = [cmd for cmd in commands if cmd.get("exitCode") != 0]
272
+ if row.get("result") == "pass" and (failed or not commands):
273
+ evidence = (
274
+ f"`{str(failed[0].get('command'))[:120]}` exited {failed[0].get('exitCode')}"
275
+ if failed else "no re-run command is recorded"
276
+ )
277
+ failures.append(
278
+ f"{_LEAD_FIX_BLOCKING} {label} records `result: pass` but {evidence}. "
279
+ "A lead fix passes only when every re-run check exits 0; otherwise "
280
+ "record `result: fail` and withhold the stage."
281
+ )
282
+ lines = row.get("changedLines")
283
+ if isinstance(lines, int) and lines > LEAD_FIX_LINE_LIMIT:
284
+ failures.append(
285
+ f"{_LEAD_FIX_BLOCKING} {label} changed {lines} lines; a lead minor fix "
286
+ f"is limited to {LEAD_FIX_LINE_LIMIT}. A larger change belongs to a fix "
287
+ "run, where the verifiers review it."
288
+ )
289
+
290
+
291
+ def _check_settled_stage(
292
+ data: dict, implementation: dict, fixes: list[dict], evidence_contract: bool,
293
+ failures: list[str],
294
+ ) -> None:
295
+ """A settled stage holds no failed lead fix, and each FAIL row is answered.
296
+
297
+ An evidence-contract run's lead fixes were already rejected, so none of
298
+ them is read as failed or as answering a FAIL.
299
+ """
300
+ unsettled = [] if evidence_contract else [
301
+ index for index, row in enumerate(fixes) if row.get("result") != "pass"]
248
302
  if unsettled:
249
303
  failures.append(
250
304
  f"{_LEAD_FIX_BLOCKING} implementation.leadFixes{unsettled} recorded "
@@ -256,7 +310,8 @@ def _validate_lead_fixes(data: dict, failures: list[str]) -> None:
256
310
  who for who, row in _verifier_rows(data)
257
311
  if str(row.get("verdict") or "").strip() == "FAIL"
258
312
  }
259
- uncovered = sorted(rejected - lead_fixed_verifiers(implementation))
313
+ uncovered = sorted(rejected - lead_fixed_verifiers(
314
+ implementation, evidence_contract=evidence_contract))
260
315
  if uncovered:
261
316
  # 권고로 둔다 — 정착 여부는 종합 판정이 정하고, 수렴에서 반박된 한 검증자의
262
317
  # FAIL 위에 PASS 로 정착한 run 은 계약대로다. 막으면 그런 run 이 전부 멈춘다.
@@ -268,7 +323,6 @@ def _validate_lead_fixes(data: dict, failures: list[str]) -> None:
268
323
  "been withheld or answered by a passing lead minor fix."
269
324
  )
270
325
 
271
-
272
326
  _CORRECTION_BLOCKING = "correction-round BLOCKING:"
273
327
 
274
328
 
@@ -360,3 +414,149 @@ def _validate_verifier_fail_blocks_verdict(data: dict, failures: list[str]) -> N
360
414
  "the lead's to substitute "
361
415
  '(`_implementation-verifier.md` "All-verifier-failure policy").'
362
416
  )
417
+
418
+
419
+
420
+ def validate_verifier_execution_evidence(
421
+ data: dict, project_root: Path, manifest_path: Path,
422
+ manifest: Mapping[str, Any], failures: list[str],
423
+ ) -> None:
424
+ """Each verifier's `executionEvidence` in an evidence-contract run is its
425
+ current execution records.
426
+
427
+ A reference must be the latest run of a check under the verifier's latest
428
+ attempt of the invocation bound to the newest generation, with the bytes and
429
+ observation it recorded; a `not-run` row is not read.
430
+ """
431
+ try:
432
+ evidence = collect_report_evidence(project_root, manifest_path)
433
+ except ValueError as exc:
434
+ failures.append(f"{EXECUTION_EVIDENCE_BLOCKING} verification execution "
435
+ f"evidence could not be collected: {exc}")
436
+ return
437
+ implementation = data.get("implementation")
438
+ rows = implementation.get("verifierResults") if isinstance(implementation, dict) else None
439
+ for index, row in enumerate(rows if isinstance(rows, list) else []):
440
+ if not isinstance(row, dict) or row.get("verdict") == "not-run":
441
+ continue
442
+ where = f"implementation.verifierResults[{index}]"
443
+ role_execution_ref = roster_verifier_role_execution_ref(manifest, row.get("verifier"))
444
+ if role_execution_ref is None:
445
+ failures.append(f"{EXECUTION_EVIDENCE_BLOCKING} {where}.verifier "
446
+ f"`{row.get('verifier')}` names no roster verifier")
447
+ continue
448
+ verifiers = [evidence[role_execution_ref]] if role_execution_ref in evidence else []
449
+ matched: set[str] = set()
450
+ reported = row.get("executionEvidence") or []
451
+ for position, reference in enumerate(reported if isinstance(reported, list) else []):
452
+ errors, paths = reference_errors(
453
+ f"{where}.executionEvidence[{position}]", reference, verifiers,
454
+ )
455
+ failures.extend(f"{EXECUTION_EVIDENCE_BLOCKING} {error}" for error in errors)
456
+ matched |= paths
457
+ omitted = omitted_records(verifiers, matched)
458
+ if omitted:
459
+ failures.append(f"{EXECUTION_EVIDENCE_BLOCKING} {where} omits the "
460
+ f"verifier's execution records {omitted}")
461
+
462
+
463
+ @dataclass(frozen=True)
464
+ class _GenerationChecks:
465
+ qa: bool
466
+ conformance: bool
467
+
468
+ def owed_by(self, *, conformance_owner: bool) -> bool:
469
+ """Whether a verifier has a check of this generation that evidence
470
+ mode lets it run: any frozen qaCommands entry, or a sealed conformance
471
+ stage for the stage QA owner."""
472
+ return self.qa or (self.conformance and conformance_owner)
473
+
474
+
475
+ def _generation_checks(
476
+ project_root: Path, manifest: Mapping[str, Any], generation_path: str,
477
+ ) -> _GenerationChecks | None:
478
+ """The kinds of check the generation at `generation_path` holds; None when
479
+ no verifier invocation is bound to it, so no verifier was dispatched after
480
+ the fix and every one still owes a record."""
481
+ root = project_root.resolve()
482
+ digest = _bound_generation_digest(root, manifest, generation_path)
483
+ if digest is None:
484
+ return None
485
+ generation_record = read_verification_generation(
486
+ safe_qa_path(root, generation_path), digest,
487
+ )
488
+ inputs = default_verification_input_store().read(
489
+ safe_qa_path(root, generation_record["verificationInputsPath"]),
490
+ generation_record["verificationInputsDigest"],
491
+ )
492
+ return _GenerationChecks(
493
+ qa=any(inputs["qaCommands"].values()),
494
+ conformance=bool(generation_record.get("conformanceStages")),
495
+ )
496
+
497
+
498
+ def _bound_generation_digest(
499
+ project_root: Path, manifest: Mapping[str, Any], generation_path: str,
500
+ ) -> str | None:
501
+ """The digest an invocation reservation of this run binds the generation at
502
+ `generation_path` to; None when no reservation binds it."""
503
+ contract = manifest.get("agentContract")
504
+ reservations = (contract.get("invocationReservationRootPath")
505
+ if isinstance(contract, Mapping) else None)
506
+ if not isinstance(reservations, str):
507
+ return None
508
+ for path in sorted(safe_qa_path(project_root, reservations).glob("*.json")):
509
+ reservation = load_owned_object(path, artifact="invocation reservation")
510
+ reference = reserved_generation_reference(
511
+ project_root, manifest, reservation["invocationRef"], reservation["attempt"],
512
+ )
513
+ if reference is not None and reference.path == generation_path:
514
+ return reference.digest
515
+ return None
516
+
517
+
518
+ def validate_settled_round_was_reverified(
519
+ data: dict, project_root: Path, manifest_path: Path,
520
+ manifest: Mapping[str, Any], failures: list[str],
521
+ ) -> None:
522
+ """A stage settled after correction round N in an evidence-contract run
523
+ shows the records of generation N + 1, the one sealed after the executor's
524
+ fix, of each verifier that generation gives a check it may run.
525
+
526
+ Evidence mode refuses a `conformance:` check from anyone but the stage QA
527
+ owner, so with no frozen `qaCommands` entry the other verifiers can write no
528
+ record at all; requiring one from them made such a stage impossible to
529
+ settle.
530
+ """
531
+ implementation = data.get("implementation")
532
+ if not isinstance(implementation, dict) or not _stage_settled(implementation):
533
+ return
534
+ rounds = [row.get("round") for row in implementation.get("correctionRounds") or []
535
+ if isinstance(row, dict) and isinstance(row.get("round"), int)]
536
+ if not rounds:
537
+ return
538
+ generation = generation_sealed_after_round(max(rounds))
539
+ expected = RunRef.from_manifest(manifest_path, manifest).verification_generation(
540
+ generation).resolve().relative_to(project_root.resolve()).as_posix()
541
+ try:
542
+ checks = _generation_checks(project_root, manifest, expected)
543
+ except (AgentInvocationError, OSError, ValueError, KeyError) as exc:
544
+ failures.append(f"{_CORRECTION_BLOCKING} generation {generation} "
545
+ f"(`{expected}`) could not be read: {exc}")
546
+ return
547
+ owner = stage_qa_owner(manifest)
548
+ for who, row in _verifier_rows(data):
549
+ if row.get("verdict") == "not-run":
550
+ continue
551
+ if checks is not None and not checks.owed_by(
552
+ conformance_owner=row.get("verifier") == owner):
553
+ continue
554
+ references = [reference for reference in row.get("executionEvidence") or []
555
+ if isinstance(reference, dict)]
556
+ if not references or any((reference.get("generation") or {}).get("path")
557
+ != expected for reference in references):
558
+ failures.append(
559
+ f"{_CORRECTION_BLOCKING} {who} settled the stage after correction "
560
+ f"round {max(rounds)} without execution records of generation "
561
+ f"{generation} (`{expected}`), the one sealed after the fix."
562
+ )
@@ -48,10 +48,11 @@ from okstra_ctl.plan_items import (
48
48
  lead_decision_basis,
49
49
  next_dispatch,
50
50
  planning_stage_ledger,
51
- reverify_item_ids,
51
+ queue_candidate_ids,
52
52
  reverify_prompt_text,
53
53
  self_fix_rounds,
54
54
  tie_vote_item_ids,
55
+ verified_content_hashes,
55
56
  voting_analyser_keys,
56
57
  with_rendered_by,
57
58
  with_response_format,
@@ -114,14 +115,9 @@ def _merged_ledger(
114
115
  def _previous_hashes(state_path: Path | None) -> dict[str, str]:
115
116
  if state_path is None or not state_path.is_file():
116
117
  return {}
117
- rows = _state_plan_body_items(_load_json_object(state_path), state_path)
118
- return {
119
- str(row["id"]): str(row["verifiedContentHash"])
120
- for row in rows
121
- if isinstance(row, Mapping)
122
- and isinstance(row.get("id"), str)
123
- and isinstance(row.get("verifiedContentHash"), str)
124
- }
118
+ return verified_content_hashes(
119
+ _state_plan_body_items(_load_json_object(state_path), state_path)
120
+ )
125
121
 
126
122
 
127
123
  def _queue_for(
@@ -138,9 +134,7 @@ def _queue_for(
138
134
  return tie_vote_item_ids(items, ledger, tied_ids)
139
135
  inputs = review_inputs or _review_inputs(items, planning, run_manifest, previous_rows)
140
136
  reusable = reusable_item_ids(previous_rows, inputs)
141
- candidates = set(dispatch_item_ids(items, ledger))
142
- if previous_hashes:
143
- candidates.update(reverify_item_ids(items, previous_hashes, ledger))
137
+ candidates = queue_candidate_ids(items, ledger, previous_hashes or {})
144
138
  return [item["id"] for item in items if item["id"] in candidates - reusable]
145
139
 
146
140
 
@@ -1148,13 +1142,20 @@ def _validate_prepared(args: argparse.Namespace) -> dict[str, Any]:
1148
1142
  **_queue_kwargs(args),
1149
1143
  )
1150
1144
  if actual.get("dispatchQueue") != expected_queue:
1151
- raise PlanItemContractError("prepared dispatch queue does not match")
1145
+ raise PlanItemContractError(
1146
+ "prepared dispatch queue does not match the queue derived from "
1147
+ "the current plan and state; prepare again, and pass "
1148
+ "validate-prepared the same --state that prepare used"
1149
+ )
1152
1150
  current_inputs = _review_inputs(
1153
1151
  expected["items"], _planning(source), args.run_manifest,
1154
1152
  _queue_kwargs(args).get("previous_rows", []),
1155
1153
  )
1156
1154
  if actual.get("reviewInputs") != current_inputs:
1157
- raise PlanItemContractError("prepared review evidence changed; prepare again")
1155
+ raise PlanItemContractError(
1156
+ "prepared review evidence changed; prepare again, and pass "
1157
+ "validate-prepared the same --state that prepare used"
1158
+ )
1158
1159
  if not getattr(args, "tie_vote", False):
1159
1160
  # 라운드 2+ 의 반대 의견 반입은 여기서만 검사된다. 봉투에서 빠지면
1160
1161
  # 프롬프트에도 빠지고, 반대한 워커는 자기 판정을 그대로 다시 적는다.
@@ -1648,18 +1649,11 @@ def _seed(args: argparse.Namespace) -> dict[str, Any]:
1648
1649
  ledger = _merged_ledger(_planning(source), getattr(args, "run_manifest", None))
1649
1650
  if ledger:
1650
1651
  verification["stageLedger"] = ledger
1651
- previous = {
1652
- str(row["id"]): str(row["verifiedContentHash"])
1653
- for row in recorded
1654
- if isinstance(row, Mapping)
1655
- and isinstance(row.get("id"), str)
1656
- and isinstance(row.get("verifiedContentHash"), str)
1657
- }
1658
1652
  verification["dispatchQueue"] = _queue_for(
1659
1653
  extracted,
1660
1654
  _planning(source),
1661
1655
  getattr(args, "run_manifest", None),
1662
- previous,
1656
+ verified_content_hashes(recorded),
1663
1657
  previous_rows=recorded,
1664
1658
  )
1665
1659
  verification["gating"] = (
@@ -413,11 +413,11 @@ round before any host or provider process starts.
413
413
 
414
414
  For contract 3.0, `prepare` checks the selected-direction draft with the same semantic validator as publication before writing the queue. Correct all reported references, coverage rows and planned commands through the writer correction procedure, then retry in this run. **Enforced:** `report_assembly.validate_plan_draft` and `plan_items_cli._prepare`; the retired Python suite previously checked that invalid coverage creates no prepared queue.
415
415
 
416
- 1. Lead runs `okstra plan-items prepare --narrative <report-writer-narrative.md> --run-manifest <run-manifest>`, places the fixed output of `okstra plan-items prompt --run-manifest <run-manifest>` verbatim in every verifier prompt, then runs `okstra plan-items validate-prepared --narrative <report-writer-narrative.md> --run-manifest <run-manifest>`. A `File-size headroom` line that prepare prints, and that `okstra plan-items prompt` carries under `## File-size headroom`, is a report only: it names an existing file the plan writes, its lines left before the 500-line implementation limit and the stages that write it. It does not block, open a correction or count as a verdict. After a self-fix rewrite, pass `--state <plan-body-verification.json>` on prepare and validate-prepared. The runtime reuses a verdict only when its body, complete declared evidence closure, shared analysis packet, plan metadata, reviewer assignments and review contract have the same fingerprint. A missing or uncertain dependency declaration, unresolved reference, non-result or executable fact probe stays in the re-verification queue. Detailed verdicts and their original rounds remain unchanged for reused items. File dependencies cover whole files; step items also include preceding steps; plan-wide and preparation items include all plan items. Python resolves the one convergence-owned state path from that run identity. Dispatch only after exact-match validation succeeds. `observed` / `deferred` stages remain omitted. An empty queue opens no worker dispatch and creates no verification round. **Enforced:** `implementation_planning.authoring._queue_for`, `plan_item_evidence.review_fingerprint`, `_validate_prepared` and the retired Python suite. An incremental carry without evidence snapshots keeps active items queued until prepare can validate their dependencies.
416
+ 1. Lead runs `okstra plan-items prepare --narrative <report-writer-narrative.md> --run-manifest <run-manifest>`, places the fixed output of `okstra plan-items prompt --run-manifest <run-manifest>` verbatim in every verifier prompt, then runs `okstra plan-items validate-prepared --narrative <report-writer-narrative.md> --run-manifest <run-manifest>`. A `File-size headroom` line that prepare prints, and that `okstra plan-items prompt` carries under `## File-size headroom`, is a report only: it names an existing file the plan writes, its lines left before the 500-line implementation limit and the stages that write it. It does not block, open a correction or count as a verdict. After a self-fix rewrite, and after `okstra incremental-carry` on a re-run, pass `--state <plan-body-verification.json>` on prepare and validate-prepared; validate-prepared needs the same `--state` the last prepare used, or it refuses with `prepared dispatch queue does not match` or `prepared review evidence changed`. The runtime reuses a verdict only when its body, complete declared evidence closure, shared analysis packet, plan metadata, reviewer assignments and review contract have the same fingerprint. A missing or uncertain dependency declaration, unresolved reference, non-result or executable fact probe stays in the re-verification queue. Detailed verdicts and their original rounds remain unchanged for reused items. File dependencies cover whole files; step items also include preceding steps; plan-wide and preparation items include all plan items. Python resolves the one convergence-owned state path from that run identity. Dispatch only after exact-match validation succeeds. `observed` / `deferred` stages remain omitted. An empty queue opens no worker dispatch and creates no verification round. **Enforced:** `implementation_planning.authoring._queue_for`, `plan_item_evidence.review_fingerprint`, `_validate_prepared` and the retired Python suite. An incremental carry without evidence snapshots keeps active items queued until prepare can validate their dependencies.
417
417
 
418
418
  **Then seed the landing table (BLOCKING):** `okstra plan-items seed --narrative <report-writer-narrative.md> --state <plan-body-verification.json> --run-manifest <run-manifest.json>`. `apply-verdicts` in step 8 refuses a verdict whose item has no `planBodyVerification.planItems[]` row. The report writer never owns that state, so the deterministic seed is the only creator of its rows. The seed is idempotent by id and never touches existing verdicts, so it is safe to re-run between rounds and after a self-fix re-extraction. It does refresh `contentHash` from the current extract. Skipping it makes step 8 fail with `plan-body state has no row for [...]`.
419
419
 
420
- **On a re-run, add `--prior-state <the previous run's plan-body-verification-<task-type>-<seq>.json>`.** A newly seeded item inherits verdicts only when its body and verified evidence fingerprint match the prepared snapshot for the same task. Reused rows carry `carriedForwardFromSeq`; their full verdicts are preserved. Legacy body-only records re-enter verification. A matching id alone never carries: `P-*` ids are positional. The flag requires `--state` and refuses another task's state. **Enforced:** `implementation_planning.authoring._carry_prior_run_verdicts` and `plan_item_evidence.reusable_item_ids`.
420
+ **On a re-run, add `--prior-state <the previous run's plan-body-verification-<task-type>-<seq>.json>`.** An incremental re-run then runs `okstra incremental-carry` and repeats prepare, prompt and validate-prepared with `--state` before dispatch (launch prompt "Incremental re-verification" step 7). A newly seeded item inherits verdicts only when its body and verified evidence fingerprint match the prepared snapshot for the same task. Reused rows carry `carriedForwardFromSeq`; their full verdicts are preserved. Legacy body-only records re-enter verification. A matching id alone never carries: `P-*` ids are positional. The flag requires `--state` and refuses another task's state. **Enforced:** `implementation_planning.authoring._carry_prior_run_verdicts` and `plan_item_evidence.reusable_item_ids`.
421
421
 
422
422
  **`--run-manifest` is what scopes the gate to the stage you are starting.** Seed uses it to overlay disk `done` / `active` onto `planBodyVerification.stageLedger`. The current plan's depends-on fills `ready` / `blocked` when no prior plan exists, so a first run does not treat every stage as in-scope. **Enforced:** `okstra_ctl.plan_items.planning_stage_ledger`.
423
423
  2. For each analyser worker in the roster, use `okstra plan-items prompt` output verbatim as the instruction body in the materialization sequence above. Read §"Re-verification rounds (round 2+)" before preparing a later round; read §"Plan-body reverify prompt" only when diagnosing a prompt-contract failure.
@@ -216,13 +216,20 @@ def _submit_selected_direction_pick(state: WizardState, value: str) -> Optional[
216
216
  resolve_selected_direction(report, expected_task_key=_task_key(state))
217
217
  except (DirectionSelectionError, UserResponseError) as exc:
218
218
  raise WizardError(str(exc)) from exc
219
+ if _settle_selected_direction(state, path):
220
+ return t["echo_variants"]["cleared_clarification"].format(value=path) + recorded
221
+ return f"selected-direction: {path}{recorded}"
222
+
223
+
224
+ def _settle_selected_direction(state: WizardState, path: str) -> bool:
225
+ """Returns whether a clarification response was cleared."""
219
226
  state.selected_direction_path = path
220
227
  # 두 입력은 상호 배타다 — 방향이 정해진 순간 이 런은 새 계획이고,
221
228
  # clarification 자리에 남은 값은 render-bundle 이 거절할 이유일 뿐이다.
222
229
  # 거절을 여기서 앞당기는 대신 값을 비우고, 무엇이 비워졌는지 echo 로
223
230
  # 알린다. 사용자 답변은 손실되지 않는다: 그 사이드카는
224
231
  # `--selected-direction` 경로로 계획 런에 첨부된다(`run.py` 참조).
225
- if state.clarification_response_path:
226
- state.clarification_response_path = ""
227
- return t["echo_variants"]["cleared_clarification"].format(value=path) + recorded
228
- return f"selected-direction: {path}{recorded}"
232
+ if not state.clarification_response_path:
233
+ return False
234
+ state.clarification_response_path = ""
235
+ return True
@@ -25,13 +25,12 @@ from okstra_ctl.worktree import (
25
25
  class HandoffConflict(Exception):
26
26
  """선행 stage 들 사이의 merge 충돌 — exit 2, 충돌 경로 동봉."""
27
27
 
28
- def __init__(self, stage: int, branch: str, paths: List[str]):
28
+ def __init__(self, stage: int, branch: str, paths: List[str],
29
+ message: str):
29
30
  self.stage = stage
30
31
  self.branch = branch
31
32
  self.paths = paths
32
- super().__init__(
33
- f"merge conflict while merging stage {stage} ({branch}): "
34
- f"{', '.join(paths)}")
33
+ super().__init__(message)
35
34
 
36
35
 
37
36
  def compute_eligibility(stage_map: List[Dict[str, Any]],
@@ -118,7 +117,7 @@ def _merge_base_for(*, project_root, project_id, task_group, task_id,
118
117
  anchor_base=anchor_base)
119
118
  except MergeBranchConflict as exc:
120
119
  raise HandoffConflict(stage=exc.stage, branch=exc.branch,
121
- paths=exc.paths) from exc
120
+ paths=exc.paths, message=str(exc)) from exc
122
121
  except IntegrateError as exc:
123
122
  raise HandoffError(str(exc)) from exc
124
123
 
@@ -38,7 +38,7 @@
38
38
  This is the release base for the run, not necessarily each PR's base: a stage that sits on another stage of this task targets that stage's branch. The release base MUST contain the task's implementation anchor base. `pr-plan` derives stacking inside this task only; when the task was built on another task's unmerged stage branch, the release base is that predecessor task's stage branch, which prepare names as the recommended base. The chosen base MUST NOT be one of this task's stage branches. If it is, re-ask.
39
39
  2p. **PR plan** (only when the user picked `push + PR`) — run
40
40
  `okstra handoff pr-plan --plan-run-root <...> --approved-plan <...> --project-root <project root> --project-id <id> --task-group <g> --task-id <t> --work-category <c> --stages <HANDOFF_STAGES> --base <chosen-base>`.
41
- It returns one row per stage with `head_branch`, `head_commit`, `base_kind` (`release-base` | `stage` | `merge-base`), `base_branch` and `base_commit`. Exit 2 means the predecessors of a multi-dependency stage conflict with each other: show the `conflicts` paths and stop (route: resolve manually, then retry). Exit 1 means an eligibility or dependency violation — most often a stage whose predecessor is neither in this run nor already PR'd nor merged into the release base: show the error verbatim and re-ask the action selection. When the error says the release base does not contain the implementation anchor, the error names the `--base` that does: show it verbatim and re-ask Q2 with that branch first. **Enforced:** `okstra_ctl.phases.release_handoff.operations._resolve_stage_base` refuses the plan. On success these rows are authoritative for every subsequent step; the lead does not recompute a base by hand.
41
+ It returns one row per stage with `head_branch`, `head_commit`, `base_kind` (`release-base` | `stage` | `merge-base`), `base_branch` and `base_commit`. Exit 2 means the predecessors of a multi-dependency stage conflict with each other: show the `conflicts` paths and the `error` text verbatim and stop. The `error` names the merge-base branch, the anchor it starts from and the predecessor commits to merge in order; route: the user rebuilds that branch by hand as described, then retries, and `pr-plan` reuses it only when it contains the anchor and every listed commit. Exit 1 means an eligibility or dependency violation — most often a stage whose predecessor is neither in this run nor already PR'd nor merged into the release base: show the error verbatim and re-ask the action selection. When the error says the release base does not contain the implementation anchor, the error names the `--base` that does: show it verbatim and re-ask Q2 with that branch first. **Enforced:** `okstra_ctl.phases.release_handoff.operations._resolve_stage_base` refuses the plan. On success these rows are authoritative for every subsequent step; the lead does not recompute a base by hand.
42
42
  A `merge-base` row means `pr-plan` created a branch merging that stage's predecessors. That branch is a PR base only — it is never a PR head — and it MUST be pushed before the PR that targets it.
43
43
  The output also carries `push_plan` and `warnings`. `push_plan` is every branch the PRs sit on, already in push order (each `merge-base` first, then the stage heads in dependency order), with the `commit` it must reach and an `action` of `create` (origin does not have it), `fast-forward` (origin is behind) or `up-to-date` (origin already has that commit — do not push it). GitHub resolves a PR's head and base by name on origin, so this list, not the local branch set, is what makes the stack real. A `warnings` row means `pr-plan` fast-forwarded a local branch to origin because origin was ahead: the commits origin adds are outside what this run verified. Quote every `warnings` row verbatim in Executed Commands and say so in the branch/PR explanation — the user is deciding whether to release commits this run did not verify. `pr-plan` refuses outright when a branch moved outside okstra or diverged from origin, since only a force push could deliver it.
44
44
  2b. **Pre-merge conflict probe** (only when the user picked `push + PR`) — before pushing, for each planned stage in dependency order:
@@ -626,6 +626,34 @@ def reverify_item_ids(
626
626
  return queue
627
627
 
628
628
 
629
+ def verified_content_hashes(rows: Sequence[Mapping[str, Any]]) -> dict[str, str]:
630
+ """`{item id: verifiedContentHash}` for the rows a recorded verdict covers."""
631
+ return {
632
+ str(row["id"]): str(row["verifiedContentHash"])
633
+ for row in rows
634
+ if isinstance(row, Mapping)
635
+ and isinstance(row.get("id"), str)
636
+ and isinstance(row.get("verifiedContentHash"), str)
637
+ }
638
+
639
+
640
+ def queue_candidate_ids(
641
+ items: Sequence[Mapping[str, Any]],
642
+ ledger: Mapping[str, str] | None,
643
+ previous_hashes: Mapping[str, str],
644
+ ) -> set[str]:
645
+ """Items a round may dispatch before verdict reuse narrows them.
646
+
647
+ `plan-items prepare` and `incremental-carry` both persist a queue, and
648
+ `team await` refuses a round whose prepared items fall outside the state's,
649
+ so both writers take their candidates from this one rule.
650
+ """
651
+ candidates = set(dispatch_item_ids(items, ledger))
652
+ if previous_hashes:
653
+ candidates.update(reverify_item_ids(items, previous_hashes, ledger))
654
+ return candidates
655
+
656
+
629
657
  def requires_plan_repair(verification: Mapping[str, Any]) -> bool:
630
658
  """검사·구현 가능성의 사실 결함은 단계 수에 따른 자문 면제에서 제외한다."""
631
659
  return any(
@@ -1705,6 +1705,18 @@ def _build_convergence_block(ctx: dict) -> dict:
1705
1705
  }
1706
1706
 
1707
1707
 
1708
+ def _evidence_contract_fields(
1709
+ recorded_manifest: dict | None, ctx: dict,
1710
+ ) -> dict[str, str]:
1711
+ """A recorded run keeps the contract it started with, so a run prepared
1712
+ before the contract existed resumes unmarked."""
1713
+ if recorded_manifest is not None:
1714
+ version = recorded_manifest.get("verificationEvidenceVersion")
1715
+ else:
1716
+ version = ctx.get("VERIFICATION_EVIDENCE_VERSION")
1717
+ return {} if version is None else {"verificationEvidenceVersion": version}
1718
+
1719
+
1708
1720
  def render_run_manifest(run_manifest_path: str, ctx: dict) -> None:
1709
1721
  run_manifest_file = Path(run_manifest_path)
1710
1722
  run_manifest_exists = run_manifest_file.is_file()
@@ -1873,6 +1885,9 @@ def render_run_manifest(run_manifest_path: str, ctx: dict) -> None:
1873
1885
  "verificationTargetDigest": ctx.get("VERIFICATION_TARGET_DIGEST", ""),
1874
1886
  "workerResultsDirectoryPath": ctx.get("WORKER_RESULTS_RELATIVE_PATH", ""),
1875
1887
  **artifact_fields(manifest_input_ref),
1888
+ **_evidence_contract_fields(
1889
+ existing_run_manifest if run_manifest_exists else None, ctx,
1890
+ ),
1876
1891
  "reportTemplatePath": ctx.get("FINAL_REPORT_TEMPLATE_RELATIVE_PATH", ""),
1877
1892
  "validatorScriptPath": ctx.get("RUN_VALIDATOR_RELATIVE_PATH", ""),
1878
1893
  "leadSessionId": ctx.get("CLAUDE_SESSION_ID", ""),