@pennixrv/trellis 0.7.2-beta.25 → 0.7.2-beta.27

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 (29) hide show
  1. package/dist/migrations/manifests/0.7.2-beta.26.json +8 -0
  2. package/dist/migrations/manifests/0.7.2-beta.27.json +8 -0
  3. package/dist/templates/codex/hooks/turn-guard.py +67 -0
  4. package/dist/templates/codex/hooks.json +63 -0
  5. package/dist/templates/common/bundled-skills/trellis-decision-space-construction-and-merging/workflow.md +6 -2
  6. package/dist/templates/common/bundled-skills/trellis-delivery-review-and-closeout/workflow.md +13 -9
  7. package/dist/templates/common/bundled-skills/trellis-goal-exploration-and-requirements/workflow.md +3 -1
  8. package/dist/templates/common/bundled-skills/trellis-solution-design-and-convergence/workflow.md +9 -1
  9. package/dist/templates/common/bundled-skills/trellis-task-implementation/workflow.md +2 -2
  10. package/dist/templates/common/commands/continue.md +9 -2
  11. package/dist/templates/common/skills/request-intake.md +2 -0
  12. package/dist/templates/omp/extensions/trellis/index.ts.txt +16 -9
  13. package/dist/templates/opencode/plugins/inject-workflow-state.js +15 -7
  14. package/dist/templates/pi/extensions/trellis/index.ts.txt +9 -4
  15. package/dist/templates/shared-hooks/index.d.ts.map +1 -1
  16. package/dist/templates/shared-hooks/index.js +1 -0
  17. package/dist/templates/shared-hooks/index.js.map +1 -1
  18. package/dist/templates/shared-hooks/inject-shell-session-context.py +27 -1
  19. package/dist/templates/shared-hooks/inject-workflow-state.py +44 -27
  20. package/dist/templates/trellis/index.d.ts.map +1 -1
  21. package/dist/templates/trellis/index.js +1 -0
  22. package/dist/templates/trellis/index.js.map +1 -1
  23. package/dist/templates/trellis/scripts/common/task_move.py +9 -3
  24. package/dist/templates/trellis/scripts/common/task_turn.py +514 -0
  25. package/dist/templates/trellis/scripts/common/task_workflow.py +289 -68
  26. package/dist/templates/trellis/scripts/common/workflow_selection.py +23 -38
  27. package/dist/templates/trellis/scripts/task.py +25 -4
  28. package/dist/templates/trellis/workflow.md +12 -2
  29. package/package.json +2 -2
@@ -80,6 +80,12 @@ def _state(meta: dict) -> dict:
80
80
  state = meta.get("task_workflow")
81
81
  if not isinstance(state, dict) or state.get("schema_version") != 1:
82
82
  raise TaskWorkflowError("TASK_PHASE_NOT_INITIALIZED", "task phase workflow is not initialized")
83
+ if "coverage_contract_version" in state and (
84
+ type(state["coverage_contract_version"]) is not int or state["coverage_contract_version"] != 1
85
+ ):
86
+ raise TaskWorkflowError("TASK_PHASE_TASK_INVALID", "unsupported coverage contract version")
87
+ if "complexity_reduction" in state and not _evidence_binding_shape(state["complexity_reduction"]):
88
+ raise TaskWorkflowError("TASK_PHASE_TASK_INVALID", "invalid complexity reduction evidence")
83
89
  if not isinstance(state.get("phases"), dict) or not isinstance(state.get("phase_ids"), list):
84
90
  raise TaskWorkflowError("TASK_PHASE_TASK_INVALID", "task phase workflow has an invalid shape")
85
91
  try:
@@ -126,6 +132,12 @@ def _state(meta: dict) -> dict:
126
132
  or not ROUTE_REVISION.fullmatch(str(skip.get("input_revision", "")))
127
133
  or not isinstance(skip.get("artifact_revision"), str)
128
134
  or not re.fullmatch(r"[a-f0-9]{64}", skip["artifact_revision"])
135
+ or ("basis" in skip and not _evidence_binding_shape(skip["basis"]))
136
+ or (("contract_ref" in skip or "contract_revision" in skip) and (
137
+ phase_id != PHASE_IDS[2] or skip.get("contract_ref") not in skip["evidence_refs"]
138
+ or not isinstance(skip.get("contract_revision"), str)
139
+ or not re.fullmatch(r"[a-f0-9]{64}", skip["contract_revision"])
140
+ ))
129
141
  or (
130
142
  phase_id in state["phases"]
131
143
  and skip["artifact_revision"] != state["phases"][phase_id].get("artifact_revision")
@@ -176,25 +188,18 @@ def implementation_start_ready(data: dict, task_dir: Path) -> bool:
176
188
  return False
177
189
  _require_current_requirements_confirmation(task_dir, state)
178
190
  _require_current_accepted_artifacts(task_dir, state)
179
- if PHASE_IDS[2] not in phase_ids:
180
- skip_records = state.get("skip_records")
181
- skipped_design = skip_records.get(PHASE_IDS[2]) if isinstance(skip_records, dict) else None
182
- evidence = skipped_design.get("evidence_refs") if isinstance(skipped_design, dict) else None
183
- return isinstance(evidence, list) and contract_ref in evidence
184
- design = state.get("phases", {}).get(PHASE_IDS[2])
185
- if not (
186
- isinstance(design, dict)
187
- and design.get("status") == "accepted"
188
- and design.get("outcome_kind") == "implementation_contract"
189
- and design.get("result_ref") == contract_ref
190
- ):
191
- return False
192
- artifact_refs = design.get("artifact_refs")
193
- if not isinstance(artifact_refs, list) or any(not isinstance(ref, str) for ref in artifact_refs):
194
- return False
195
- if _artifact_digest(task_dir, artifact_refs) != design.get("artifact_revision"):
196
- raise TaskWorkflowError("TASK_PHASE_STALE_ARTIFACT", "Solution Design and Convergence Phase implementation contract changed after acceptance; refresh and accept the current artifact before implementation")
197
- return True
191
+ _require_current_omissions(task_dir, state)
192
+ return _matches_contract(state, contract_ref)
193
+
194
+
195
+ def _matches_contract(state: dict, contract_ref: str) -> bool:
196
+ design = state["phases"].get(PHASE_IDS[2])
197
+ if isinstance(design, dict) and design["status"] == "accepted":
198
+ return design.get("outcome_kind") == "implementation_contract" and design.get("result_ref") == contract_ref
199
+ if design is None or design.get("status") == "skipped":
200
+ record = state["skip_records"].get(PHASE_IDS[2], {})
201
+ return record.get("contract_ref", contract_ref) == contract_ref and contract_ref in record.get("evidence_refs", [])
202
+ return False
198
203
 
199
204
 
200
205
  def _save(task_file: Path, data: dict) -> None:
@@ -433,6 +438,7 @@ def _init(args: argparse.Namespace, task_dir: Path, data: dict, meta: dict) -> i
433
438
  input_revision = "1"
434
439
  meta["task_workflow"] = {
435
440
  "schema_version": 1,
441
+ "coverage_contract_version": 1,
436
442
  "task_route_revision": "1",
437
443
  "task_kind": args.task_kind,
438
444
  "complexity": args.complexity,
@@ -466,29 +472,135 @@ def _show(state: dict) -> int:
466
472
  return 0
467
473
 
468
474
 
469
- def _require_acceptance_coverage(task_dir: Path, contract_ref: str) -> None:
470
- _artifact_digest(task_dir, [contract_ref])
471
- lines = (task_dir / contract_ref).read_text(encoding="utf-8").splitlines()
472
- heading = next((index for index, line in enumerate(lines) if line.strip() == "## 验收覆盖"), None)
473
- headers = ["接受条件", "工作包", "Owner", "验证入口", "交付证据", "停止条件"]
474
- if heading is not None:
475
- section = []
476
- for line in lines[heading + 1:]:
477
- if line.startswith("#"):
478
- break
479
- if line.strip():
480
- section.append(line.strip())
481
- rows = [line.strip("|").split("|") for line in section if line.startswith("|") and line.endswith("|")]
482
- rows = [[cell.strip() for cell in row] for row in rows]
483
- if (
484
- len(rows) >= 3
485
- and rows[0] == headers
475
+ def _read_phase_text(task_dir: Path, ref: str) -> str:
476
+ _artifact_digest(task_dir, [ref])
477
+ try:
478
+ return (task_dir / ref).read_text(encoding="utf-8")
479
+ except (OSError, UnicodeError) as error:
480
+ raise TaskWorkflowError("TASK_PHASE_ARTIFACT_INVALID", f"cannot read {ref}: {error}") from error
481
+
482
+
483
+ def _table(text: str, heading: str, headers: list[str]) -> list[list[str]]:
484
+ headings = re.split(r"(?m)^#{1,2}[ \t]+", text)
485
+ sections = [section.splitlines()[1:] for section in headings[1:] if section.splitlines()[0].strip() == heading]
486
+ rows = [[cell.strip() for cell in line.strip()[1:-1].split("|")]
487
+ for section in sections for line in section if line.strip().startswith("|") and line.strip().endswith("|")]
488
+ if (len(sections) == 1 and len(rows) >= 3 and rows[0] == headers
486
489
  and len(rows[1]) == len(headers)
487
490
  and all(re.fullmatch(r":?-{3,}:?", cell) for cell in rows[1])
488
- and all(len(row) == len(headers) and all(row) for row in rows[2:])
489
- ):
490
- return
491
- raise TaskWorkflowError("TASK_PHASE_COVERAGE_REQUIRED", "implementation contract requires ## 验收覆盖 with nonempty rows: " + " | ".join(headers))
491
+ and all(len(row) == len(headers) and all(row) for row in rows[2:])):
492
+ return rows[2:]
493
+ raise TaskWorkflowError("TASK_PHASE_COVERAGE_REQUIRED", f"## {heading} requires nonempty rows: " + " | ".join(headers))
494
+
495
+
496
+ def _require_acceptance_coverage(task_dir: Path, contract_ref: str) -> list[list[str]]:
497
+ return _table(_read_phase_text(task_dir, contract_ref), "验收覆盖",
498
+ ["接受条件", "工作包", "Owner", "验证入口", "交付证据", "停止条件"])
499
+
500
+
501
+ _ACCEPTANCE_ID = re.compile(r"^\**([A-Z][A-Z0-9]*(?:-[A-Z0-9]+)*[0-9])(?:\**(?=[::\s]|$)|(?=[::]))")
502
+ _CHECKLIST_ITEM = re.compile(r"^\s*[-*+]\s+\[[ xX]\]\s+(.+)$")
503
+ _OPTIONAL_PHASES = PHASE_IDS[1:3]
504
+
505
+
506
+ def _evidence_binding_shape(value: object) -> bool:
507
+ return (isinstance(value, dict) and isinstance(value.get("refs"), list)
508
+ and bool(value["refs"]) and all(isinstance(ref, str) and ref for ref in value["refs"])
509
+ and all(isinstance(value.get(key), str) and re.fullmatch(r"[a-f0-9]{64}", value[key])
510
+ for key in ("digest", "requirements")))
511
+
512
+
513
+ def _coverage_enabled(state: dict) -> bool:
514
+ return state.get("coverage_contract_version") == 1 and state["complexity"] == "complex"
515
+
516
+
517
+ def _requirements_ids(task_dir: Path, ref: str) -> set[str]:
518
+ text = _read_phase_text(task_dir, ref)
519
+ match = re.search(r"(?m)^##\s+(?:Acceptance Criteria|验收条件|验收标准)\s*$", text)
520
+ lines = re.split(r"(?m)^##\s+", text[match.end():], maxsplit=1)[0].splitlines() if match else []
521
+ items = [item[1] for ln in lines if (item := _CHECKLIST_ITEM.match(ln))]
522
+ ids = [found[1] for item in items if (found := _ACCEPTANCE_ID.match(item))]
523
+ if not ids or len(ids) != len(items) or len(set(ids)) != len(ids):
524
+ raise TaskWorkflowError("TASK_PHASE_COVERAGE_IDS_REQUIRED", "number every acceptance criterion once (for example A1, A2) in the confirmed requirements")
525
+ return set(ids)
526
+
527
+
528
+ def _check_coverage(task_dir: Path, state: dict, phase: str, outcome: str, ref: str) -> None:
529
+ if phase == PHASE_IDS[2] and outcome == "implementation_contract":
530
+ rows = _require_acceptance_coverage(task_dir, ref)
531
+ elif not _coverage_enabled(state):
532
+ return
533
+ elif phase == PHASE_IDS[1]:
534
+ rows = _table(_read_phase_text(task_dir, ref), "决策覆盖", ["接受条件", "处置", "证据"])
535
+ else:
536
+ rows = _table(_read_phase_text(task_dir, ref), "验收覆盖", ["接受条件", "结论", "证据"])
537
+ if not _coverage_enabled(state):
538
+ return
539
+ requirement_ref = _required_text(state["phases"][PHASE_IDS[0]].get("result_ref"), "accepted requirements result")
540
+ expected = _requirements_ids(task_dir, requirement_ref)
541
+ actual = [found[1] if (found := _ACCEPTANCE_ID.match(row[0])) else "" for row in rows]
542
+ if len(actual) != len(set(actual)) or set(actual) != expected:
543
+ raise TaskWorkflowError("TASK_PHASE_COVERAGE_MISMATCH", f"coverage IDs: missing {sorted(expected - set(actual))}; unknown {sorted(set(actual) - expected)}; IDs must be unique")
544
+ if phase == PHASE_IDS[1] or outcome != "implementation_contract":
545
+ refs = {row[2] for row in rows}
546
+ _artifact_digest(task_dir, sorted(refs))
547
+ bound = {value for key, record in state["phases"].items() if key == phase or record["status"] == "accepted"
548
+ for value in record["artifact_refs"]}
549
+ if not refs <= bound:
550
+ raise TaskWorkflowError("TASK_PHASE_COVERAGE_EVIDENCE_REQUIRED", f"bind coverage evidence with phase artifact first: {sorted(refs - bound)}")
551
+
552
+
553
+ def _omission_basis(task_dir: Path, phase: str, refs: list[str], requirement: dict) -> dict:
554
+ paths = [ref for ref in refs if Path(ref).suffix.lower() == ".md"]
555
+ if not paths:
556
+ raise TaskWorkflowError("TASK_PHASE_OMISSION_EVIDENCE_REQUIRED", f"{phase} needs task-local Markdown evidence")
557
+ heading = "降级依据" if phase == "complexity_reduction" else "省略依据"
558
+ headers = ["适用对象", "不再适用的理由" if phase == "complexity_reduction" else "省略理由", "依据", "重入条件"]
559
+ supporting = set(paths)
560
+ found = False
561
+ for ref in paths:
562
+ text = _read_phase_text(task_dir, ref)
563
+ if not re.search(rf"(?m)^##[ \t]+{heading}[ \t]*$", text):
564
+ continue
565
+ for row in _table(text, heading, headers):
566
+ if row[0] == phase:
567
+ found = True
568
+ supporting.add(row[2])
569
+ if not found:
570
+ raise TaskWorkflowError("TASK_PHASE_OMISSION_EVIDENCE_REQUIRED", f"## {heading} needs a row for {phase}")
571
+ return {"refs": sorted(supporting), "digest": _artifact_digest(task_dir, sorted(supporting)),
572
+ "requirements": requirement["artifact_revision"]}
573
+
574
+
575
+ def _bind_omissions(task_dir: Path, state: dict) -> None:
576
+ if not _coverage_enabled(state):
577
+ return
578
+ requirement = state["phases"][PHASE_IDS[0]]
579
+ for phase in _OPTIONAL_PHASES:
580
+ skip = state["skip_records"].get(phase)
581
+ if skip is not None and "basis" not in skip:
582
+ skip["basis"] = _omission_basis(task_dir, phase, skip["evidence_refs"], requirement)
583
+
584
+
585
+ def _require_current_omissions(task_dir: Path, state: dict) -> None:
586
+ skipped = state.get("skip_records", {}).get(PHASE_IDS[2], {})
587
+ if "contract_ref" in skipped and _artifact_digest(task_dir, [skipped["contract_ref"]]) != skipped.get("contract_revision"):
588
+ raise TaskWorkflowError("TASK_PHASE_STALE_OMISSION", "the contract bound to design omission changed")
589
+ if not _coverage_enabled(state) and state.get("complexity_reduction") is None:
590
+ return
591
+ requirement = state["phases"][PHASE_IDS[0]]
592
+ current = state.get("current_phase_id")
593
+ check = {}
594
+ if _coverage_enabled(state):
595
+ check.update({phase: state["skip_records"][phase].get("basis") for phase in _OPTIONAL_PHASES
596
+ if phase in state["skip_records"] and (current is None or PHASE_IDS.index(phase) <= PHASE_IDS.index(current))})
597
+ if state.get("complexity_reduction") is not None:
598
+ check["complexity reduction"] = state["complexity_reduction"]
599
+ for phase, basis in check.items():
600
+ if (not isinstance(basis, dict) or not _evidence_binding_shape(basis)
601
+ or basis["requirements"] != requirement["artifact_revision"]
602
+ or basis.get("digest") != _artifact_digest(task_dir, basis["refs"])):
603
+ raise TaskWorkflowError("TASK_PHASE_STALE_OMISSION", f"review and rebind {phase} evidence via phase route before proceeding")
492
604
 
493
605
 
494
606
  def _update(args: argparse.Namespace, task_dir: Path, data: dict, state: dict) -> int:
@@ -500,13 +612,23 @@ def _update(args: argparse.Namespace, task_dir: Path, data: dict, state: dict) -
500
612
  if data.get("status") in {"completed", "cancelled"}:
501
613
  raise TaskWorkflowError("TASK_PHASE_TASK_TERMINAL", f"task is already {data['status']}")
502
614
 
615
+ if action == "preflight":
616
+ return _preflight(args, task_dir, state)
617
+
503
618
  _expected_route(state, args.expected_route_revision)
504
619
  reviewed_delivery = (
505
620
  state.get("current_phase_id") is None
506
621
  and action in {"return", "route"}
507
622
  and state["phases"].get(PHASE_IDS[4], {}).get("status") == "accepted"
508
623
  )
509
- if reviewed_delivery:
624
+ skipped_delivery = (
625
+ state.get("current_phase_id") is None
626
+ and action == "return" and args.target_phase == PHASE_IDS[4]
627
+ and args.return_kind == "contract_change"
628
+ and state["phases"][PHASE_IDS[4]]["status"] == "skipped"
629
+ and state.get("closeout_disposition") is None
630
+ )
631
+ if reviewed_delivery or skipped_delivery:
510
632
  current, record = PHASE_IDS[4], state["phases"][PHASE_IDS[4]]
511
633
  else:
512
634
  current, record = _phase(state)
@@ -515,7 +637,7 @@ def _update(args: argparse.Namespace, task_dir: Path, data: dict, state: dict) -
515
637
  rerouting_to_requirements = action == "route" and args.target_phase == PHASE_IDS[0]
516
638
  if current != PHASE_IDS[0] and not returning_to_requirements and not rerouting_to_requirements:
517
639
  _require_current_requirements_confirmation(task_dir, state)
518
- if action not in {"show", "resume", "route", "authorize", "admission"} and record.get("status") != "active" and not reviewed_delivery and not accepted_design_return:
640
+ if action not in {"show", "resume", "route", "authorize", "admission"} and record.get("status") != "active" and not (reviewed_delivery or skipped_delivery or accepted_design_return):
519
641
  raise TaskWorkflowError("TASK_PHASE_INVALID_TRANSITION", "only the active phase can be changed")
520
642
 
521
643
  if action == "artifact":
@@ -556,8 +678,15 @@ def _update(args: argparse.Namespace, task_dir: Path, data: dict, state: dict) -
556
678
  elif action == "skip":
557
679
  reason = _required_text(args.reason, "--reason")
558
680
  evidence = _refs(args.evidence_ref, "--evidence-ref", required=True)
559
- if current == PHASE_IDS[0]:
560
- raise TaskWorkflowError("TASK_PHASE_INVALID_TRANSITION", "The Goal Exploration and Requirements Confirmation Phase must reach minimum alignment and acceptance and cannot be skipped")
681
+ if current not in PHASE_IDS[1:3]:
682
+ raise TaskWorkflowError("TASK_PHASE_INVALID_TRANSITION", f"Required phase cannot be skipped: {current}")
683
+ contract_fields = {}
684
+ if current == PHASE_IDS[2] and PHASE_IDS[3] in state["phase_ids"]:
685
+ contract_ref = _required_text(args.contract_ref, "--contract-ref")
686
+ if contract_ref not in evidence:
687
+ raise TaskWorkflowError("TASK_PHASE_CONTRACT_NOT_ACCEPTED", "include the implementation contract among the skip evidence")
688
+ _check_coverage(task_dir, state, PHASE_IDS[2], "implementation_contract", contract_ref)
689
+ contract_fields = {"contract_ref": contract_ref, "contract_revision": _artifact_digest(task_dir, [contract_ref])}
561
690
  record.update({"status": "skipped", "reason": reason, "evidence_refs": evidence})
562
691
  state["skip_records"][current] = {
563
692
  "reason": reason,
@@ -565,10 +694,15 @@ def _update(args: argparse.Namespace, task_dir: Path, data: dict, state: dict) -
565
694
  "task_route_revision": state["task_route_revision"],
566
695
  "input_revision": state["input_revision"],
567
696
  "artifact_revision": record["artifact_revision"],
697
+ **contract_fields,
568
698
  }
699
+ _bind_omissions(task_dir, state)
700
+ _require_current_omissions(task_dir, state)
569
701
  _advance(state, current)
570
702
  elif action == "accept":
571
703
  _require_current_accepted_artifacts(task_dir, state)
704
+ if current != PHASE_IDS[0]:
705
+ _require_current_omissions(task_dir, state)
572
706
  artifact_revision = _required_text(args.artifact_revision, "--artifact-revision")
573
707
  current_revision = _artifact_digest(task_dir, record["artifact_refs"])
574
708
  if artifact_revision != record["artifact_revision"] or current_revision != record["artifact_revision"]:
@@ -581,15 +715,25 @@ def _update(args: argparse.Namespace, task_dir: Path, data: dict, state: dict) -
581
715
  raise TaskWorkflowError("TASK_PHASE_INVALID_TRANSITION", "Goal Exploration and Requirements Confirmation Phase can advance only with phase_result=accepted")
582
716
  if current == PHASE_IDS[2] and outcome not in {"implementation_contract", "analysis_conclusion", "no_go"}:
583
717
  raise TaskWorkflowError("TASK_PHASE_INVALID_TRANSITION", "Solution Design and Convergence Phase must remain active for pending_user_decision or deferred; accept implementation_contract, analysis_conclusion, or no_go")
718
+ if current == PHASE_IDS[2] and (outcome == "implementation_contract") != (PHASE_IDS[3] in state["phase_ids"]):
719
+ raise TaskWorkflowError("TASK_PHASE_INVALID_ROUTE", "design result conflicts with the route; align the route before accepting")
584
720
  if result_ref not in record["artifact_refs"]:
585
721
  raise TaskWorkflowError("TASK_PHASE_RESULT_NOT_BOUND", "--result-ref must be included in the current phase artifact refs")
586
- if current == PHASE_IDS[2] and outcome == "implementation_contract":
587
- _require_acceptance_coverage(task_dir, result_ref)
722
+ if current == PHASE_IDS[0] and _coverage_enabled(state):
723
+ _requirements_ids(task_dir, result_ref)
724
+ _bind_omissions(task_dir, state)
725
+ elif current in _OPTIONAL_PHASES:
726
+ _check_coverage(task_dir, state, current, outcome, result_ref)
588
727
  if current == PHASE_IDS[3]:
589
- authorization = state.get("implementation_authorization")
590
- if not isinstance(authorization, dict) or authorization.get("task_route_revision") != state["task_route_revision"]:
728
+ if not implementation_start_ready(data, task_dir):
591
729
  raise TaskWorkflowError("TASK_PHASE_IMPLEMENTATION_NOT_AUTHORIZED", "Task Implementation and Test Verification Phase requires a current implementation authorization")
730
+ if data.get("status") != "in_progress":
731
+ raise TaskWorkflowError("TASK_PHASE_IMPLEMENTATION_NOT_STARTED", "enter in_progress with task.py start before accepting implementation")
592
732
  if current == PHASE_IDS[4]:
733
+ _require_current_omissions(task_dir, state)
734
+ readiness = _required_implementation_error(data, state)
735
+ if readiness:
736
+ raise TaskWorkflowError("TASK_PHASE_CLOSEOUT_REQUIRED", readiness)
593
737
  if args.closeout_disposition not in {"delivery_ready", "no_go", "cancelled"}:
594
738
  raise TaskWorkflowError("TASK_PHASE_INVALID_INPUT", "Delivery Review and On-Site Closeout Phase requires --closeout-disposition delivery_ready, no_go, or cancelled")
595
739
  if outcome != args.closeout_disposition:
@@ -625,7 +769,7 @@ def _update(args: argparse.Namespace, task_dir: Path, data: dict, state: dict) -
625
769
  execution_rework = return_kind == "execution_rework"
626
770
  if target not in state["phase_ids"] or (
627
771
  state["phase_ids"].index(target) >= state["phase_ids"].index(current)
628
- and not ((reviewed_delivery or accepted_design_return or execution_rework) and target == current)
772
+ and not ((reviewed_delivery or skipped_delivery or accepted_design_return or execution_rework) and target == current)
629
773
  ):
630
774
  raise TaskWorkflowError("TASK_PHASE_INVALID_TRANSITION", "return target must be an earlier phase in the current route")
631
775
  reason = _required_text(args.reason, "--reason")
@@ -662,7 +806,15 @@ def _update(args: argparse.Namespace, task_dir: Path, data: dict, state: dict) -
662
806
  reason = _required_text(args.reason, "--reason")
663
807
  target = _required_text(args.target_phase, "--target-phase")
664
808
  evidence = _refs(args.evidence_ref, "--evidence-ref", required=True)
809
+ if target not in PHASE_ID_SET:
810
+ raise TaskWorkflowError("TASK_PHASE_INVALID_ROUTE", "--target-phase must be a declared phase")
665
811
  old_ids = state["phase_ids"]
812
+ old_skips = state["skip_records"]
813
+ was_guarded = _coverage_enabled(state)
814
+ if args.enable_coverage and target != PHASE_IDS[0]:
815
+ raise TaskWorkflowError("TASK_PHASE_INVALID_ROUTE", "enabling coverage for an existing task requires returning to requirements")
816
+ if args.enable_coverage:
817
+ state["coverage_contract_version"] = 1
666
818
  changed = [phase for phase in PHASE_IDS if (phase in old_ids) != (phase in phases)]
667
819
  classification_changed = any(
668
820
  new != state[field]
@@ -678,10 +830,13 @@ def _update(args: argparse.Namespace, task_dir: Path, data: dict, state: dict) -
678
830
  and bool(evidence)
679
831
  and args.return_kind == "withdrawal"
680
832
  )
681
- if not changed and not classification_changed and target == current and not reviewed_delivery:
833
+ if not changed and not classification_changed and target == current and not (reviewed_delivery or args.enable_coverage):
682
834
  raise TaskWorkflowError("TASK_PHASE_INVALID_ROUTE", "the updated route and target are unchanged")
683
835
  earliest_change = min((PHASE_IDS.index(phase) for phase in changed), default=PHASE_IDS.index(target))
684
- if target not in PHASE_ID_SET or (PHASE_IDS.index(target) > earliest_change and not withdrawal_route):
836
+ if (PHASE_IDS[3] in changed and PHASE_IDS[2] in phases
837
+ and state["phases"].get(PHASE_IDS[2], {}).get("status") == "accepted"):
838
+ earliest_change = min(earliest_change, 2)
839
+ if PHASE_IDS.index(target) > earliest_change and not withdrawal_route:
685
840
  raise TaskWorkflowError("TASK_PHASE_INVALID_ROUTE", "--target-phase must cover the earliest affected route change")
686
841
  omitted = [phase for phase in PHASE_IDS if phase not in phases]
687
842
  old_phases = state["phases"]
@@ -693,6 +848,14 @@ def _update(args: argparse.Namespace, task_dir: Path, data: dict, state: dict) -
693
848
  state["project_context"] = project_context
694
849
  state["phase_ids"] = phases
695
850
  state["phases"] = {phase: old_phases.get(phase, _phase_record(state["input_revision"])) for phase in phases}
851
+ if not withdrawal_route and _coverage_enabled(state) and not was_guarded and target != PHASE_IDS[0]:
852
+ _requirements_ids(task_dir, _required_text(old_phases[PHASE_IDS[0]].get("result_ref"), "accepted requirements result"))
853
+ if withdrawal_route or _coverage_enabled(state):
854
+ state.pop("complexity_reduction", None)
855
+ elif was_guarded or state.get("complexity_reduction") is not None:
856
+ state["complexity_reduction"] = _omission_basis(
857
+ task_dir, "complexity_reduction", evidence, old_phases[PHASE_IDS[0]]
858
+ )
696
859
  affected = [phase for phase in phases if PHASE_IDS.index(phase) >= PHASE_IDS.index(target)]
697
860
  for phase_id in affected:
698
861
  state["phases"][phase_id].update({
@@ -708,7 +871,6 @@ def _update(args: argparse.Namespace, task_dir: Path, data: dict, state: dict) -
708
871
  and PHASE_IDS.index(previous_current) < PHASE_IDS.index(target)
709
872
  ):
710
873
  state["current_phase_id"] = previous_current
711
- state["phases"][previous_current]["status"] = "active"
712
874
  else:
713
875
  next_current = next((phase for phase in phases if PHASE_IDS.index(phase) >= PHASE_IDS.index(target)), None)
714
876
  state["current_phase_id"] = next_current
@@ -730,9 +892,9 @@ def _update(args: argparse.Namespace, task_dir: Path, data: dict, state: dict) -
730
892
  }
731
893
  for phase_id in omitted:
732
894
  phase_record = state["phases"].get(phase_id, old_phases.get(phase_id, _phase_record(state["input_revision"])))
895
+ preserved = old_skips.get(phase_id) if PHASE_IDS.index(phase_id) < PHASE_IDS.index(target) else None
733
896
  state["skip_records"][phase_id] = {
734
- "reason": reason,
735
- "evidence_refs": evidence,
897
+ **(preserved or {"reason": reason, "evidence_refs": evidence}),
736
898
  "task_route_revision": state["task_route_revision"],
737
899
  "input_revision": state["input_revision"],
738
900
  "artifact_revision": phase_record["artifact_revision"],
@@ -764,24 +926,27 @@ def _update(args: argparse.Namespace, task_dir: Path, data: dict, state: dict) -
764
926
  "evidence_refs": evidence,
765
927
  "task_route_revision": state["task_route_revision"],
766
928
  }
929
+ if not withdrawal_route and state["phases"][PHASE_IDS[0]]["status"] == "accepted":
930
+ _bind_omissions(task_dir, state)
931
+ _require_current_omissions(task_dir, state)
767
932
  elif action == "authorize":
768
- if current not in {PHASE_IDS[2], PHASE_IDS[3]}:
933
+ if current not in {PHASE_IDS[2], PHASE_IDS[3]} or PHASE_IDS[3] not in state["phase_ids"]:
769
934
  raise TaskWorkflowError("TASK_PHASE_INVALID_TRANSITION", "implementation authorization is recorded at the Task Implementation and Test Verification Phase entry")
935
+ if current == PHASE_IDS[3] and record["status"] != "active":
936
+ raise TaskWorkflowError("TASK_PHASE_INVALID_TRANSITION", "resume the implementation phase before authorizing")
770
937
  contract_ref = _required_text(args.contract_ref, "--contract-ref")
771
938
  approval_ref = _required_text(args.approval_ref, "--approval-ref")
772
- design = state["phases"].get(PHASE_IDS[2])
773
- if PHASE_IDS[2] in state["phase_ids"]:
774
- if not isinstance(design, dict) or design.get("status") != "accepted" or design.get("outcome_kind") != "implementation_contract" or design.get("result_ref") != contract_ref:
775
- raise TaskWorkflowError("TASK_PHASE_CONTRACT_NOT_ACCEPTED", "authorize the accepted implementation contract from Solution Design and Convergence Phase")
776
- artifact_refs = design.get("artifact_refs")
777
- if not isinstance(artifact_refs, list) or any(not isinstance(ref, str) for ref in artifact_refs):
778
- raise TaskWorkflowError("TASK_PHASE_TASK_INVALID", "accepted Solution Design and Convergence Phase artifact references are invalid")
779
- if _artifact_digest(task_dir, artifact_refs) != design.get("artifact_revision"):
780
- raise TaskWorkflowError("TASK_PHASE_STALE_ARTIFACT", "Solution Design and Convergence Phase implementation contract changed after acceptance; refresh and accept the current artifact before authorization")
781
- elif contract_ref not in state.get("skip_records", {}).get(PHASE_IDS[2], {}).get("evidence_refs", []):
782
- raise TaskWorkflowError("TASK_PHASE_CONTRACT_NOT_ACCEPTED", "when Solution Design and Convergence Phase is omitted, the implementation contract must be among its route evidence")
783
- _require_acceptance_coverage(task_dir, contract_ref)
784
- state["implementation_authorization"] = {"contract_ref": contract_ref, "contract_revision": _artifact_digest(task_dir, [contract_ref]), "approval_ref": approval_ref, "task_route_revision": state["task_route_revision"]}
939
+ if not _matches_contract(state, contract_ref):
940
+ raise TaskWorkflowError("TASK_PHASE_CONTRACT_NOT_ACCEPTED", "authorize the accepted implementation contract or the contract bound to design omission evidence")
941
+ _require_current_accepted_artifacts(task_dir, state)
942
+ _require_current_omissions(task_dir, state)
943
+ _check_coverage(task_dir, state, PHASE_IDS[2], "implementation_contract", contract_ref)
944
+ contract_revision = _artifact_digest(task_dir, [contract_ref])
945
+ if args.artifact_revision is not None:
946
+ approved_revision = design_preflight(task_dir, state, "implementation_contract", contract_ref, None)["artifact_revision"]
947
+ if args.artifact_revision != approved_revision:
948
+ raise TaskWorkflowError("TASK_PHASE_STALE_ARTIFACT", "authorization refers to a different candidate")
949
+ state["implementation_authorization"] = {"contract_ref": contract_ref, "contract_revision": contract_revision, "approval_ref": approval_ref, "task_route_revision": state["task_route_revision"]}
785
950
  if current == PHASE_IDS[2]:
786
951
  _advance(state, current)
787
952
  else:
@@ -805,6 +970,48 @@ def cmd_phase(args: argparse.Namespace) -> int:
805
970
  return 1
806
971
 
807
972
 
973
+ def _preflight(args: argparse.Namespace, task_dir: Path, state: dict) -> int:
974
+ if args.expected_route_revision is not None:
975
+ _expected_route(state, args.expected_route_revision)
976
+ print(json.dumps(design_preflight(task_dir, state, args.outcome_kind,
977
+ args.result_ref or args.contract_ref, args.artifact_revision), ensure_ascii=False))
978
+ return 0
979
+
980
+
981
+ def design_preflight(task_dir: Path, state: dict, outcome: str | None, ref: str | None, revision: str | None) -> dict:
982
+ current = state.get("current_phase_id")
983
+ if current not in {PHASE_IDS[2], PHASE_IDS[3]}:
984
+ raise TaskWorkflowError("TASK_PHASE_INVALID_TRANSITION", "preflight requires design or the implementation entry after design omission")
985
+ _require_current_requirements_confirmation(task_dir, state)
986
+ _require_current_accepted_artifacts(task_dir, state)
987
+ _require_current_omissions(task_dir, state)
988
+ design = state["phases"].get(PHASE_IDS[2], {})
989
+ outcome = outcome or design.get("outcome_kind") or "implementation_contract"
990
+ if (outcome not in {"implementation_contract", "analysis_conclusion", "no_go"}
991
+ or (outcome == "implementation_contract") != (PHASE_IDS[3] in state["phase_ids"])):
992
+ raise TaskWorkflowError("TASK_PHASE_INVALID_ROUTE", "preflight result conflicts with the route")
993
+ ref = _required_text(ref or design.get("result_ref"), "--result-ref or --contract-ref")
994
+ if current == PHASE_IDS[2]:
995
+ candidate = _artifact_digest(task_dir, design["artifact_refs"])
996
+ if ref not in design["artifact_refs"] or candidate != design["artifact_revision"]:
997
+ raise TaskWorkflowError("TASK_PHASE_STALE_ARTIFACT", "bind the current design candidate with phase artifact before preflight")
998
+ else:
999
+ if not _matches_contract(state, ref):
1000
+ raise TaskWorkflowError("TASK_PHASE_CONTRACT_NOT_ACCEPTED", "preflight requires the contract in the design omission record")
1001
+ candidate = _artifact_digest(task_dir, [ref])
1002
+ if revision is not None and revision != candidate:
1003
+ raise TaskWorkflowError("TASK_PHASE_STALE_ARTIFACT", "candidate changed since review")
1004
+ _check_coverage(task_dir, state, PHASE_IDS[2], outcome, ref)
1005
+ return {
1006
+ "status": "ready", "task": task_dir.name, "route_revision": state["task_route_revision"],
1007
+ "input_revision": state["input_revision"], "outcome_kind": outcome, "result_ref": ref,
1008
+ "artifact_revision": candidate, "requirements_revision": state["phases"][PHASE_IDS[0]]["artifact_revision"],
1009
+ "decision_revision": state["phases"].get(PHASE_IDS[1], {}).get("artifact_revision"),
1010
+ "omissions": {phase: skip.get("basis") for phase, skip in state["skip_records"].items() if phase in _OPTIONAL_PHASES},
1011
+ "complexity_reduction": state.get("complexity_reduction"),
1012
+ }
1013
+
1014
+
808
1015
  DELEGATION_DEPENDENCIES = {"pennix-lifecycle", "paseo", "git"}
809
1016
 
810
1017
 
@@ -1219,6 +1426,16 @@ def cmd_reopen_task(args: argparse.Namespace) -> int:
1219
1426
  return 1
1220
1427
 
1221
1428
 
1429
+ def _required_implementation_error(data: dict, state: dict) -> str | None:
1430
+ if PHASE_IDS[3] in state["phase_ids"]:
1431
+ implementation = state["phases"].get(PHASE_IDS[3])
1432
+ if not isinstance(implementation, dict) or implementation.get("status") != "accepted":
1433
+ return "the required implementation phase must be accepted before closeout"
1434
+ if data.get("status") not in {"in_progress", "completed"}:
1435
+ return "the required implementation phase did not enter in_progress"
1436
+ return None
1437
+
1438
+
1222
1439
  def task_closeout_readiness(data: dict, disposition: str) -> str | None:
1223
1440
  if "meta" in data and not isinstance(data["meta"], dict):
1224
1441
  return "task metadata is malformed"
@@ -1230,6 +1447,9 @@ def task_closeout_readiness(data: dict, disposition: str) -> str | None:
1230
1447
  return "task phase workflow data is malformed"
1231
1448
  if state.get("current_phase_id") is not None:
1232
1449
  return "the current task phase route is not complete"
1450
+ implementation_error = _required_implementation_error(data, state)
1451
+ if implementation_error:
1452
+ return implementation_error
1233
1453
  for phase_id in state["phase_ids"]:
1234
1454
  phase = state["phases"].get(phase_id)
1235
1455
  if not isinstance(phase, dict) or phase.get("status") not in {"accepted", "skipped"}:
@@ -1399,6 +1619,7 @@ def cmd_complete_task(args: argparse.Namespace) -> int:
1399
1619
  if disposition not in {"delivery_ready", "no_go"}:
1400
1620
  raise TaskWorkflowError("TASK_PHASE_CLOSEOUT_REQUIRED", "Delivery Review and On-Site Closeout Phase must accept delivery_ready or no_go before complete")
1401
1621
  _require_current_accepted_artifacts(task_dir, state)
1622
+ _require_current_omissions(task_dir, state)
1402
1623
  readiness_error = task_closeout_readiness(data, disposition)
1403
1624
  if readiness_error:
1404
1625
  raise TaskWorkflowError("TASK_PHASE_CLOSEOUT_REQUIRED", readiness_error)