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.
- letitloop-0.2.0.dist-info/METADATA +232 -0
- letitloop-0.2.0.dist-info/RECORD +175 -0
- letitloop-0.2.0.dist-info/WHEEL +5 -0
- letitloop-0.2.0.dist-info/entry_points.txt +4 -0
- letitloop-0.2.0.dist-info/licenses/LICENSE +21 -0
- letitloop-0.2.0.dist-info/top_level.txt +1 -0
- orchestrator/SKILL.md +292 -0
- orchestrator/__init__.py +151 -0
- orchestrator/anti_ouroboros.py +78 -0
- orchestrator/approval.py +139 -0
- orchestrator/ast_node_splicer.py +130 -0
- orchestrator/ast_splicer.py +94 -0
- orchestrator/audit.py +88 -0
- orchestrator/budget.py +195 -0
- orchestrator/checkpoint.py +248 -0
- orchestrator/cli.py +1971 -0
- orchestrator/codebase_introspector.py +66 -0
- orchestrator/component_slicer.py +185 -0
- orchestrator/config.py +152 -0
- orchestrator/contract.py +404 -0
- orchestrator/dag_validator.py +172 -0
- orchestrator/elasticity_governor.py +80 -0
- orchestrator/env_doctor.py +166 -0
- orchestrator/errors.py +211 -0
- orchestrator/events.py +120 -0
- orchestrator/evidence.py +203 -0
- orchestrator/exceptions.py +37 -0
- orchestrator/experimental/arena_arbiter.py +260 -0
- orchestrator/experimental/fuzz_engine.py +206 -0
- orchestrator/experimental/mutation_tester.py +382 -0
- orchestrator/failure.py +226 -0
- orchestrator/fast_sandbox.py +126 -0
- orchestrator/feasibility_gate.py +115 -0
- orchestrator/feedback.py +302 -0
- orchestrator/fixtures/__init__.py +0 -0
- orchestrator/fixtures/example_contract.json +50 -0
- orchestrator/fixtures/generated/evidence-cli-run-test-step-1.json +47 -0
- orchestrator/fixtures/generated/evidence-cli-run-test-step-2.json +47 -0
- orchestrator/fixtures/generated/evidence-inject-test-a.json +47 -0
- orchestrator/fixtures/generated/evidence-inject-test-b.json +47 -0
- orchestrator/fixtures/generated/evidence-inject-test-c.json +47 -0
- orchestrator/fixtures/generated/evidence-json-test-a.json +47 -0
- orchestrator/fixtures/generated/evidence-json-test-b.json +47 -0
- orchestrator/fixtures/generated/fail-report-fail-task-1.json +47 -0
- orchestrator/fixtures/generated/fail-report-json-task-1.json +47 -0
- orchestrator/fixtures/generated/fail-report-success-task-1.json +47 -0
- orchestrator/fixtures/generated/fuzz-engine-design.json +63 -0
- orchestrator/fixtures/generated/fuzz-engine-impl.json +62 -0
- orchestrator/fixtures/generated/fuzz-engine-tests.json +62 -0
- orchestrator/fixtures/generated/fuzz-engine-verify.json +62 -0
- orchestrator/fixtures/generated/goal-orch-step-1.json +63 -0
- orchestrator/fixtures/generated/goal-orch-step-2.json +62 -0
- orchestrator/fixtures/generated/goal-orch-step-3.json +62 -0
- orchestrator/fixtures/generated/goal-orch-step-4.json +62 -0
- orchestrator/fixtures/generated/goal-orch-step-5.json +62 -0
- orchestrator/fixtures/generated/goal-orch-step-6.json +63 -0
- orchestrator/fixtures/generated/implement-a-thread-safe-token-bucket-rat-task-1.json +53 -0
- orchestrator/fixtures/generated/orchestrator-checkpoint-rollback-3.json +63 -0
- orchestrator/fixtures/generated/orchestrator-checkpoint-rollback.json +62 -0
- orchestrator/fixtures/generated/orchestrator-live-telemetry-2.json +62 -0
- orchestrator/fixtures/generated/orchestrator-live-telemetry.json +62 -0
- orchestrator/fixtures/generated/orchestrator-spec-synthesis-1.json +62 -0
- orchestrator/fixtures/generated/orchestrator-spec-synthesis.json +62 -0
- orchestrator/fixtures/generated/orchestrator-test-verification-4.json +62 -0
- orchestrator/fixtures/generated/orchestrator-test-verification.json +62 -0
- orchestrator/fixtures/generated/perf-step-1.json +61 -0
- orchestrator/fixtures/generated/perf-step-2.json +62 -0
- orchestrator/fixtures/generated/perf-step-3.json +62 -0
- orchestrator/fixtures/generated/perf-step-4.json +62 -0
- orchestrator/fixtures/generated/perf-step-5.json +63 -0
- orchestrator/fixtures/generated/phase2-proof-two-step-step-1.json +47 -0
- orchestrator/fixtures/generated/phase2-proof-two-step-step-2.json +47 -0
- orchestrator/fixtures/generated/planner-spec-synthesis-impl.json +59 -0
- orchestrator/fixtures/generated/self-evolution-ast-formatter.json +69 -0
- orchestrator/fixtures/generated/self-evolution-checkpoint-rollback.json +70 -0
- orchestrator/fixtures/generated/self-evolution-spec-synthesis.json +70 -0
- orchestrator/fixtures/generated/self-evolution-step-1.json +70 -0
- orchestrator/fixtures/generated/self-evolution-step-2.json +70 -0
- orchestrator/fixtures/generated/self-evolution-step-3.json +70 -0
- orchestrator/fixtures/generated/self-evolution-step-4.json +70 -0
- orchestrator/fixtures/generated/self-evolution-step-5.json +65 -0
- orchestrator/fixtures/generated/self-evolution-telemetry.json +70 -0
- orchestrator/fixtures/generated/self-evolution-tests.json +71 -0
- orchestrator/fixtures/generated/spec-telemetry-research-design.json +64 -0
- orchestrator/fixtures/generated/spec-telemetry-step-1.json +62 -0
- orchestrator/fixtures/generated/spec-telemetry-step-2.json +62 -0
- orchestrator/fixtures/generated/spec-telemetry-step-3.json +62 -0
- orchestrator/fixtures/generated/spec-telemetry-step-4.json +62 -0
- orchestrator/fixtures/generated/spec-telemetry-step-5.json +62 -0
- orchestrator/fixtures/generated/spec-telemetry-verification.json +58 -0
- orchestrator/fixtures/generated/token-bucket-impl.json +69 -0
- orchestrator/fixtures/generated/token-bucket-step-1.json +70 -0
- orchestrator/fixtures/generated/token-bucket-step-2.json +70 -0
- orchestrator/fixtures/generated/token-bucket-step-3.json +60 -0
- orchestrator/fixtures/generated/token-bucket-tests.json +70 -0
- orchestrator/fixtures/generated/token-bucket-verify.json +61 -0
- orchestrator/fixtures/generated/trace-ux-tests-step-1.json +64 -0
- orchestrator/fixtures/generated/trace-ux-tests-step-2.json +64 -0
- orchestrator/fixtures/generated/trace-ux-tests-step-3.json +62 -0
- orchestrator/fixtures/generated/tui-live-telemetry-impl.json +59 -0
- orchestrator/fixtures/phase1_proof_escalation_contract.json +41 -0
- orchestrator/fixtures/phase1_proof_happy_path_contract.json +83 -0
- orchestrator/fixtures/phase1_proof_qc_contract.json +41 -0
- orchestrator/fixtures/phase1_proof_repair_contract.json +41 -0
- orchestrator/fixtures/phase2_proof_two_step_goal.json +15 -0
- orchestrator/fixtures/run_proofs.py +299 -0
- orchestrator/fixtures/test_normalizer.py +16 -0
- orchestrator/generator.py +239 -0
- orchestrator/goal.py +245 -0
- orchestrator/handoff.py +86 -0
- orchestrator/hybrid_worker.py +840 -0
- orchestrator/impossibility.py +162 -0
- orchestrator/limits.py +60 -0
- orchestrator/live_evolution_engine.py +247 -0
- orchestrator/llm.py +291 -0
- orchestrator/local_tool_calling.py +285 -0
- orchestrator/lock.py +404 -0
- orchestrator/mcp_client.py +571 -0
- orchestrator/mcp_server.py +344 -0
- orchestrator/memory_bridge.py +182 -0
- orchestrator/metrics.py +159 -0
- orchestrator/micro_epoch.py +42 -0
- orchestrator/models.py +350 -0
- orchestrator/parsing.py +237 -0
- orchestrator/patch_applier.py +154 -0
- orchestrator/plan_preview.py +138 -0
- orchestrator/plan_quality.py +357 -0
- orchestrator/planner.py +532 -0
- orchestrator/preferences.py +115 -0
- orchestrator/preflight.py +141 -0
- orchestrator/process_guard.py +357 -0
- orchestrator/prometheus_exporter.py +207 -0
- orchestrator/prompts.py +275 -0
- orchestrator/proposal_ledger.py +194 -0
- orchestrator/provenance.py +263 -0
- orchestrator/provider_scheduler.py +394 -0
- orchestrator/qc/__init__.py +153 -0
- orchestrator/qc/aggregator.py +330 -0
- orchestrator/qc/parsing.py +287 -0
- orchestrator/qc/personas.py +242 -0
- orchestrator/qc/runner.py +569 -0
- orchestrator/qc_overrule.py +87 -0
- orchestrator/qc_review.py +282 -0
- orchestrator/quality_lenses.py +314 -0
- orchestrator/quality_plan.py +449 -0
- orchestrator/quality_plane.py +103 -0
- orchestrator/reconcile.py +191 -0
- orchestrator/replanner.py +433 -0
- orchestrator/research.py +176 -0
- orchestrator/review_artifact.py +672 -0
- orchestrator/safety.py +271 -0
- orchestrator/schemas.py +230 -0
- orchestrator/scope.py +466 -0
- orchestrator/sensory_radar.py +79 -0
- orchestrator/skill_installer.py +140 -0
- orchestrator/sse_server.py +160 -0
- orchestrator/state.py +871 -0
- orchestrator/subprocess_helper.py +131 -0
- orchestrator/supervisor/__init__.py +184 -0
- orchestrator/supervisor/_shared.py +164 -0
- orchestrator/supervisor/cleanup.py +185 -0
- orchestrator/supervisor/core.py +1680 -0
- orchestrator/supervisor/recovery.py +367 -0
- orchestrator/supervisor/reporting.py +251 -0
- orchestrator/surgical_extractor.py +119 -0
- orchestrator/telemetry.py +61 -0
- orchestrator/templates.py +268 -0
- orchestrator/token_gate.py +245 -0
- orchestrator/tui.py +649 -0
- orchestrator/verifier.py +1103 -0
- orchestrator/webhooks.py +168 -0
- orchestrator/worker.py +469 -0
- orchestrator/worker_adapters.py +815 -0
- orchestrator/worker_pool.py +121 -0
- orchestrator/worktree.py +364 -0
orchestrator/planner.py
ADDED
|
@@ -0,0 +1,532 @@
|
|
|
1
|
+
"""LLM-driven goal decomposer planner with rich preferences and hybrid routing."""
|
|
2
|
+
|
|
3
|
+
import copy
|
|
4
|
+
import hashlib
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
from typing import Any, Dict, List, Optional
|
|
9
|
+
|
|
10
|
+
from .contract import requires_semantic_qc, validate_contract
|
|
11
|
+
from .dag_validator import raise_if_invalid
|
|
12
|
+
from .exceptions import PlannerError
|
|
13
|
+
from .goal import Goal, Plan
|
|
14
|
+
from .llm import LLMError, call_llm
|
|
15
|
+
from .models import ModelRegistry
|
|
16
|
+
from .plan_quality import check_plan_quality, plan_is_safe
|
|
17
|
+
|
|
18
|
+
WORKER_MODEL = ModelRegistry.default_worker()
|
|
19
|
+
GENERATED_DIR = os.path.join("orchestrator", "fixtures", "generated")
|
|
20
|
+
|
|
21
|
+
HYBRID_MODEL = ModelRegistry.hybrid()
|
|
22
|
+
|
|
23
|
+
_ADVERSARIAL_SECTIONS = [
|
|
24
|
+
"Executive Verdict",
|
|
25
|
+
"System Map",
|
|
26
|
+
"Core Strengths",
|
|
27
|
+
"Critical Contradictions",
|
|
28
|
+
"Uncomfortable Truths",
|
|
29
|
+
"Failure Modes & Edge Cases",
|
|
30
|
+
"Concrete Schemas & Artifacts",
|
|
31
|
+
"Test Specifications",
|
|
32
|
+
"Alternative Architectures",
|
|
33
|
+
"90-Day Hardening Plan",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
_TASK_TYPE_TO_WORKER = {
|
|
37
|
+
"implementation": {"model": HYBRID_MODEL, "max_attempts": 3},
|
|
38
|
+
"code_generation": {"model": HYBRID_MODEL, "max_attempts": 3},
|
|
39
|
+
"research": {"model": WORKER_MODEL, "max_attempts": 2},
|
|
40
|
+
"verification": {"model": WORKER_MODEL, "max_attempts": 2},
|
|
41
|
+
"aggregation": {"model": WORKER_MODEL, "max_attempts": 2},
|
|
42
|
+
"adversarial_audit": {
|
|
43
|
+
"model": WORKER_MODEL,
|
|
44
|
+
"max_attempts": 3,
|
|
45
|
+
"quality_profile": "adversarial_architecture_audit",
|
|
46
|
+
},
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
_TASK_TYPE_CHECKS = {
|
|
50
|
+
"aggregation": lambda p: [
|
|
51
|
+
{"id": f"{p}-json", "kind": "json_schema", "path": "PLACEHOLDER", "expected": {}},
|
|
52
|
+
],
|
|
53
|
+
"adversarial_audit": lambda p: [
|
|
54
|
+
{"id": f"{p}-content", "kind": "content_regex", "path": "PLACEHOLDER", "expected": ".+"},
|
|
55
|
+
{"id": f"{p}-min_size", "kind": "min_size", "path": "PLACEHOLDER", "expected": 1000},
|
|
56
|
+
{"id": f"{p}-sections", "kind": "required_sections", "path": "PLACEHOLDER", "expected": _ADVERSARIAL_SECTIONS},
|
|
57
|
+
],
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _get_scope(goal: Goal) -> Dict[str, List[str]]:
|
|
62
|
+
constraints = goal.constraints
|
|
63
|
+
if "workspace_scope" in constraints and isinstance(constraints["workspace_scope"], dict):
|
|
64
|
+
scope = constraints["workspace_scope"]
|
|
65
|
+
return {
|
|
66
|
+
"allow": list(scope.get("allow", ["scratch/"])),
|
|
67
|
+
"deny": list(scope.get("deny", [])),
|
|
68
|
+
}
|
|
69
|
+
allow = constraints.get("allow", ["scratch/"])
|
|
70
|
+
deny = constraints.get("deny", [])
|
|
71
|
+
return {"allow": list(allow), "deny": list(deny)}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _preferences_block(goal: Goal) -> str:
|
|
75
|
+
"""Build a preferences section for the prompt.
|
|
76
|
+
|
|
77
|
+
Serializes the FULL _preferences structure — not just a hardcoded
|
|
78
|
+
whitelist. Known sections render as friendly bullets; arbitrary custom
|
|
79
|
+
key-value pairs (including dynamic risk thresholds) are preserved and
|
|
80
|
+
emitted generically so nothing is silently dropped.
|
|
81
|
+
"""
|
|
82
|
+
constraints = goal.constraints
|
|
83
|
+
prefs = constraints.get("_preferences", {})
|
|
84
|
+
if not prefs or not isinstance(prefs, dict):
|
|
85
|
+
return ""
|
|
86
|
+
lines = ["User preferences:"]
|
|
87
|
+
|
|
88
|
+
known_sections = {
|
|
89
|
+
"style": {
|
|
90
|
+
"minimal_changes": "Prefer minimal changes",
|
|
91
|
+
"keep_simple": "Keep implementation simple",
|
|
92
|
+
},
|
|
93
|
+
"safety": {
|
|
94
|
+
"never_delete_blindly": "Never delete files without asking",
|
|
95
|
+
"do_not_touch": "Do not touch protected files",
|
|
96
|
+
},
|
|
97
|
+
"verification": {
|
|
98
|
+
"run_tests": "Run tests after changes",
|
|
99
|
+
},
|
|
100
|
+
"planning": {
|
|
101
|
+
"approval_required_for_macro": "Require approval for macro tasks",
|
|
102
|
+
},
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
emitted = set()
|
|
106
|
+
|
|
107
|
+
def _render_value(value, indent: str = "") -> List[str]:
|
|
108
|
+
out = []
|
|
109
|
+
if isinstance(value, dict):
|
|
110
|
+
for k, v in value.items():
|
|
111
|
+
if isinstance(v, (dict, list)):
|
|
112
|
+
out.append(f"{indent}- {k}:")
|
|
113
|
+
out.extend(_render_value(v, indent + " "))
|
|
114
|
+
else:
|
|
115
|
+
out.append(f"{indent}- {k}: {v}")
|
|
116
|
+
elif isinstance(value, list):
|
|
117
|
+
for item in value:
|
|
118
|
+
if isinstance(item, (dict, list)):
|
|
119
|
+
out.append(f"{indent}- {_render_scalar(item)}")
|
|
120
|
+
else:
|
|
121
|
+
out.append(f"{indent}- {item}")
|
|
122
|
+
else:
|
|
123
|
+
out.append(f"{indent}- {value}")
|
|
124
|
+
return out
|
|
125
|
+
|
|
126
|
+
def _render_scalar(value) -> str:
|
|
127
|
+
if isinstance(value, (dict, list)):
|
|
128
|
+
return json.dumps(value, ensure_ascii=False)
|
|
129
|
+
return str(value)
|
|
130
|
+
|
|
131
|
+
for section, mapping in known_sections.items():
|
|
132
|
+
sec = prefs.get(section)
|
|
133
|
+
if not isinstance(sec, dict):
|
|
134
|
+
continue
|
|
135
|
+
for key, label in mapping.items():
|
|
136
|
+
if sec.get(key):
|
|
137
|
+
lines.append(f"- {label}")
|
|
138
|
+
emitted.add((section, key))
|
|
139
|
+
|
|
140
|
+
# Preserve any custom keys the whitelist doesn't know — risk thresholds,
|
|
141
|
+
# arbitrary key-value pairs, nested structures — so nothing is lost.
|
|
142
|
+
for section, sec in prefs.items():
|
|
143
|
+
if not isinstance(sec, dict):
|
|
144
|
+
lines.append(f"- {section}: {_render_scalar(sec)}")
|
|
145
|
+
continue
|
|
146
|
+
for key, value in sec.items():
|
|
147
|
+
if (section, key) in emitted:
|
|
148
|
+
continue
|
|
149
|
+
if isinstance(value, bool):
|
|
150
|
+
lines.append(f"- {key}: {value}")
|
|
151
|
+
elif isinstance(value, (dict, list)):
|
|
152
|
+
lines.append(f"- {section}.{key}:")
|
|
153
|
+
lines.extend(_render_value(value, " "))
|
|
154
|
+
else:
|
|
155
|
+
lines.append(f"- {section}.{key}: {value}")
|
|
156
|
+
|
|
157
|
+
lines.append("")
|
|
158
|
+
return "\n".join(lines)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _build_planner_prompt(goal: Goal) -> str:
|
|
162
|
+
prompt = (
|
|
163
|
+
"You are a task decomposition planner. "
|
|
164
|
+
"Given a high-level goal, break it down into 1-8 subtasks as executable contracts.\n"
|
|
165
|
+
f"Goal Title: {goal.title}\n"
|
|
166
|
+
f"Goal Description: {goal.description}\n"
|
|
167
|
+
f"Goal Constraints: {json.dumps(goal.constraints)}\n\n"
|
|
168
|
+
)
|
|
169
|
+
prefs_block = _preferences_block(goal)
|
|
170
|
+
if prefs_block:
|
|
171
|
+
prompt += prefs_block + "\n"
|
|
172
|
+
|
|
173
|
+
prompt += (
|
|
174
|
+
"Return ONLY valid JSON. No markdown, no extra text.\n\n"
|
|
175
|
+
"JSON format:\n"
|
|
176
|
+
"{\n"
|
|
177
|
+
' "summary": "One-line summary of the plan",\n'
|
|
178
|
+
' "contracts": [\n'
|
|
179
|
+
" {\n"
|
|
180
|
+
' "task_id": "goal-id-step-1",\n'
|
|
181
|
+
' "title": "Step 1: descriptive title",\n'
|
|
182
|
+
' "type": "implementation | code_generation | research | verification | aggregation | adversarial_audit",\n'
|
|
183
|
+
' "objective": "clear concrete objective for this step",\n'
|
|
184
|
+
' "output_path": "scratch/goal-id/step1_output.py",\n'
|
|
185
|
+
' "depends_on": [],\n'
|
|
186
|
+
' "acceptance_checks": [\n'
|
|
187
|
+
' {"id": "check-1", "kind": "content_regex", "path": "scratch/goal-id/step1_output.py", "expected": ".+"}\n'
|
|
188
|
+
" ],\n"
|
|
189
|
+
' "quality_spec": {\n'
|
|
190
|
+
' "required_sections": [],\n'
|
|
191
|
+
' "quality_dimensions": {"completeness": 0.5, "correctness": 0.5},\n'
|
|
192
|
+
' "hard_failures": [],\n'
|
|
193
|
+
' "minimum_score": 0.8\n'
|
|
194
|
+
" }\n"
|
|
195
|
+
" }\n"
|
|
196
|
+
" ]\n"
|
|
197
|
+
"}\n\n"
|
|
198
|
+
"Rules:\n"
|
|
199
|
+
"- For implementation/code_generation tasks, produce syntax-valid files\n"
|
|
200
|
+
"- Research tasks go to scratch/, implementation can go to src/ if appropriate\n"
|
|
201
|
+
"- Set quality_spec with required_sections, quality_dimensions, hard_failures, and minimum_score\n"
|
|
202
|
+
"- Use depends_on for ordering (e.g., inspection before implementation)\n"
|
|
203
|
+
"- Keep each step focused and concrete\n"
|
|
204
|
+
"- output_path must be within allowed workspace scope\n"
|
|
205
|
+
)
|
|
206
|
+
return prompt
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _extract_first_balanced_json_object(text: str) -> str:
|
|
210
|
+
"""Return the first brace-balanced JSON object, respecting JSON string literals."""
|
|
211
|
+
start = text.find("{")
|
|
212
|
+
if start < 0:
|
|
213
|
+
return ""
|
|
214
|
+
depth = 0
|
|
215
|
+
in_string = False
|
|
216
|
+
escaped = False
|
|
217
|
+
for index in range(start, len(text)):
|
|
218
|
+
char = text[index]
|
|
219
|
+
if in_string:
|
|
220
|
+
if escaped:
|
|
221
|
+
escaped = False
|
|
222
|
+
elif char == "\\":
|
|
223
|
+
escaped = True
|
|
224
|
+
elif char == '"':
|
|
225
|
+
in_string = False
|
|
226
|
+
continue
|
|
227
|
+
if char == '"':
|
|
228
|
+
in_string = True
|
|
229
|
+
elif char == "{":
|
|
230
|
+
depth += 1
|
|
231
|
+
elif char == "}":
|
|
232
|
+
depth -= 1
|
|
233
|
+
if depth == 0:
|
|
234
|
+
return text[start : index + 1]
|
|
235
|
+
return ""
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _all_balanced_json_objects(text: str) -> List[str]:
|
|
239
|
+
"""Yield every string-aware brace-balanced JSON object in order.
|
|
240
|
+
|
|
241
|
+
Unlike _extract_first_balanced_json_object, this scans past the first
|
|
242
|
+
object so a leading example JSON / schema block does not shadow the
|
|
243
|
+
actual plan. String literals are respected (a '{' inside a string value
|
|
244
|
+
must not corrupt the balance).
|
|
245
|
+
"""
|
|
246
|
+
results: List[str] = []
|
|
247
|
+
start = 0
|
|
248
|
+
while True:
|
|
249
|
+
start = text.find("{", start)
|
|
250
|
+
if start < 0:
|
|
251
|
+
break
|
|
252
|
+
depth = 0
|
|
253
|
+
in_string = False
|
|
254
|
+
escaped = False
|
|
255
|
+
for index in range(start, len(text)):
|
|
256
|
+
char = text[index]
|
|
257
|
+
if in_string:
|
|
258
|
+
if escaped:
|
|
259
|
+
escaped = False
|
|
260
|
+
elif char == "\\":
|
|
261
|
+
escaped = True
|
|
262
|
+
elif char == '"':
|
|
263
|
+
in_string = False
|
|
264
|
+
continue
|
|
265
|
+
if char == '"':
|
|
266
|
+
in_string = True
|
|
267
|
+
elif char == "{":
|
|
268
|
+
depth += 1
|
|
269
|
+
elif char == "}":
|
|
270
|
+
depth -= 1
|
|
271
|
+
if depth == 0:
|
|
272
|
+
results.append(text[start : index + 1])
|
|
273
|
+
start = index + 1
|
|
274
|
+
break
|
|
275
|
+
else:
|
|
276
|
+
break
|
|
277
|
+
return results
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _try_parse_plan_candidates(candidates: List[str]) -> Optional[Dict[str, Any]]:
|
|
281
|
+
"""Attempt json.loads on each candidate, preferring one shaped like a plan.
|
|
282
|
+
|
|
283
|
+
A leading ```json example/schema block must NOT shadow the actual plan:
|
|
284
|
+
among all parseable dicts with a non-empty 'contracts' list, the one with
|
|
285
|
+
the most contracts wins (ties go to the latest in order). Falls back to
|
|
286
|
+
the first parseable dict (e.g. a wrapped {plan: ...} schema), else None.
|
|
287
|
+
"""
|
|
288
|
+
first_dict: Optional[Dict[str, Any]] = None
|
|
289
|
+
best: Optional[Dict[str, Any]] = None
|
|
290
|
+
best_count = -1
|
|
291
|
+
for raw in candidates:
|
|
292
|
+
try:
|
|
293
|
+
data = json.loads(raw)
|
|
294
|
+
except (json.JSONDecodeError, TypeError):
|
|
295
|
+
continue
|
|
296
|
+
if not isinstance(data, dict):
|
|
297
|
+
continue
|
|
298
|
+
if first_dict is None:
|
|
299
|
+
first_dict = data
|
|
300
|
+
contracts = data.get("contracts")
|
|
301
|
+
if isinstance(contracts, list) and contracts:
|
|
302
|
+
count = len(contracts)
|
|
303
|
+
if count >= best_count:
|
|
304
|
+
best = data
|
|
305
|
+
best_count = count
|
|
306
|
+
return best if best is not None else first_dict
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _parse_llm_json(stdout: str) -> Dict[str, Any]:
|
|
310
|
+
if not stdout or not stdout.strip():
|
|
311
|
+
raise PlannerError("Empty output from LLM")
|
|
312
|
+
|
|
313
|
+
candidates: List[str] = []
|
|
314
|
+
|
|
315
|
+
# 1. Whole response as-is (common case: no markdown, pure JSON).
|
|
316
|
+
candidates.append(stdout.strip())
|
|
317
|
+
|
|
318
|
+
# 2. Each markdown fenced block, in order — a leading ```json example
|
|
319
|
+
# block must not capture the actual plan that follows.
|
|
320
|
+
fences = re.findall(r"```(?:json)?\s*(.*?)\s*```", stdout, re.DOTALL)
|
|
321
|
+
candidates.extend(f.strip() for f in fences if f.strip())
|
|
322
|
+
|
|
323
|
+
# 3. Every string-aware brace-balanced object, in order. The first object
|
|
324
|
+
# may be schema/example; the plan-bearing object wins via
|
|
325
|
+
# _try_parse_plan_candidates.
|
|
326
|
+
candidates.extend(_all_balanced_json_objects(stdout))
|
|
327
|
+
|
|
328
|
+
data = _try_parse_plan_candidates(candidates)
|
|
329
|
+
if data is None:
|
|
330
|
+
digest = hashlib.sha256(stdout.encode("utf-8", errors="replace")).hexdigest()[:8]
|
|
331
|
+
raise PlannerError(f"Failed to parse JSON from LLM response (raw_sha256={digest})")
|
|
332
|
+
|
|
333
|
+
if "contracts" not in data or not isinstance(data["contracts"], list):
|
|
334
|
+
raise PlannerError("LLM response JSON missing 'contracts' array")
|
|
335
|
+
if not data["contracts"]:
|
|
336
|
+
raise PlannerError("LLM returned empty contracts array")
|
|
337
|
+
return data
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def _call_llm_planner(prompt: str, workspace_root: str, timeout_sec: int = 120) -> str:
|
|
341
|
+
"""Call the generic LLM transport with the planner prompt with fail-closed semantics."""
|
|
342
|
+
if os.environ.get("FAKE_WORKER", ""):
|
|
343
|
+
timeout_sec = 1
|
|
344
|
+
try:
|
|
345
|
+
response = call_llm(prompt, ModelRegistry.default_worker(), timeout_s=timeout_sec)
|
|
346
|
+
return response["text"] or ""
|
|
347
|
+
except LLMError as e:
|
|
348
|
+
raise PlannerError(f"Planner LLM call failed: {e}")
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def _pick_worker(task_type: str) -> Dict[str, Any]:
|
|
352
|
+
"""Pick worker config based on task type."""
|
|
353
|
+
return dict(_TASK_TYPE_TO_WORKER.get(task_type, _TASK_TYPE_TO_WORKER["implementation"]))
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def _checks_for_output(task_type: str, output_path: str) -> List[Dict[str, Any]]:
|
|
357
|
+
"""Generate format-aware acceptance checks for an output path (AUT-007).
|
|
358
|
+
|
|
359
|
+
Checks must match the expected artifact format: json_schema for JSON,
|
|
360
|
+
required_sections/render for markdown, syntax+hygiene for Python.
|
|
361
|
+
"""
|
|
362
|
+
extension = os.path.splitext(output_path)[1].lower()
|
|
363
|
+
|
|
364
|
+
if task_type == "aggregation":
|
|
365
|
+
return _TASK_TYPE_CHECKS["aggregation"]("chk")
|
|
366
|
+
|
|
367
|
+
if extension == ".json":
|
|
368
|
+
return [
|
|
369
|
+
{"id": "chk-json", "kind": "json_schema", "path": "PLACEHOLDER", "expected": {}},
|
|
370
|
+
]
|
|
371
|
+
|
|
372
|
+
if extension == ".md":
|
|
373
|
+
if task_type == "adversarial_audit":
|
|
374
|
+
checks = _TASK_TYPE_CHECKS["adversarial_audit"]("chk")
|
|
375
|
+
checks.append({"id": "chk-render", "kind": "render", "path": "PLACEHOLDER", "expected": "markdown"})
|
|
376
|
+
return checks
|
|
377
|
+
return [
|
|
378
|
+
{"id": "chk-sections", "kind": "required_sections", "path": "PLACEHOLDER", "expected": []},
|
|
379
|
+
{"id": "chk-min_size", "kind": "min_size", "path": "PLACEHOLDER", "expected": 10},
|
|
380
|
+
{"id": "chk-render", "kind": "render", "path": "PLACEHOLDER", "expected": "markdown"},
|
|
381
|
+
]
|
|
382
|
+
|
|
383
|
+
if extension == ".py":
|
|
384
|
+
return [
|
|
385
|
+
{"id": "chk-syntax", "kind": "syntax", "path": "PLACEHOLDER"},
|
|
386
|
+
{"id": "chk-hygiene", "kind": "hygiene", "path": "PLACEHOLDER"},
|
|
387
|
+
{"id": "chk-min_size", "kind": "min_size", "path": "PLACEHOLDER", "expected": 10},
|
|
388
|
+
{"id": "chk-content", "kind": "content_regex", "path": "PLACEHOLDER", "expected": ".+"},
|
|
389
|
+
]
|
|
390
|
+
|
|
391
|
+
return [
|
|
392
|
+
{"id": "chk-min_size", "kind": "min_size", "path": "PLACEHOLDER", "expected": 1},
|
|
393
|
+
{"id": "chk-content", "kind": "content_regex", "path": "PLACEHOLDER", "expected": ".+"},
|
|
394
|
+
]
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def _pick_checks(task_type: str, output_path: str) -> List[Dict[str, Any]]:
|
|
398
|
+
"""Generate format-aware acceptance checks, filling in the output path."""
|
|
399
|
+
checks = []
|
|
400
|
+
for check in _checks_for_output(task_type, output_path):
|
|
401
|
+
entry = copy.deepcopy(check)
|
|
402
|
+
if entry.get("path") == "PLACEHOLDER":
|
|
403
|
+
entry["path"] = output_path
|
|
404
|
+
checks.append(entry)
|
|
405
|
+
return checks
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def decompose_goal(
|
|
409
|
+
goal: Goal,
|
|
410
|
+
workspace_root: str,
|
|
411
|
+
timeout_sec: int = 120,
|
|
412
|
+
prefs: Optional[Dict[str, Any]] = None,
|
|
413
|
+
) -> Plan:
|
|
414
|
+
"""Decompose a high-level Goal into subtask contracts via LLM with @file transport.
|
|
415
|
+
|
|
416
|
+
Generates contracts with:
|
|
417
|
+
- hybrid: workers for implementation/code_generation
|
|
418
|
+
- richer acceptance checks (syntax, hygiene, min_size)
|
|
419
|
+
- plan metadata (summary, approval info)
|
|
420
|
+
"""
|
|
421
|
+
goal.constraints = dict(goal.constraints)
|
|
422
|
+
goal.constraints["_preferences"] = prefs or {}
|
|
423
|
+
prompt = _build_planner_prompt(goal)
|
|
424
|
+
|
|
425
|
+
stdout = _call_llm_planner(prompt, workspace_root, timeout_sec)
|
|
426
|
+
llm_data = _parse_llm_json(stdout)
|
|
427
|
+
|
|
428
|
+
scope = _get_scope(goal)
|
|
429
|
+
out_dir = os.path.join(workspace_root, GENERATED_DIR)
|
|
430
|
+
os.makedirs(out_dir, exist_ok=True)
|
|
431
|
+
|
|
432
|
+
llm_data.get("summary", "")
|
|
433
|
+
contracts_plan_meta = []
|
|
434
|
+
|
|
435
|
+
for idx, raw_c in enumerate(llm_data["contracts"]):
|
|
436
|
+
if not isinstance(raw_c, dict):
|
|
437
|
+
raise PlannerError(f"Contract item {idx} is not a dict")
|
|
438
|
+
|
|
439
|
+
task_id = raw_c.get("task_id", f"{goal.goal_id}-step-{idx + 1}")
|
|
440
|
+
title = raw_c.get("title", f"Step {idx + 1}")
|
|
441
|
+
task_type = raw_c.get("type", "implementation")
|
|
442
|
+
objective = raw_c.get("objective", goal.description)
|
|
443
|
+
depends_on = raw_c.get("depends_on", [])
|
|
444
|
+
|
|
445
|
+
if task_type not in _TASK_TYPE_TO_WORKER:
|
|
446
|
+
task_type = "implementation"
|
|
447
|
+
|
|
448
|
+
if "outputs" in raw_c and isinstance(raw_c["outputs"], list) and raw_c["outputs"]:
|
|
449
|
+
outputs = raw_c["outputs"]
|
|
450
|
+
else:
|
|
451
|
+
output_path = raw_c.get("output_path", f"scratch/phase2/{goal.goal_id}_step{idx + 1}.txt")
|
|
452
|
+
outputs = [{"path": output_path}]
|
|
453
|
+
|
|
454
|
+
main_out = outputs[0]["path"] if outputs else "scratch/scratch.txt"
|
|
455
|
+
|
|
456
|
+
if "acceptance_checks" in raw_c and isinstance(raw_c["acceptance_checks"], list) and raw_c["acceptance_checks"]:
|
|
457
|
+
acceptance_checks = raw_c["acceptance_checks"]
|
|
458
|
+
else:
|
|
459
|
+
acceptance_checks = _pick_checks(task_type, main_out)
|
|
460
|
+
|
|
461
|
+
worker = _pick_worker(task_type)
|
|
462
|
+
worker["hybrid_critic_model"] = WORKER_MODEL
|
|
463
|
+
worker["hybrid_max_repair_turns"] = 3
|
|
464
|
+
worker["hybrid_max_tokens"] = 32000
|
|
465
|
+
worker["hybrid_max_cost_usd"] = 0.30
|
|
466
|
+
worker["hybrid_max_identical_verdicts"] = 2
|
|
467
|
+
|
|
468
|
+
risk_tier = goal.constraints.get("risk_tier", "auto")
|
|
469
|
+
quality_spec = raw_c.get("quality_spec", {})
|
|
470
|
+
if not quality_spec and requires_semantic_qc(risk_tier, outputs, acceptance_checks):
|
|
471
|
+
quality_spec = {
|
|
472
|
+
"required_sections": [],
|
|
473
|
+
"quality_dimensions": {"completeness": 0.5, "correctness": 0.5},
|
|
474
|
+
"hard_failures": [],
|
|
475
|
+
"minimum_score": 0.8,
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
qc_explicit = raw_c.get("qc", {}).get("required") if isinstance(raw_c.get("qc"), dict) else None
|
|
479
|
+
qc_semantic = requires_semantic_qc(risk_tier, outputs, acceptance_checks, quality_spec)
|
|
480
|
+
if qc_explicit is True:
|
|
481
|
+
qc_required = True
|
|
482
|
+
elif qc_explicit is False:
|
|
483
|
+
qc_required = qc_semantic
|
|
484
|
+
else:
|
|
485
|
+
qc_required = qc_semantic
|
|
486
|
+
|
|
487
|
+
contract_dict = {
|
|
488
|
+
"task_id": task_id,
|
|
489
|
+
"title": title,
|
|
490
|
+
"status": "DRAFTED",
|
|
491
|
+
"risk_tier": goal.constraints.get("risk_tier", "auto"),
|
|
492
|
+
"workspace_scope": scope,
|
|
493
|
+
"objective": objective,
|
|
494
|
+
"worker": worker,
|
|
495
|
+
"inputs": raw_c.get("inputs", []),
|
|
496
|
+
"outputs": outputs,
|
|
497
|
+
"acceptance_checks": acceptance_checks,
|
|
498
|
+
"quality_spec": quality_spec,
|
|
499
|
+
"qc": {"required": qc_required, "lens": "code_correctness"},
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
errors = validate_contract(contract_dict, workspace_root=workspace_root)
|
|
503
|
+
if errors:
|
|
504
|
+
raise PlannerError(f"Generated contract {task_id} failed validation: {errors}")
|
|
505
|
+
|
|
506
|
+
contract_file_path = os.path.join(out_dir, f"{task_id}.json")
|
|
507
|
+
with open(contract_file_path, "w", encoding="utf-8") as f:
|
|
508
|
+
json.dump(contract_dict, f, indent=2, ensure_ascii=False)
|
|
509
|
+
|
|
510
|
+
try:
|
|
511
|
+
rel_contract_path = os.path.relpath(contract_file_path, workspace_root)
|
|
512
|
+
except ValueError:
|
|
513
|
+
rel_contract_path = os.path.abspath(contract_file_path)
|
|
514
|
+
contracts_plan_meta.append(
|
|
515
|
+
{
|
|
516
|
+
"task_id": task_id,
|
|
517
|
+
"depends_on": depends_on,
|
|
518
|
+
"status": "DRAFTED",
|
|
519
|
+
"contract_path": rel_contract_path,
|
|
520
|
+
"contract": contract_dict,
|
|
521
|
+
"type": task_type,
|
|
522
|
+
"objective": objective,
|
|
523
|
+
}
|
|
524
|
+
)
|
|
525
|
+
|
|
526
|
+
plan = Plan(goal_id=goal.goal_id, contracts=contracts_plan_meta)
|
|
527
|
+
quality_warnings = check_plan_quality(plan, workspace_root=workspace_root)
|
|
528
|
+
if not plan_is_safe(quality_warnings):
|
|
529
|
+
error_msgs = [w.message for w in quality_warnings if w.severity == "error"]
|
|
530
|
+
raise PlannerError(f"Generated plan has quality errors: {'; '.join(error_msgs)}")
|
|
531
|
+
raise_if_invalid(plan.contracts)
|
|
532
|
+
return plan
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Preference collector — merges user prompt, project rules, and defaults."""
|
|
2
|
+
|
|
3
|
+
import copy
|
|
4
|
+
import os
|
|
5
|
+
from typing import Any, Dict, List, Optional
|
|
6
|
+
|
|
7
|
+
PROJECT_RULES_FILE = "AGENTS.md"
|
|
8
|
+
MEMORY_DIR = "memory"
|
|
9
|
+
BRAIN_FILE = os.path.join("memory", "BRAIN.md")
|
|
10
|
+
|
|
11
|
+
DEFAULT_PREFERENCES: Dict[str, Any] = {
|
|
12
|
+
"style": {
|
|
13
|
+
"minimal_changes": True,
|
|
14
|
+
"keep_simple": True,
|
|
15
|
+
"avoid_overengineering": True,
|
|
16
|
+
},
|
|
17
|
+
"safety": {
|
|
18
|
+
"never_delete_blindly": True,
|
|
19
|
+
"ask_before_destructive": True,
|
|
20
|
+
},
|
|
21
|
+
"verification": {
|
|
22
|
+
"run_tests": True,
|
|
23
|
+
"require_empirical_proof": True,
|
|
24
|
+
},
|
|
25
|
+
"planning": {
|
|
26
|
+
"approval_required_for_macro": True,
|
|
27
|
+
"approval_required_for_src_changes": True,
|
|
28
|
+
"approval_required_for_multi_file": True,
|
|
29
|
+
"max_contracts_before_approval": 2,
|
|
30
|
+
},
|
|
31
|
+
"deny_paths": ["AGENTS.md", "memory/", ".opencode/", ".claude/", ".agents/"],
|
|
32
|
+
"allow_paths": ["scratch/"],
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _try_read_lines(path: str, max_lines: int = 50) -> List[str]:
|
|
37
|
+
"""Read first max_lines lines of a file, return empty list on failure."""
|
|
38
|
+
if not os.path.isfile(path):
|
|
39
|
+
return []
|
|
40
|
+
try:
|
|
41
|
+
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
42
|
+
return [line.rstrip("\n") for _, line in zip(range(max_lines), f)]
|
|
43
|
+
except (OSError, UnicodeDecodeError):
|
|
44
|
+
return []
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def collect_preferences(
|
|
48
|
+
workspace_root: str,
|
|
49
|
+
user_hints: Optional[Dict[str, Any]] = None,
|
|
50
|
+
) -> Dict[str, Any]:
|
|
51
|
+
"""Collect and merge preferences from all sources.
|
|
52
|
+
|
|
53
|
+
Priority (highest wins):
|
|
54
|
+
1. explicit user_hints
|
|
55
|
+
2. project rules (AGENTS.md)
|
|
56
|
+
3. DEFAULT_PREFERENCES
|
|
57
|
+
"""
|
|
58
|
+
prefs = copy.deepcopy(DEFAULT_PREFERENCES)
|
|
59
|
+
|
|
60
|
+
# Source: AGENTS.md
|
|
61
|
+
agents_lines = _try_read_lines(os.path.join(workspace_root, PROJECT_RULES_FILE))
|
|
62
|
+
if agents_lines:
|
|
63
|
+
prefs["_sources"] = prefs.get("_sources", []) + ["AGENTS.md"]
|
|
64
|
+
for line in agents_lines:
|
|
65
|
+
low = line.lower()
|
|
66
|
+
if "never delete" in low:
|
|
67
|
+
prefs.setdefault("safety", {})["never_delete_blindly"] = True
|
|
68
|
+
if "do not touch" in low or "never commit" in low:
|
|
69
|
+
prefs.setdefault("safety", {})["do_not_touch"] = True
|
|
70
|
+
if "test" in low and ("run" in low or "pytest" in low):
|
|
71
|
+
prefs.setdefault("verification", {})["run_tests"] = True
|
|
72
|
+
if "scope" in low and ("allow" in low or "deny" in low):
|
|
73
|
+
pass
|
|
74
|
+
|
|
75
|
+
# Source: BRAIN.md scope·DECISIONS
|
|
76
|
+
brain_lines = _try_read_lines(os.path.join(workspace_root, BRAIN_FILE))
|
|
77
|
+
if brain_lines:
|
|
78
|
+
in_decisions = False
|
|
79
|
+
for line in brain_lines:
|
|
80
|
+
if "[SCOPE: DECISIONS]" in line:
|
|
81
|
+
in_decisions = True
|
|
82
|
+
continue
|
|
83
|
+
if in_decisions and line.startswith("#"):
|
|
84
|
+
break
|
|
85
|
+
if in_decisions and ":" in line:
|
|
86
|
+
k, _, v = line.partition(":")
|
|
87
|
+
prefs.setdefault("_brain_decisions", {})[k.strip()] = v.strip()
|
|
88
|
+
|
|
89
|
+
# Override with user hints
|
|
90
|
+
if user_hints:
|
|
91
|
+
for section in ("style", "safety", "verification", "planning"):
|
|
92
|
+
if section in user_hints:
|
|
93
|
+
prefs.setdefault(section, {}).update(user_hints[section])
|
|
94
|
+
if "deny_paths" in user_hints:
|
|
95
|
+
prefs["deny_paths"] = list(set(prefs.get("deny_paths", []) + user_hints["deny_paths"]))
|
|
96
|
+
if "allow_paths" in user_hints:
|
|
97
|
+
prefs["allow_paths"] = list(set(prefs.get("allow_paths", []) + user_hints["allow_paths"]))
|
|
98
|
+
|
|
99
|
+
return prefs
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def apply_preferences_to_goal(goal_dict: Dict[str, Any], prefs: Dict[str, Any]) -> Dict[str, Any]:
|
|
103
|
+
"""Merge preferences into a goal's constraints."""
|
|
104
|
+
constraints = goal_dict.get("constraints", {})
|
|
105
|
+
scope = constraints.get("workspace_scope", {})
|
|
106
|
+
if not scope:
|
|
107
|
+
scope = {"allow": [], "deny": []}
|
|
108
|
+
existing_allow = set(scope.get("allow", []))
|
|
109
|
+
existing_deny = set(scope.get("deny", []))
|
|
110
|
+
scope["allow"] = sorted(existing_allow | set(prefs.get("allow_paths", ["scratch/"])))
|
|
111
|
+
scope["deny"] = sorted(existing_deny | set(prefs.get("deny_paths", [])))
|
|
112
|
+
constraints["workspace_scope"] = scope
|
|
113
|
+
constraints["_preferences"] = {k: v for k, v in prefs.items() if not k.startswith("_")}
|
|
114
|
+
goal_dict["constraints"] = constraints
|
|
115
|
+
return goal_dict
|