letitloop 0.2.0__py3-none-any.whl

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 (175) hide show
  1. letitloop-0.2.0.dist-info/METADATA +232 -0
  2. letitloop-0.2.0.dist-info/RECORD +175 -0
  3. letitloop-0.2.0.dist-info/WHEEL +5 -0
  4. letitloop-0.2.0.dist-info/entry_points.txt +4 -0
  5. letitloop-0.2.0.dist-info/licenses/LICENSE +21 -0
  6. letitloop-0.2.0.dist-info/top_level.txt +1 -0
  7. orchestrator/SKILL.md +292 -0
  8. orchestrator/__init__.py +151 -0
  9. orchestrator/anti_ouroboros.py +78 -0
  10. orchestrator/approval.py +139 -0
  11. orchestrator/ast_node_splicer.py +130 -0
  12. orchestrator/ast_splicer.py +94 -0
  13. orchestrator/audit.py +88 -0
  14. orchestrator/budget.py +195 -0
  15. orchestrator/checkpoint.py +248 -0
  16. orchestrator/cli.py +1971 -0
  17. orchestrator/codebase_introspector.py +66 -0
  18. orchestrator/component_slicer.py +185 -0
  19. orchestrator/config.py +152 -0
  20. orchestrator/contract.py +404 -0
  21. orchestrator/dag_validator.py +172 -0
  22. orchestrator/elasticity_governor.py +80 -0
  23. orchestrator/env_doctor.py +166 -0
  24. orchestrator/errors.py +211 -0
  25. orchestrator/events.py +120 -0
  26. orchestrator/evidence.py +203 -0
  27. orchestrator/exceptions.py +37 -0
  28. orchestrator/experimental/arena_arbiter.py +260 -0
  29. orchestrator/experimental/fuzz_engine.py +206 -0
  30. orchestrator/experimental/mutation_tester.py +382 -0
  31. orchestrator/failure.py +226 -0
  32. orchestrator/fast_sandbox.py +126 -0
  33. orchestrator/feasibility_gate.py +115 -0
  34. orchestrator/feedback.py +302 -0
  35. orchestrator/fixtures/__init__.py +0 -0
  36. orchestrator/fixtures/example_contract.json +50 -0
  37. orchestrator/fixtures/generated/evidence-cli-run-test-step-1.json +47 -0
  38. orchestrator/fixtures/generated/evidence-cli-run-test-step-2.json +47 -0
  39. orchestrator/fixtures/generated/evidence-inject-test-a.json +47 -0
  40. orchestrator/fixtures/generated/evidence-inject-test-b.json +47 -0
  41. orchestrator/fixtures/generated/evidence-inject-test-c.json +47 -0
  42. orchestrator/fixtures/generated/evidence-json-test-a.json +47 -0
  43. orchestrator/fixtures/generated/evidence-json-test-b.json +47 -0
  44. orchestrator/fixtures/generated/fail-report-fail-task-1.json +47 -0
  45. orchestrator/fixtures/generated/fail-report-json-task-1.json +47 -0
  46. orchestrator/fixtures/generated/fail-report-success-task-1.json +47 -0
  47. orchestrator/fixtures/generated/fuzz-engine-design.json +63 -0
  48. orchestrator/fixtures/generated/fuzz-engine-impl.json +62 -0
  49. orchestrator/fixtures/generated/fuzz-engine-tests.json +62 -0
  50. orchestrator/fixtures/generated/fuzz-engine-verify.json +62 -0
  51. orchestrator/fixtures/generated/goal-orch-step-1.json +63 -0
  52. orchestrator/fixtures/generated/goal-orch-step-2.json +62 -0
  53. orchestrator/fixtures/generated/goal-orch-step-3.json +62 -0
  54. orchestrator/fixtures/generated/goal-orch-step-4.json +62 -0
  55. orchestrator/fixtures/generated/goal-orch-step-5.json +62 -0
  56. orchestrator/fixtures/generated/goal-orch-step-6.json +63 -0
  57. orchestrator/fixtures/generated/implement-a-thread-safe-token-bucket-rat-task-1.json +53 -0
  58. orchestrator/fixtures/generated/orchestrator-checkpoint-rollback-3.json +63 -0
  59. orchestrator/fixtures/generated/orchestrator-checkpoint-rollback.json +62 -0
  60. orchestrator/fixtures/generated/orchestrator-live-telemetry-2.json +62 -0
  61. orchestrator/fixtures/generated/orchestrator-live-telemetry.json +62 -0
  62. orchestrator/fixtures/generated/orchestrator-spec-synthesis-1.json +62 -0
  63. orchestrator/fixtures/generated/orchestrator-spec-synthesis.json +62 -0
  64. orchestrator/fixtures/generated/orchestrator-test-verification-4.json +62 -0
  65. orchestrator/fixtures/generated/orchestrator-test-verification.json +62 -0
  66. orchestrator/fixtures/generated/perf-step-1.json +61 -0
  67. orchestrator/fixtures/generated/perf-step-2.json +62 -0
  68. orchestrator/fixtures/generated/perf-step-3.json +62 -0
  69. orchestrator/fixtures/generated/perf-step-4.json +62 -0
  70. orchestrator/fixtures/generated/perf-step-5.json +63 -0
  71. orchestrator/fixtures/generated/phase2-proof-two-step-step-1.json +47 -0
  72. orchestrator/fixtures/generated/phase2-proof-two-step-step-2.json +47 -0
  73. orchestrator/fixtures/generated/planner-spec-synthesis-impl.json +59 -0
  74. orchestrator/fixtures/generated/self-evolution-ast-formatter.json +69 -0
  75. orchestrator/fixtures/generated/self-evolution-checkpoint-rollback.json +70 -0
  76. orchestrator/fixtures/generated/self-evolution-spec-synthesis.json +70 -0
  77. orchestrator/fixtures/generated/self-evolution-step-1.json +70 -0
  78. orchestrator/fixtures/generated/self-evolution-step-2.json +70 -0
  79. orchestrator/fixtures/generated/self-evolution-step-3.json +70 -0
  80. orchestrator/fixtures/generated/self-evolution-step-4.json +70 -0
  81. orchestrator/fixtures/generated/self-evolution-step-5.json +65 -0
  82. orchestrator/fixtures/generated/self-evolution-telemetry.json +70 -0
  83. orchestrator/fixtures/generated/self-evolution-tests.json +71 -0
  84. orchestrator/fixtures/generated/spec-telemetry-research-design.json +64 -0
  85. orchestrator/fixtures/generated/spec-telemetry-step-1.json +62 -0
  86. orchestrator/fixtures/generated/spec-telemetry-step-2.json +62 -0
  87. orchestrator/fixtures/generated/spec-telemetry-step-3.json +62 -0
  88. orchestrator/fixtures/generated/spec-telemetry-step-4.json +62 -0
  89. orchestrator/fixtures/generated/spec-telemetry-step-5.json +62 -0
  90. orchestrator/fixtures/generated/spec-telemetry-verification.json +58 -0
  91. orchestrator/fixtures/generated/token-bucket-impl.json +69 -0
  92. orchestrator/fixtures/generated/token-bucket-step-1.json +70 -0
  93. orchestrator/fixtures/generated/token-bucket-step-2.json +70 -0
  94. orchestrator/fixtures/generated/token-bucket-step-3.json +60 -0
  95. orchestrator/fixtures/generated/token-bucket-tests.json +70 -0
  96. orchestrator/fixtures/generated/token-bucket-verify.json +61 -0
  97. orchestrator/fixtures/generated/trace-ux-tests-step-1.json +64 -0
  98. orchestrator/fixtures/generated/trace-ux-tests-step-2.json +64 -0
  99. orchestrator/fixtures/generated/trace-ux-tests-step-3.json +62 -0
  100. orchestrator/fixtures/generated/tui-live-telemetry-impl.json +59 -0
  101. orchestrator/fixtures/phase1_proof_escalation_contract.json +41 -0
  102. orchestrator/fixtures/phase1_proof_happy_path_contract.json +83 -0
  103. orchestrator/fixtures/phase1_proof_qc_contract.json +41 -0
  104. orchestrator/fixtures/phase1_proof_repair_contract.json +41 -0
  105. orchestrator/fixtures/phase2_proof_two_step_goal.json +15 -0
  106. orchestrator/fixtures/run_proofs.py +299 -0
  107. orchestrator/fixtures/test_normalizer.py +16 -0
  108. orchestrator/generator.py +239 -0
  109. orchestrator/goal.py +245 -0
  110. orchestrator/handoff.py +86 -0
  111. orchestrator/hybrid_worker.py +840 -0
  112. orchestrator/impossibility.py +162 -0
  113. orchestrator/limits.py +60 -0
  114. orchestrator/live_evolution_engine.py +247 -0
  115. orchestrator/llm.py +291 -0
  116. orchestrator/local_tool_calling.py +285 -0
  117. orchestrator/lock.py +404 -0
  118. orchestrator/mcp_client.py +571 -0
  119. orchestrator/mcp_server.py +344 -0
  120. orchestrator/memory_bridge.py +182 -0
  121. orchestrator/metrics.py +159 -0
  122. orchestrator/micro_epoch.py +42 -0
  123. orchestrator/models.py +350 -0
  124. orchestrator/parsing.py +237 -0
  125. orchestrator/patch_applier.py +154 -0
  126. orchestrator/plan_preview.py +138 -0
  127. orchestrator/plan_quality.py +357 -0
  128. orchestrator/planner.py +532 -0
  129. orchestrator/preferences.py +115 -0
  130. orchestrator/preflight.py +141 -0
  131. orchestrator/process_guard.py +357 -0
  132. orchestrator/prometheus_exporter.py +207 -0
  133. orchestrator/prompts.py +275 -0
  134. orchestrator/proposal_ledger.py +194 -0
  135. orchestrator/provenance.py +263 -0
  136. orchestrator/provider_scheduler.py +394 -0
  137. orchestrator/qc/__init__.py +153 -0
  138. orchestrator/qc/aggregator.py +330 -0
  139. orchestrator/qc/parsing.py +287 -0
  140. orchestrator/qc/personas.py +242 -0
  141. orchestrator/qc/runner.py +569 -0
  142. orchestrator/qc_overrule.py +87 -0
  143. orchestrator/qc_review.py +282 -0
  144. orchestrator/quality_lenses.py +314 -0
  145. orchestrator/quality_plan.py +449 -0
  146. orchestrator/quality_plane.py +103 -0
  147. orchestrator/reconcile.py +191 -0
  148. orchestrator/replanner.py +433 -0
  149. orchestrator/research.py +176 -0
  150. orchestrator/review_artifact.py +672 -0
  151. orchestrator/safety.py +271 -0
  152. orchestrator/schemas.py +230 -0
  153. orchestrator/scope.py +466 -0
  154. orchestrator/sensory_radar.py +79 -0
  155. orchestrator/skill_installer.py +140 -0
  156. orchestrator/sse_server.py +160 -0
  157. orchestrator/state.py +871 -0
  158. orchestrator/subprocess_helper.py +131 -0
  159. orchestrator/supervisor/__init__.py +184 -0
  160. orchestrator/supervisor/_shared.py +164 -0
  161. orchestrator/supervisor/cleanup.py +185 -0
  162. orchestrator/supervisor/core.py +1680 -0
  163. orchestrator/supervisor/recovery.py +367 -0
  164. orchestrator/supervisor/reporting.py +251 -0
  165. orchestrator/surgical_extractor.py +119 -0
  166. orchestrator/telemetry.py +61 -0
  167. orchestrator/templates.py +268 -0
  168. orchestrator/token_gate.py +245 -0
  169. orchestrator/tui.py +649 -0
  170. orchestrator/verifier.py +1103 -0
  171. orchestrator/webhooks.py +168 -0
  172. orchestrator/worker.py +469 -0
  173. orchestrator/worker_adapters.py +815 -0
  174. orchestrator/worker_pool.py +121 -0
  175. orchestrator/worktree.py +364 -0
@@ -0,0 +1,154 @@
1
+ """
2
+ orchestrator/patch_applier.py
3
+ Transactional Search/Replace Delta Patching Engine.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import difflib
9
+ import re
10
+ from dataclasses import dataclass
11
+ from typing import List, Optional
12
+
13
+
14
+ @dataclass
15
+ class PatchChunk:
16
+ search_block: str
17
+ replace_block: str
18
+ original_line_start: Optional[int] = None
19
+
20
+
21
+ @dataclass
22
+ class PatchResult:
23
+ success: bool
24
+ modified_content: str
25
+ diff_preview: str
26
+ chunks_applied: int
27
+ error_message: Optional[str] = None
28
+
29
+
30
+ class SearchReplacePatchParser:
31
+ """Parses and validates Aider-style Search/Replace blocks."""
32
+
33
+ SEARCH_RE = re.compile(
34
+ r"<{5,9}\s*SEARCH\s*\n(.*?)\n={5,9}\s*\n(.*?)\n>{5,9}\s*REPLACE",
35
+ re.DOTALL,
36
+ )
37
+
38
+ @classmethod
39
+ def parse_chunks(cls, raw_text: str) -> List[PatchChunk]:
40
+ chunks = []
41
+ for match in cls.SEARCH_RE.finditer(raw_text):
42
+ search_content = match.group(1)
43
+ replace_content = match.group(2)
44
+ chunks.append(PatchChunk(search_block=search_content, replace_block=replace_content))
45
+ return chunks
46
+
47
+
48
+ class PatchApplier:
49
+ """Applies Search/Replace delta chunks with EOL normalization, uniqueness, and atomicity."""
50
+
51
+ @staticmethod
52
+ def normalize_eol(text: str) -> str:
53
+ """Standardize all line endings to Unix LF."""
54
+ return text.replace("\r\n", "\n").replace("\r", "\n")
55
+
56
+ @classmethod
57
+ def apply_patch(
58
+ cls,
59
+ original_content: str,
60
+ patch_text: str,
61
+ fuzzy_whitespace: bool = True,
62
+ ) -> PatchResult:
63
+ chunks = SearchReplacePatchParser.parse_chunks(patch_text)
64
+ if not chunks:
65
+ return PatchResult(
66
+ success=False,
67
+ modified_content=original_content,
68
+ diff_preview="",
69
+ chunks_applied=0,
70
+ error_message="No valid <<<<<<< SEARCH ... ======= ... >>>>>>> REPLACE blocks found.",
71
+ )
72
+
73
+ norm_original = cls.normalize_eol(original_content)
74
+ current_content = norm_original
75
+ applied_count = 0
76
+
77
+ # Transactional verification: verify all chunks match uniquely before mutating
78
+ for i, chunk in enumerate(chunks, 1):
79
+ norm_search = cls.normalize_eol(chunk.search_block)
80
+ norm_replace = cls.normalize_eol(chunk.replace_block)
81
+
82
+ # Check occurrence count
83
+ count = current_content.count(norm_search)
84
+ if count == 0 and fuzzy_whitespace:
85
+ # Attempt fuzzy whitespace matching
86
+ matched_target = cls._fuzzy_find(current_content, norm_search)
87
+ if matched_target is None:
88
+ return PatchResult(
89
+ success=False,
90
+ modified_content=original_content,
91
+ diff_preview="",
92
+ chunks_applied=0,
93
+ error_message=f"Chunk {i} SEARCH block not found in target file.",
94
+ )
95
+ norm_search = matched_target
96
+ count = current_content.count(norm_search)
97
+
98
+ if count > 1:
99
+ return PatchResult(
100
+ success=False,
101
+ modified_content=original_content,
102
+ diff_preview="",
103
+ chunks_applied=0,
104
+ error_message=f"Ambiguous patch: Chunk {i} matches {count} locations. Expand SEARCH context.",
105
+ )
106
+
107
+ if count == 0:
108
+ return PatchResult(
109
+ success=False,
110
+ modified_content=original_content,
111
+ diff_preview="",
112
+ chunks_applied=0,
113
+ error_message=f"Chunk {i} SEARCH block not found in target file.",
114
+ )
115
+
116
+ # Apply single unique replacement
117
+ current_content = current_content.replace(norm_search, norm_replace, 1)
118
+ applied_count += 1
119
+
120
+ # Generate unified diff preview
121
+ diff = "".join(
122
+ difflib.unified_diff(
123
+ norm_original.splitlines(keepends=True),
124
+ current_content.splitlines(keepends=True),
125
+ fromfile="original",
126
+ tofile="modified",
127
+ n=3,
128
+ )
129
+ )
130
+
131
+ return PatchResult(
132
+ success=True,
133
+ modified_content=current_content,
134
+ diff_preview=diff,
135
+ chunks_applied=applied_count,
136
+ )
137
+
138
+ @classmethod
139
+ def _fuzzy_find(cls, haystack: str, needle: str) -> Optional[str]:
140
+ """Fuzzy match ignoring trailing whitespace and blank line discrepancies."""
141
+ haystack_lines = haystack.splitlines()
142
+ needle_lines = needle.splitlines()
143
+ if not needle_lines:
144
+ return None
145
+
146
+ n_len = len(needle_lines)
147
+ needle_stripped = [line.rstrip() for line in needle_lines]
148
+
149
+ for i in range(len(haystack_lines) - n_len + 1):
150
+ window = [haystack_lines[i + j].rstrip() for j in range(n_len)]
151
+ if window == needle_stripped:
152
+ # Return exact slice from haystack preserving original line endings
153
+ return "\n".join(haystack_lines[i : i + n_len])
154
+ return None
@@ -0,0 +1,138 @@
1
+ """Plan preview renderer — machine plan → human-readable markdown."""
2
+
3
+ from typing import Any, Dict, Optional
4
+
5
+ from .approval import format_approval_reasons, requires_approval
6
+ from .goal import Plan
7
+
8
+
9
+ def _describe_risk(plan: Plan) -> str:
10
+ """Classify plan risk."""
11
+ from .approval import _get_plan_stats
12
+
13
+ stats = _get_plan_stats(plan)
14
+ if stats["has_destructive"] or stats["touches_config"] > 0:
15
+ return "High"
16
+ if stats["touches_src"] > 0 or stats["touches_tests"] > 0 or stats["total"] > 3:
17
+ return "Medium"
18
+ return "Low"
19
+
20
+
21
+ def _contract_type_label(contract_dict: Dict[str, Any]) -> str:
22
+ worker = contract_dict.get("worker", {})
23
+ model = worker.get("model", "")
24
+ if model.startswith("hybrid:"):
25
+ return "code_generation (hybrid loop)"
26
+ from .llm import provider_of
27
+
28
+ return f"worker ({provider_of(model)})"
29
+
30
+
31
+ def render_plan_preview(
32
+ plan: Plan,
33
+ goal_dict: Optional[Dict[str, Any]] = None,
34
+ prefs: Optional[Dict[str, Any]] = None,
35
+ ) -> str:
36
+ """Render a Plan as a human-readable markdown preview."""
37
+ blocks = []
38
+ blocks.append("# Plan Preview")
39
+ blocks.append("")
40
+
41
+ # Goal
42
+ if goal_dict:
43
+ blocks.append("## Summary")
44
+ blocks.append("")
45
+ blocks.append(goal_dict.get("description", goal_dict.get("title", "")))
46
+ blocks.append("")
47
+
48
+ # Risk
49
+ risk = _describe_risk(plan)
50
+ blocks.append(f"**Risk:** {risk}")
51
+ blocks.append("")
52
+
53
+ # Approval
54
+ approval = requires_approval(plan, prefs=prefs)
55
+ if approval["requires_approval"]:
56
+ blocks.append("**Approval required:** Yes")
57
+ blocks.append("")
58
+ blocks.append(format_approval_reasons(approval))
59
+ else:
60
+ blocks.append("**Approval required:** No")
61
+ blocks.append("")
62
+
63
+ # Steps
64
+ blocks.append("## Steps")
65
+ blocks.append("")
66
+ for i, c in enumerate(plan.contracts, 1):
67
+ contract_dict = c.get("contract", {}) or {}
68
+ c.get("task_id", contract_dict.get("task_id", f"step-{i}"))
69
+ title = contract_dict.get("title", c.get("title", f"Step {i}"))
70
+ objective = contract_dict.get("objective", c.get("objective", ""))
71
+ worker = contract_dict.get("worker", c.get("worker", {}))
72
+ model = worker.get("model", "default")
73
+ outputs = contract_dict.get("outputs", c.get("outputs", []))
74
+ checks = contract_dict.get("acceptance_checks", c.get("acceptance_checks", []))
75
+ depends_on = c.get("depends_on", contract_dict.get("depends_on", []))
76
+ task_type_ = _contract_type_label(contract_dict)
77
+
78
+ blocks.append(f"### {i}. {title}")
79
+ blocks.append("")
80
+ blocks.append(f"**Type:** {task_type_}")
81
+ blocks.append(f"**Model:** {model}")
82
+ if depends_on:
83
+ blocks.append(f"**Depends on:** {', '.join(depends_on)}")
84
+ blocks.append("")
85
+ if objective:
86
+ blocks.append(objective)
87
+ blocks.append("")
88
+
89
+ if outputs:
90
+ blocks.append("**Outputs:**")
91
+ for out in outputs:
92
+ p = out.get("path", "") if isinstance(out, dict) else str(out)
93
+ blocks.append(f"- `{p}`")
94
+ blocks.append("")
95
+
96
+ if checks:
97
+ blocks.append("**Acceptance checks:**")
98
+ for ch in checks:
99
+ kind = ch.get("kind", "?")
100
+ desc = f"`{kind}`"
101
+ if "expected" in ch:
102
+ exp = ch["expected"]
103
+ desc += f" (expected: `{exp}`)" if not isinstance(exp, dict) else ""
104
+ if "path" in ch:
105
+ desc += f" on `{ch['path']}`"
106
+ blocks.append(f"- {desc}")
107
+ blocks.append("")
108
+
109
+ # Summary stats
110
+ blocks.append("---")
111
+ blocks.append("")
112
+ stats = _get_plan_stats_safe(plan)
113
+ blocks.append(f"**Total steps:** {stats['total']}")
114
+ blocks.append(f"**Files in src/:** {stats['touches_src']}")
115
+ blocks.append(f"**Files in tests/:** {stats['touches_tests']}")
116
+ blocks.append(f"**Files in scratch/:** {stats['touches_scratch']}")
117
+ blocks.append("")
118
+
119
+ return "\n".join(blocks)
120
+
121
+
122
+ def _get_plan_stats_safe(plan: Plan) -> Dict[str, int]:
123
+ from .approval import _get_plan_stats as gps
124
+
125
+ return gps(plan)
126
+
127
+
128
+ def write_plan_preview(
129
+ plan: Plan, output_path: str, goal_dict: Optional[Dict[str, Any]] = None, prefs: Optional[Dict[str, Any]] = None
130
+ ):
131
+ """Render and write plan preview to a file."""
132
+ content = render_plan_preview(plan, goal_dict=goal_dict, prefs=prefs)
133
+ import os
134
+
135
+ parent = os.path.dirname(output_path) or "."
136
+ os.makedirs(parent, exist_ok=True)
137
+ with open(output_path, "w", encoding="utf-8") as f:
138
+ f.write(content)
@@ -0,0 +1,357 @@
1
+ """Plan quality validation — catches low-quality or dangerous plan patterns."""
2
+
3
+ import os
4
+ import re
5
+ from typing import Dict, List
6
+
7
+ from .goal import Plan
8
+
9
+ PERMISSIVE_PATTERNS = [
10
+ r"\.\*", # regex match-all .*
11
+ r"^\.\+$", # regex non-empty match-all .+
12
+ r"^\.\+", # regex non-empty match-all .+ (without anchors)
13
+ r"True", # bare True as expected for file_exists (should be bool)
14
+ r"^$", # empty expected string
15
+ ]
16
+
17
+
18
+ class PlanQualityWarning:
19
+ """A single quality warning with severity."""
20
+
21
+ def __init__(self, message: str, severity: str = "warning", task_id: str = ""):
22
+ self.message = message
23
+ self.severity = severity # error or warning
24
+ self.task_id = task_id
25
+
26
+ def to_dict(self) -> Dict[str, str]:
27
+ return {"message": self.message, "severity": self.severity, "task_id": self.task_id}
28
+
29
+ def __repr__(self) -> str:
30
+ return f"[{self.severity.upper()}] {self.task_id}: {self.message}"
31
+
32
+
33
+ def check_plan_quality(plan: Plan, workspace_root: str = "") -> List[PlanQualityWarning]:
34
+ """Run all quality checks on a Plan. Returns list of warnings (empty = clean)."""
35
+ warnings = []
36
+ task_ids = set()
37
+
38
+ for c in plan.contracts:
39
+ tid = c.get("task_id", "")
40
+ if not tid:
41
+ warnings.append(PlanQualityWarning("contract missing task_id", severity="error"))
42
+ continue
43
+
44
+ # 1. Duplicate task_id check
45
+ if tid in task_ids:
46
+ warnings.append(PlanQualityWarning(f"duplicate task_id: {tid}", severity="error", task_id=tid))
47
+ task_ids.add(tid)
48
+
49
+ # 3. Permissive acceptance checks
50
+ contract_dict = c.get("contract", {}) or {}
51
+ checks = contract_dict.get("acceptance_checks", c.get("acceptance_checks", []))
52
+ if not checks:
53
+ warnings.append(
54
+ PlanQualityWarning(
55
+ "contract has no acceptance checks",
56
+ severity="warning",
57
+ task_id=tid,
58
+ )
59
+ )
60
+ for check in checks:
61
+ expected = check.get("expected", "")
62
+ if isinstance(expected, str) and any(re.search(p, expected) for p in PERMISSIVE_PATTERNS):
63
+ warnings.append(
64
+ PlanQualityWarning(
65
+ f"permissive acceptance check: {check.get('id', '?')} uses '{expected}'",
66
+ severity="warning",
67
+ task_id=tid,
68
+ )
69
+ )
70
+
71
+ # 4. Missing outputs
72
+ outputs = contract_dict.get("outputs", c.get("outputs", []))
73
+ if not outputs:
74
+ warnings.append(
75
+ PlanQualityWarning(
76
+ "contract has no outputs defined",
77
+ severity="error",
78
+ task_id=tid,
79
+ )
80
+ )
81
+
82
+ # 5. Scope check — output paths outside allowed scope
83
+ scope = contract_dict.get("workspace_scope", c.get("workspace_scope", {}))
84
+ allow_paths = scope.get("allow", [])
85
+ if allow_paths:
86
+ for out in outputs:
87
+ out_path = out.get("path", "") if isinstance(out, dict) else ""
88
+ if out_path and allow_paths:
89
+ allowed = any(
90
+ out_path.startswith(a.rstrip("/\\") + "/")
91
+ or out_path.startswith(a.rstrip("/\\") + "\\")
92
+ or out_path == a
93
+ for a in allow_paths
94
+ )
95
+ if not allowed:
96
+ warnings.append(
97
+ PlanQualityWarning(
98
+ f"output '{out_path}' not in allowed paths {allow_paths}",
99
+ severity="error",
100
+ task_id=tid,
101
+ )
102
+ )
103
+
104
+ # 5b. Empty or generic objective
105
+ objective = contract_dict.get("objective", c.get("objective", ""))
106
+ if not objective or not objective.strip():
107
+ warnings.append(
108
+ PlanQualityWarning(
109
+ "contract has empty objective",
110
+ severity="error",
111
+ task_id=tid,
112
+ )
113
+ )
114
+ generic_objectives = ["test", "implement", "implement feature", "do task", "execute"]
115
+ if objective.strip().lower() in generic_objectives:
116
+ warnings.append(
117
+ PlanQualityWarning(
118
+ f"generic objective: '{objective.strip()}'",
119
+ severity="warning",
120
+ task_id=tid,
121
+ )
122
+ )
123
+
124
+ # 6. Check dependency references exist
125
+ all_ids = set(c.get("task_id", "") for c in plan.contracts)
126
+ for c in plan.contracts:
127
+ tid = c.get("task_id", "")
128
+ for dep in c.get("depends_on", []):
129
+ if dep not in all_ids:
130
+ warnings.append(
131
+ PlanQualityWarning(
132
+ f"dependency '{dep}' does not exist in plan",
133
+ severity="error",
134
+ task_id=tid,
135
+ )
136
+ )
137
+ if dep == tid:
138
+ warnings.append(
139
+ PlanQualityWarning(
140
+ f"contract depends on itself: {tid}",
141
+ severity="error",
142
+ task_id=tid,
143
+ )
144
+ )
145
+
146
+ # 7. Maximum contracts check
147
+ if len(plan.contracts) > 5:
148
+ warnings.append(
149
+ PlanQualityWarning(
150
+ f"plan has {len(plan.contracts)} contracts (max recommended: 5)",
151
+ severity="warning",
152
+ )
153
+ )
154
+
155
+ # 8. Reject contracts where ALL checks are weak (.+ or .* regex only)
156
+ for c in plan.contracts:
157
+ tid = c.get("task_id", "")
158
+ contract_dict = c.get("contract", {}) or {}
159
+ checks = contract_dict.get("acceptance_checks", c.get("acceptance_checks", []))
160
+ outputs = contract_dict.get("outputs", c.get("outputs", []))
161
+ if checks and outputs:
162
+ weak_kinds = {"content_regex", "file_exists", "min_size"}
163
+ all_weak = all(
164
+ ch.get("kind") in weak_kinds and ch.get("expected", "") in (".+", ".*", True, 1) for ch in checks
165
+ )
166
+ is_scratch = all(out.get("path", "").startswith("scratch/") for out in outputs)
167
+ if all_weak and not is_scratch:
168
+ warnings.append(
169
+ PlanQualityWarning(
170
+ "all acceptance checks are weak for non-scratch outputs",
171
+ severity="error",
172
+ task_id=tid,
173
+ )
174
+ )
175
+
176
+ # 9. QC_required but no quality_spec
177
+ for c in plan.contracts:
178
+ tid = c.get("task_id", "")
179
+ contract_dict = c.get("contract", {}) or {}
180
+ qc = contract_dict.get("qc", c.get("qc", {}))
181
+ qs = contract_dict.get("quality_spec", c.get("quality_spec", {}))
182
+ if qc.get("required") and not qs:
183
+ outputs = contract_dict.get("outputs", c.get("outputs", []))
184
+ is_scratch = all(o.get("path", "").replace("\\", "/").startswith("scratch/") for o in outputs)
185
+ severity = "warning" if is_scratch else "error"
186
+ warnings.append(
187
+ PlanQualityWarning(
188
+ "QC required but no quality_spec defined",
189
+ severity=severity,
190
+ task_id=tid,
191
+ )
192
+ )
193
+
194
+ # 10. Empty acceptance checks on non-trivial tasks
195
+ for c in plan.contracts:
196
+ tid = c.get("task_id", "")
197
+ contract_dict = c.get("contract", {}) or {}
198
+ checks = contract_dict.get("acceptance_checks", c.get("acceptance_checks", []))
199
+ if not checks:
200
+ outputs = contract_dict.get("outputs", c.get("outputs", []))
201
+ is_scratch = all(o.get("path", "").replace("\\", "/").startswith("scratch/") for o in outputs)
202
+ if not is_scratch:
203
+ warnings.append(
204
+ PlanQualityWarning(
205
+ "no acceptance checks for non-scratch task",
206
+ severity="error",
207
+ task_id=tid,
208
+ )
209
+ )
210
+
211
+ # 11. Check paths that don't match any output path
212
+ for c in plan.contracts:
213
+ tid = c.get("task_id", "")
214
+ contract_dict = c.get("contract", {}) or {}
215
+ checks = contract_dict.get("acceptance_checks", c.get("acceptance_checks", []))
216
+ outputs = contract_dict.get("outputs", c.get("outputs", []))
217
+ output_paths = {o.get("path", "") for o in outputs}
218
+ for check in checks:
219
+ path = check.get("path", "")
220
+ if path and path not in output_paths and check.get("kind") not in ("command",):
221
+ warnings.append(
222
+ PlanQualityWarning(
223
+ f"check '{check.get('id', '?')}' path '{path}' does not match any output",
224
+ severity="warning",
225
+ task_id=tid,
226
+ )
227
+ )
228
+
229
+ # 12. Suspicious check parameters
230
+ for c in plan.contracts:
231
+ tid = c.get("task_id", "")
232
+ contract_dict = c.get("contract", {}) or {}
233
+ checks = contract_dict.get("acceptance_checks", c.get("acceptance_checks", []))
234
+ for check in checks:
235
+ kind = check.get("kind", "")
236
+ if kind == "min_size":
237
+ expected = check.get("expected", 0)
238
+ if isinstance(expected, (int, float)) and expected <= 0:
239
+ warnings.append(
240
+ PlanQualityWarning(
241
+ f"min_size expected={expected} is not positive",
242
+ severity="error",
243
+ task_id=tid,
244
+ )
245
+ )
246
+ elif kind == "command":
247
+ cmd = check.get("command", check.get("expected", ""))
248
+ if not cmd:
249
+ warnings.append(
250
+ PlanQualityWarning(
251
+ "command check has empty command",
252
+ severity="error",
253
+ task_id=tid,
254
+ )
255
+ )
256
+ elif kind == "syntax":
257
+ path = check.get("path", "")
258
+ if path:
259
+ ext = os.path.splitext(path)[1].lower()
260
+ if ext not in (
261
+ ".py",
262
+ ".js",
263
+ ".ts",
264
+ ".tsx",
265
+ ".jsx",
266
+ ".rs",
267
+ ".go",
268
+ ".java",
269
+ ".c",
270
+ ".cpp",
271
+ ".h",
272
+ ".hpp",
273
+ ".rb",
274
+ ".sh",
275
+ ".bat",
276
+ ".ps1",
277
+ ".json",
278
+ ".yaml",
279
+ ".yml",
280
+ ".toml",
281
+ ".xml",
282
+ ".html",
283
+ ".css",
284
+ ".scss",
285
+ ):
286
+ warnings.append(
287
+ PlanQualityWarning(
288
+ f"syntax check on path with unrecognized extension: {path}",
289
+ severity="warning",
290
+ task_id=tid,
291
+ )
292
+ )
293
+ elif kind == "required_sections":
294
+ sections = check.get("expected", [])
295
+ if isinstance(sections, list) and not sections:
296
+ warnings.append(
297
+ PlanQualityWarning(
298
+ "required_sections check with empty section list",
299
+ severity="warning",
300
+ task_id=tid,
301
+ )
302
+ )
303
+ elif kind == "render":
304
+ fmt = check.get("expected", "markdown")
305
+ supported = {"markdown", "html"}
306
+ if fmt not in supported:
307
+ warnings.append(
308
+ PlanQualityWarning(
309
+ f"render check with unsupported format: {fmt} (supported: {sorted(supported)})",
310
+ severity="warning",
311
+ task_id=tid,
312
+ )
313
+ )
314
+
315
+ # 13. quality_spec validation
316
+ for c in plan.contracts:
317
+ tid = c.get("task_id", "")
318
+ contract_dict = c.get("contract", {}) or {}
319
+ qs = contract_dict.get("quality_spec", c.get("quality_spec", {}))
320
+ if qs:
321
+ ms = qs.get("minimum_score")
322
+ if ms is not None and (not isinstance(ms, (int, float)) or ms < 0 or ms > 1):
323
+ warnings.append(
324
+ PlanQualityWarning(
325
+ f"quality_spec.minimum_score={ms} is outside valid range [0, 1]",
326
+ severity="error",
327
+ task_id=tid,
328
+ )
329
+ )
330
+ dims = qs.get("quality_dimensions", {})
331
+ if dims and isinstance(dims, dict):
332
+ total_weight = sum(v for v in dims.values() if isinstance(v, (int, float)))
333
+ if total_weight <= 0:
334
+ warnings.append(
335
+ PlanQualityWarning(
336
+ "quality_spec quality_dimensions weights sum to zero or negative",
337
+ severity="warning",
338
+ task_id=tid,
339
+ )
340
+ )
341
+
342
+ return warnings
343
+
344
+
345
+ def plan_is_safe(warnings: List[PlanQualityWarning]) -> bool:
346
+ """Return True if there are no error-severity issues."""
347
+ return all(w.severity != "error" for w in warnings)
348
+
349
+
350
+ def format_warnings(warnings: List[PlanQualityWarning]) -> str:
351
+ """Format warnings as a human-readable string."""
352
+ if not warnings:
353
+ return "Plan quality check passed — no issues found."
354
+ lines = [f"Plan quality: {len(warnings)} issue(s) found"]
355
+ for w in warnings:
356
+ lines.append(f" [{w.severity.upper()}] {w.task_id}: {w.message}")
357
+ return "\n".join(lines)