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,119 @@
1
+ """
2
+ orchestrator/surgical_extractor.py
3
+ AST-driven Neighborhood Context Extractor.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import ast
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+ from typing import Dict, List, Optional, Tuple
12
+
13
+
14
+ @dataclass
15
+ class NeighborhoodContext:
16
+ target_node_id: str
17
+ target_name: str
18
+ target_type: str # 'function' | 'async_function' | 'method'
19
+ enclosing_class: Optional[str]
20
+ start_line: int
21
+ end_line: int
22
+ imports: List[str]
23
+ constants: Dict[str, str]
24
+ class_attributes: List[str]
25
+ target_source: str
26
+ file_path: str
27
+ full_module_loc: int
28
+
29
+
30
+ class SurgicalContextExtractor:
31
+ """Extracts bounded AST neighborhoods to prevent context starvation."""
32
+
33
+ def __init__(self, workspace_root: Path):
34
+ self.workspace_root = workspace_root
35
+
36
+ def extract(self, file_path: str, target_symbol: str) -> NeighborhoodContext:
37
+ full_path = (self.workspace_root / file_path).resolve()
38
+ source_code = full_path.read_text(encoding="utf-8", errors="replace")
39
+ tree = ast.parse(source_code, filename=str(full_path))
40
+ lines = source_code.splitlines(keepends=True)
41
+
42
+ imports = self._extract_imports(tree)
43
+ constants = self._extract_module_constants(tree, source_code)
44
+
45
+ target_node, enclosing_class = self._find_target(tree, target_symbol)
46
+ if not target_node:
47
+ raise ValueError(f"Symbol '{target_symbol}' not found in {file_path}")
48
+
49
+ class_attrs = []
50
+ if enclosing_class:
51
+ class_attrs = self._extract_class_context(enclosing_class, lines)
52
+
53
+ start_line = target_node.lineno
54
+ end_line = target_node.end_lineno
55
+ target_src = "".join(lines[start_line - 1 : end_line])
56
+
57
+ return NeighborhoodContext(
58
+ target_node_id=f"{file_path}::{target_symbol}",
59
+ target_name=target_symbol,
60
+ target_type="method"
61
+ if enclosing_class
62
+ else ("async_function" if isinstance(target_node, ast.AsyncFunctionDef) else "function"),
63
+ enclosing_class=enclosing_class.name if enclosing_class else None,
64
+ start_line=start_line,
65
+ end_line=end_line,
66
+ imports=imports,
67
+ constants=constants,
68
+ class_attributes=class_attrs,
69
+ target_source=target_src,
70
+ file_path=file_path,
71
+ full_module_loc=len(lines),
72
+ )
73
+
74
+ def _extract_imports(self, tree: ast.AST) -> List[str]:
75
+ imports = []
76
+ for node in ast.iter_child_nodes(tree):
77
+ if isinstance(node, ast.Import):
78
+ for alias in node.names:
79
+ imports.append(f"import {alias.name}")
80
+ elif isinstance(node, ast.ImportFrom):
81
+ module = node.module or ""
82
+ names = ", ".join(a.name for a in node.names)
83
+ imports.append(f"from {module} import {names}")
84
+ return imports
85
+
86
+ def _extract_module_constants(self, tree: ast.AST, source: str) -> Dict[str, str]:
87
+ constants = {}
88
+ for node in ast.iter_child_nodes(tree):
89
+ if isinstance(node, ast.Assign):
90
+ for target in node.targets:
91
+ if isinstance(target, ast.Name) and (target.id.isupper() or target.id.startswith("_")):
92
+ try:
93
+ val_src = ast.get_source_segment(source, node.value)
94
+ if val_src and len(val_src) < 200:
95
+ constants[target.id] = val_src
96
+ except Exception:
97
+ pass
98
+ return constants
99
+
100
+ def _find_target(self, tree: ast.AST, symbol_name: str) -> Tuple[Optional[ast.AST], Optional[ast.ClassDef]]:
101
+ for node in ast.iter_child_nodes(tree):
102
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == symbol_name:
103
+ return node, None
104
+ if isinstance(node, ast.ClassDef):
105
+ for sub in ast.iter_child_nodes(node):
106
+ if isinstance(sub, (ast.FunctionDef, ast.AsyncFunctionDef)) and sub.name == symbol_name:
107
+ return sub, node
108
+ return None, None
109
+
110
+ def _extract_class_context(self, class_node: ast.ClassDef, lines: List[str]) -> List[str]:
111
+ attrs = []
112
+ for sub in class_node.body:
113
+ if isinstance(sub, (ast.AnnAssign, ast.Assign)):
114
+ s = "".join(lines[sub.lineno - 1 : sub.end_lineno]).strip()
115
+ attrs.append(s)
116
+ elif isinstance(sub, ast.FunctionDef) and sub.name == "__init__":
117
+ s = "".join(lines[sub.lineno - 1 : sub.end_lineno]).strip()
118
+ attrs.append(s)
119
+ return attrs
@@ -0,0 +1,61 @@
1
+ """Lightweight telemetry collector — captures execution events to a local JSON log."""
2
+
3
+ import json
4
+ import os
5
+ from datetime import datetime, timezone
6
+ from typing import Any, Dict, List, Optional
7
+
8
+
9
+ def _log_path(run_dir: str) -> str:
10
+ return os.path.join(run_dir, "telemetry.jsonl")
11
+
12
+
13
+ def record_event(
14
+ run_dir: str,
15
+ event_type: str,
16
+ task_id: str = "",
17
+ goal_id: str = "",
18
+ payload: Optional[Dict[str, Any]] = None,
19
+ ) -> None:
20
+ """Append a telemetry event to the JSONL log."""
21
+ entry = {
22
+ "timestamp": datetime.now(timezone.utc).isoformat(),
23
+ "event_type": event_type,
24
+ "task_id": task_id,
25
+ "goal_id": goal_id,
26
+ "payload": payload or {},
27
+ }
28
+ os.makedirs(run_dir, exist_ok=True)
29
+ with open(_log_path(run_dir), "a", encoding="utf-8") as f:
30
+ f.write(json.dumps(entry, ensure_ascii=False) + "\n")
31
+
32
+
33
+ def load_events(run_dir: str) -> List[Dict[str, Any]]:
34
+ """Load all telemetry events from the log."""
35
+ path = _log_path(run_dir)
36
+ if not os.path.isfile(path):
37
+ return []
38
+ events = []
39
+ with open(path, "r", encoding="utf-8") as f:
40
+ for line in f:
41
+ line = line.strip()
42
+ if line:
43
+ try:
44
+ events.append(json.loads(line))
45
+ except json.JSONDecodeError:
46
+ pass
47
+ return events
48
+
49
+
50
+ def summarize(events: List[Dict[str, Any]]) -> str:
51
+ """Return a human-readable summary of telemetry events."""
52
+ if not events:
53
+ return "No telemetry events recorded."
54
+ by_type: Dict[str, int] = {}
55
+ for e in events:
56
+ et = e.get("event_type", "unknown")
57
+ by_type[et] = by_type.get(et, 0) + 1
58
+ lines = [f"Telemetry: {len(events)} events"]
59
+ for et, count in sorted(by_type.items()):
60
+ lines.append(f" {et}: {count}")
61
+ return "\n".join(lines)
@@ -0,0 +1,268 @@
1
+ """Contract template library — pre-built contract skeletons for common task types."""
2
+
3
+ from typing import Any, Dict, List
4
+
5
+ from .contract import requires_semantic_qc, validate_contract
6
+ from .models import ModelRegistry
7
+
8
+ _WORKER = ModelRegistry.WORKER_PREFIXED
9
+ _HYBRID = ModelRegistry.hybrid()
10
+ _HYBRID_CRITIC = ModelRegistry.WORKER_PREFIXED
11
+
12
+ _ADVERSARIAL_SECTIONS = [
13
+ "Executive Verdict",
14
+ "System Map",
15
+ "Core Strengths",
16
+ "Critical Contradictions",
17
+ "Uncomfortable Truths",
18
+ "Failure Modes & Edge Cases",
19
+ "Concrete Schemas & Artifacts",
20
+ "Test Specifications",
21
+ "Alternative Architectures",
22
+ "90-Day Hardening Plan",
23
+ ]
24
+
25
+ _ADVERSARIAL_DIMENSIONS = {
26
+ "analytical_depth": 0.25,
27
+ "contradiction_resolution": 0.15,
28
+ "actionability": 0.20,
29
+ "intellectual_courage": 0.15,
30
+ "edge_case_coverage": 0.10,
31
+ "writing_quality": 0.10,
32
+ "source_fidelity": 0.05,
33
+ }
34
+
35
+ TEMPLATES: Dict[str, Dict[str, Any]] = {
36
+ "research": {
37
+ "description": "Research / reconnaissance task — content check on output, low retry budget",
38
+ "defaults": {
39
+ "title": "Research: {objective}",
40
+ "status": "DRAFTED",
41
+ "risk_tier": "auto",
42
+ "workspace_scope": {"allow": ["scratch/"], "deny": []},
43
+ "worker": {"model": _WORKER, "max_attempts": 2},
44
+ "inputs": [],
45
+ "acceptance_checks": [
46
+ {"id": "{task_id}-content", "kind": "content_regex", "path": "{output_path}", "expected": ".+"},
47
+ ],
48
+ "qc": {"required": "auto", "lens": "code_correctness"},
49
+ },
50
+ "notes": "task_id, objective, outputs required. Two attempts — research LLM calls are nondeterministic; a retry budget absorbs transient worker slips.",
51
+ },
52
+ "implementation": {
53
+ "description": "Implementation task — hybrid LLM loop with critic + verifier, up to 5 turns",
54
+ "defaults": {
55
+ "title": "Implement: {objective}",
56
+ "status": "DRAFTED",
57
+ "risk_tier": "auto",
58
+ "workspace_scope": {"allow": ["scratch/"], "deny": []},
59
+ "worker": {
60
+ "model": _HYBRID,
61
+ "max_attempts": 3,
62
+ "hybrid_critic_model": _HYBRID_CRITIC,
63
+ "hybrid_max_repair_turns": 5,
64
+ "hybrid_max_tokens": 32000,
65
+ "hybrid_max_cost_usd": 0.30,
66
+ "hybrid_max_identical_verdicts": 3,
67
+ },
68
+ "inputs": [],
69
+ "acceptance_checks": [
70
+ {"id": "{task_id}-syntax", "kind": "syntax", "path": "{output_path}"},
71
+ {"id": "{task_id}-hygiene", "kind": "hygiene", "path": "{output_path}"},
72
+ {"id": "{task_id}-min_size", "kind": "min_size", "path": "{output_path}", "expected": 10},
73
+ {"id": "{task_id}-content", "kind": "content_regex", "path": "{output_path}", "expected": ".+"},
74
+ ],
75
+ "qc": {"required": "auto", "lens": "code_correctness"},
76
+ },
77
+ "notes": "task_id, objective, outputs required. Hybrid loop: implementer → verifier → critic → repair. Supports `hybrid:` model prefix for bounded LLM loop.",
78
+ },
79
+ "verification": {
80
+ "description": "Verification task — checks upstream output exists, single shot",
81
+ "defaults": {
82
+ "title": "Verify: {objective}",
83
+ "status": "DRAFTED",
84
+ "risk_tier": "auto",
85
+ "workspace_scope": {"allow": ["scratch/"], "deny": []},
86
+ "worker": {"model": _WORKER, "max_attempts": 2},
87
+ "inputs": [],
88
+ "acceptance_checks": [
89
+ {"id": "{task_id}-regex", "kind": "content_regex", "path": "{output_path}", "expected": ".*"},
90
+ ],
91
+ "qc": {"required": "auto", "lens": "code_correctness"},
92
+ },
93
+ "notes": "task_id, objective, outputs required. Depend on upstream task for input.",
94
+ },
95
+ "aggregation": {
96
+ "description": "Aggregation task — merges upstream outputs into JSON",
97
+ "defaults": {
98
+ "title": "Aggregate: {objective}",
99
+ "status": "DRAFTED",
100
+ "risk_tier": "auto",
101
+ "workspace_scope": {"allow": ["scratch/"], "deny": []},
102
+ "worker": {"model": _WORKER, "max_attempts": 2},
103
+ "inputs": [],
104
+ "acceptance_checks": [
105
+ {"id": "{task_id}-json", "kind": "json_schema", "path": "{output_path}", "expected": {}},
106
+ ],
107
+ "qc": {"required": "auto", "lens": "code_correctness"},
108
+ },
109
+ "notes": "task_id, objective, outputs required. Expects JSON output.",
110
+ },
111
+ "code_generation": {
112
+ "description": "Code generation task — hybrid LLM loop with critic + verifier, writes source files",
113
+ "defaults": {
114
+ "title": "Generate: {objective}",
115
+ "status": "DRAFTED",
116
+ "risk_tier": "auto",
117
+ "workspace_scope": {"allow": ["scratch/", "src/"], "deny": ["AGENTS.md", "memory/", ".opencode/"]},
118
+ "worker": {
119
+ "model": _HYBRID,
120
+ "max_attempts": 3,
121
+ "hybrid_critic_model": _HYBRID_CRITIC,
122
+ "hybrid_max_repair_turns": 5,
123
+ "hybrid_max_tokens": 32000,
124
+ "hybrid_max_cost_usd": 0.30,
125
+ "hybrid_max_identical_verdicts": 3,
126
+ },
127
+ "inputs": [],
128
+ "acceptance_checks": [
129
+ {"id": "{task_id}-syntax", "kind": "syntax", "path": "{output_path}"},
130
+ {"id": "{task_id}-hygiene", "kind": "hygiene", "path": "{output_path}"},
131
+ {"id": "{task_id}-min_size", "kind": "min_size", "path": "{output_path}", "expected": 10},
132
+ {"id": "{task_id}-content", "kind": "content_regex", "path": "{output_path}", "expected": ".+"},
133
+ ],
134
+ "qc": {"required": "auto", "lens": "code_correctness"},
135
+ },
136
+ "notes": "task_id, objective, outputs required. Custom scope includes src/. Hybrid loop with verifier + critic.",
137
+ },
138
+ "adversarial_audit": {
139
+ "description": "Adversarial architecture audit — deep critical review with contradiction detection, edge case enumeration, concrete schemas, and implementation-ready recommendations",
140
+ "defaults": {
141
+ "title": "Architecture Audit: {objective}",
142
+ "status": "DRAFTED",
143
+ "risk_tier": "qc_required",
144
+ "workspace_scope": {"allow": ["scratch/"], "deny": []},
145
+ "worker": {
146
+ "model": _WORKER,
147
+ "max_attempts": 3,
148
+ "quality_profile": "adversarial_architecture_audit",
149
+ },
150
+ "inputs": [],
151
+ "acceptance_checks": [
152
+ {"id": "{task_id}-content", "kind": "content_regex", "path": "{output_path}", "expected": ".+"},
153
+ {"id": "{task_id}-min_size", "kind": "min_size", "path": "{output_path}", "expected": 1000},
154
+ {
155
+ "id": "{task_id}-sections",
156
+ "kind": "required_sections",
157
+ "path": "{output_path}",
158
+ "expected": list(_ADVERSARIAL_SECTIONS),
159
+ },
160
+ {"id": "{task_id}-render", "kind": "render", "path": "{output_path}", "expected": "markdown"},
161
+ ],
162
+ "quality_spec": {
163
+ "required_sections": list(_ADVERSARIAL_SECTIONS),
164
+ "quality_dimensions": _ADVERSARIAL_DIMENSIONS,
165
+ "hard_failures": [
166
+ "no_contradictions",
167
+ "no_edge_cases",
168
+ "no_schemas",
169
+ "no_alternative_architecture",
170
+ "no_uncomfortable_truths",
171
+ ],
172
+ "minimum_score": 0.85,
173
+ "minimum_counts": {
174
+ "contradictions": 5,
175
+ "edge_cases": 20,
176
+ "test_specs": 10,
177
+ "schemas": 3,
178
+ "radical_alternatives": 1,
179
+ },
180
+ },
181
+ "qc": {"required": "auto", "lens": "architecture_audit"},
182
+ },
183
+ "notes": "task_id, objective, outputs required. Aggressive QC with dimensional scoring. Worker must be adversarial — reject summaries, demand original thinking.",
184
+ },
185
+ }
186
+
187
+
188
+ def list_templates() -> List[str]:
189
+ return list(TEMPLATES.keys())
190
+
191
+
192
+ def template_details(name: str) -> Dict[str, Any]:
193
+ if name not in TEMPLATES:
194
+ raise ValueError(f"unknown template: {name!r}")
195
+ t = TEMPLATES[name]
196
+ return {"name": name, "description": t["description"], "defaults": dict(t["defaults"]), "notes": t["notes"]}
197
+
198
+
199
+ def apply_template(name: str, overrides: Dict[str, Any]) -> Dict[str, Any]:
200
+ if name not in TEMPLATES:
201
+ raise ValueError(f"unknown template: {name!r}")
202
+ t = TEMPLATES[name]
203
+ defaults = dict(t["defaults"])
204
+
205
+ task_id = overrides.get("task_id")
206
+ objective = overrides.get("objective")
207
+ outputs = overrides.get("outputs")
208
+ if not task_id:
209
+ raise ValueError("overrides must include 'task_id'")
210
+ if not objective:
211
+ raise ValueError("overrides must include 'objective'")
212
+ if not outputs:
213
+ raise ValueError("overrides must include 'outputs' (list of path dicts)")
214
+
215
+ out_path = outputs[0]["path"] if isinstance(outputs[0], dict) else str(outputs[0])
216
+
217
+ max_depth = 50
218
+
219
+ def _subst(v, _depth=0, _visited=None):
220
+ if _depth > max_depth:
221
+ raise ValueError(f"template substitution exceeded max depth ({max_depth}) — possible circular reference")
222
+ if _visited is None:
223
+ _visited = set()
224
+ obj_id = id(v)
225
+ if obj_id in _visited:
226
+ raise ValueError("circular reference detected in template substitution")
227
+ if isinstance(v, (dict, list)):
228
+ _visited.add(obj_id)
229
+ if isinstance(v, str):
230
+ return v.replace("{task_id}", task_id).replace("{objective}", objective).replace("{output_path}", out_path)
231
+ if isinstance(v, list):
232
+ result = [_subst(item, _depth + 1, _visited) for item in v]
233
+ return result
234
+ if isinstance(v, dict):
235
+ result = {kk: _subst(vv, _depth + 1, _visited) for kk, vv in v.items()}
236
+ return result
237
+ return v
238
+
239
+ def _deep_merge(base: dict, override: dict) -> dict:
240
+ merged = dict(base)
241
+ for k, v in override.items():
242
+ if k in merged and isinstance(merged[k], dict) and isinstance(v, dict):
243
+ merged[k] = _deep_merge(merged[k], v)
244
+ else:
245
+ merged[k] = v
246
+ return merged
247
+
248
+ contract = _subst(defaults)
249
+
250
+ for k, v in overrides.items():
251
+ if k in ("task_id", "objective", "outputs"):
252
+ contract[k] = v
253
+ elif k in defaults and isinstance(v, dict) and isinstance(contract.get(k), dict):
254
+ contract[k] = _deep_merge(contract[k], v)
255
+ else:
256
+ contract[k] = v
257
+
258
+ if contract.get("qc", {}).get("required") == "auto":
259
+ risk_tier = contract.get("risk_tier", "auto")
260
+ outputs = contract.get("outputs", [])
261
+ checks = contract.get("acceptance_checks", [])
262
+ contract["qc"]["required"] = requires_semantic_qc(risk_tier, outputs, checks)
263
+
264
+ errs = validate_contract(contract)
265
+ if errs:
266
+ raise ValueError(f"generated contract failed validation: {errs}")
267
+
268
+ return contract