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/webhooks.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""Webhook delivery for orchestrator events — signed HTTP POSTs via urllib."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import hmac
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
import threading
|
|
9
|
+
import urllib.request
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from typing import Any, Callable, Dict, List, Optional
|
|
12
|
+
|
|
13
|
+
from .events import EVENT_TYPES, EventBus
|
|
14
|
+
|
|
15
|
+
ENV_WEBHOOKS_JSON = "LETITLOOP_WEBHOOKS_JSON"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def sign_payload(body: bytes, secret: str) -> str:
|
|
19
|
+
"""Return the HMAC-SHA256 hex digest of body keyed by secret."""
|
|
20
|
+
return hmac.new(secret.encode("utf-8"), body, hashlib.sha256).hexdigest()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class WebhookConfig:
|
|
25
|
+
"""A single webhook endpoint configuration."""
|
|
26
|
+
|
|
27
|
+
url: str
|
|
28
|
+
secret: Optional[str] = None
|
|
29
|
+
events: Optional[List[str]] = None
|
|
30
|
+
timeout: float = 5.0
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class WebhookDispatcher:
|
|
34
|
+
"""Delivers event envelopes to configured webhook endpoints."""
|
|
35
|
+
|
|
36
|
+
DEFAULT_MAX_CONCURRENT = 16
|
|
37
|
+
|
|
38
|
+
def __init__(
|
|
39
|
+
self,
|
|
40
|
+
webhooks: List[WebhookConfig],
|
|
41
|
+
max_concurrent: int = DEFAULT_MAX_CONCURRENT,
|
|
42
|
+
) -> None:
|
|
43
|
+
self.webhooks = list(webhooks)
|
|
44
|
+
cap = max(1, int(max_concurrent))
|
|
45
|
+
self._capacity = cap
|
|
46
|
+
self._slots = threading.BoundedSemaphore(cap)
|
|
47
|
+
self.dropped_count = 0
|
|
48
|
+
|
|
49
|
+
def dispatch(self, event_type: str, envelope: Dict[str, Any]) -> None:
|
|
50
|
+
"""Fire matching webhook deliveries asynchronously; never raises or blocks.
|
|
51
|
+
|
|
52
|
+
When the concurrent-delivery cap is saturated the delivery is skipped
|
|
53
|
+
and counted (``dropped_count``) instead of spawning unbounded threads.
|
|
54
|
+
"""
|
|
55
|
+
body = json.dumps(envelope, ensure_ascii=False).encode("utf-8")
|
|
56
|
+
for config in self.webhooks:
|
|
57
|
+
if config.events is not None and event_type not in config.events:
|
|
58
|
+
continue
|
|
59
|
+
if not self._slots.acquire(blocking=False):
|
|
60
|
+
self.dropped_count += 1
|
|
61
|
+
print(
|
|
62
|
+
f"[webhooks] delivery saturated - dropping {event_type} -> {config.url}"
|
|
63
|
+
f" (dropped_total={self.dropped_count})",
|
|
64
|
+
file=sys.stderr,
|
|
65
|
+
)
|
|
66
|
+
continue
|
|
67
|
+
thread = threading.Thread(
|
|
68
|
+
target=self._deliver,
|
|
69
|
+
args=(config, body, event_type),
|
|
70
|
+
daemon=True,
|
|
71
|
+
)
|
|
72
|
+
thread.start()
|
|
73
|
+
|
|
74
|
+
def _deliver(self, config: WebhookConfig, body: bytes, event_type: str) -> None:
|
|
75
|
+
try:
|
|
76
|
+
self._post(config, body, event_type)
|
|
77
|
+
finally:
|
|
78
|
+
try:
|
|
79
|
+
self._slots.release()
|
|
80
|
+
except ValueError:
|
|
81
|
+
pass
|
|
82
|
+
|
|
83
|
+
def _post(self, config: WebhookConfig, body: bytes, event_type: str) -> None:
|
|
84
|
+
try:
|
|
85
|
+
headers = {
|
|
86
|
+
"Content-Type": "application/json",
|
|
87
|
+
"X-LetItLoop-Event": event_type,
|
|
88
|
+
}
|
|
89
|
+
if config.secret:
|
|
90
|
+
headers["X-LetItLoop-Signature"] = "sha256=" + sign_payload(body, config.secret)
|
|
91
|
+
req = urllib.request.Request(config.url, data=body, headers=headers)
|
|
92
|
+
with urllib.request.urlopen(req, timeout=config.timeout) as resp: # nosec B310
|
|
93
|
+
resp.read()
|
|
94
|
+
except Exception as exc:
|
|
95
|
+
print(f"[webhooks] delivery to {config.url} failed: {exc}", file=sys.stderr)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def attach_webhooks(bus: EventBus, dispatcher: WebhookDispatcher) -> Callable[[], None]:
|
|
99
|
+
"""Subscribe dispatcher.dispatch on the bus for all known event types.
|
|
100
|
+
|
|
101
|
+
Returns an unsubscribe callable that detaches every registration.
|
|
102
|
+
"""
|
|
103
|
+
unsubs = []
|
|
104
|
+
for et in EVENT_TYPES:
|
|
105
|
+
|
|
106
|
+
def make_callback(event_type=et):
|
|
107
|
+
def cb(envelope: Dict[str, Any]) -> None:
|
|
108
|
+
dispatcher.dispatch(event_type, envelope)
|
|
109
|
+
|
|
110
|
+
return cb
|
|
111
|
+
|
|
112
|
+
unsubs.append(bus.subscribe(make_callback(), event_type=et))
|
|
113
|
+
|
|
114
|
+
def detach() -> None:
|
|
115
|
+
for unsub in unsubs:
|
|
116
|
+
unsub()
|
|
117
|
+
|
|
118
|
+
return detach
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def load_webhook_configs(path: str) -> List[WebhookConfig]:
|
|
122
|
+
"""Load webhook configs from a JSON list file; missing file yields []."""
|
|
123
|
+
if not path or not os.path.isfile(path):
|
|
124
|
+
return []
|
|
125
|
+
try:
|
|
126
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
127
|
+
raw = json.load(f)
|
|
128
|
+
except (OSError, ValueError) as exc:
|
|
129
|
+
print(f"[webhooks] failed to read {path}: {exc}", file=sys.stderr)
|
|
130
|
+
return []
|
|
131
|
+
if not isinstance(raw, list):
|
|
132
|
+
print(f"[webhooks] {path}: expected a JSON list", file=sys.stderr)
|
|
133
|
+
return []
|
|
134
|
+
configs: List[WebhookConfig] = []
|
|
135
|
+
for entry in raw:
|
|
136
|
+
config = _parse_config(entry)
|
|
137
|
+
if config is None:
|
|
138
|
+
print(f"[webhooks] skipping invalid webhook entry: {entry!r}", file=sys.stderr)
|
|
139
|
+
else:
|
|
140
|
+
configs.append(config)
|
|
141
|
+
return configs
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _parse_config(entry: Any) -> Optional[WebhookConfig]:
|
|
145
|
+
if not isinstance(entry, dict):
|
|
146
|
+
return None
|
|
147
|
+
url = entry.get("url")
|
|
148
|
+
if not isinstance(url, str) or not url.strip():
|
|
149
|
+
return None
|
|
150
|
+
events = entry.get("events")
|
|
151
|
+
if events is not None and not isinstance(events, list):
|
|
152
|
+
return None
|
|
153
|
+
secret = entry.get("secret")
|
|
154
|
+
try:
|
|
155
|
+
timeout = float(entry.get("timeout", 5.0))
|
|
156
|
+
except (TypeError, ValueError):
|
|
157
|
+
return None
|
|
158
|
+
return WebhookConfig(
|
|
159
|
+
url=url,
|
|
160
|
+
secret=secret if isinstance(secret, str) and secret else None,
|
|
161
|
+
events=[str(e) for e in events] if events is not None else None,
|
|
162
|
+
timeout=timeout,
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def load_webhook_configs_from_env() -> List[WebhookConfig]:
|
|
167
|
+
"""Load webhook configs from the path named by LETITLOOP_WEBHOOKS_JSON, if set."""
|
|
168
|
+
return load_webhook_configs(os.environ.get(ENV_WEBHOOKS_JSON, ""))
|
orchestrator/worker.py
ADDED
|
@@ -0,0 +1,469 @@
|
|
|
1
|
+
"""Worker adapter: invokes a generic LLM with contract-derived brief."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
import sys
|
|
7
|
+
import time
|
|
8
|
+
|
|
9
|
+
from .llm import LLMError, call_llm
|
|
10
|
+
from .models import ModelRegistry
|
|
11
|
+
from .token_gate import TokenGateError, preflight
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _safe_stderr(msg):
|
|
15
|
+
try:
|
|
16
|
+
print(msg, file=sys.stderr, flush=True)
|
|
17
|
+
except OSError:
|
|
18
|
+
pass
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
DEFAULT_MODEL = ModelRegistry.FALLBACK
|
|
22
|
+
|
|
23
|
+
MAX_OUTPUT_SIZE = 512 * 1024 # 512KB cap on captured output
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _build_brief(contract, previous_failures=None, changed_approach=None):
|
|
27
|
+
"""Build a zero-context bounded brief from contract and optional failure context.
|
|
28
|
+
|
|
29
|
+
Returns a string ready to pass to the model as the worker prompt.
|
|
30
|
+
"""
|
|
31
|
+
allow_paths = "; ".join(sorted(contract.allowed_paths()))
|
|
32
|
+
deny_paths = "; ".join(sorted(contract.denied_paths()))
|
|
33
|
+
scratch_dir = contract.workspace_scope.get("scratch_dir", "")
|
|
34
|
+
|
|
35
|
+
lines = [
|
|
36
|
+
f"Task: {contract.title}",
|
|
37
|
+
f"Objective: {contract.objective}",
|
|
38
|
+
"",
|
|
39
|
+
"Allowed paths (write scope):",
|
|
40
|
+
f" {allow_paths}" if allow_paths else " (none)",
|
|
41
|
+
"",
|
|
42
|
+
"Forbidden paths:",
|
|
43
|
+
f" {deny_paths}" if deny_paths else " (none)",
|
|
44
|
+
"",
|
|
45
|
+
]
|
|
46
|
+
if scratch_dir:
|
|
47
|
+
lines.extend(
|
|
48
|
+
[
|
|
49
|
+
"Scratch/temp directory (write helpers here, not in production paths):",
|
|
50
|
+
f" {scratch_dir}",
|
|
51
|
+
"",
|
|
52
|
+
]
|
|
53
|
+
)
|
|
54
|
+
lines.append("Required outputs:")
|
|
55
|
+
for out in contract.outputs:
|
|
56
|
+
lines.append(f" - {out['path']}")
|
|
57
|
+
lines.append("")
|
|
58
|
+
|
|
59
|
+
quality_spec = getattr(contract, "quality_spec", {})
|
|
60
|
+
if quality_spec:
|
|
61
|
+
lines.append("QUALITY SPECIFICATION (you will be judged on these):")
|
|
62
|
+
if quality_spec.get("required_sections"):
|
|
63
|
+
lines.append(
|
|
64
|
+
f" Required sections (must include ALL as markdown headings ##): {quality_spec['required_sections']}"
|
|
65
|
+
)
|
|
66
|
+
lines.append(
|
|
67
|
+
" - You MUST include a distinct section heading (e.g. ## Section Title) for EVERY required section above."
|
|
68
|
+
)
|
|
69
|
+
lines.append(" - Be concise and focused so no required sections are omitted or truncated.")
|
|
70
|
+
if quality_spec.get("quality_dimensions"):
|
|
71
|
+
lines.append(f" Quality dimensions: {json.dumps(quality_spec['quality_dimensions'])}")
|
|
72
|
+
if quality_spec.get("hard_failures"):
|
|
73
|
+
lines.append(f" Hard failures (must avoid): {quality_spec['hard_failures']}")
|
|
74
|
+
if quality_spec.get("minimum_score"):
|
|
75
|
+
lines.append(f" Minimum quality score: {quality_spec['minimum_score']}")
|
|
76
|
+
if quality_spec.get("minimum_counts"):
|
|
77
|
+
lines.append(f" Minimum content counts: {json.dumps(quality_spec['minimum_counts'])}")
|
|
78
|
+
lines.append(" Every claim must include specific source file citations (file name + section).")
|
|
79
|
+
lines.append("")
|
|
80
|
+
|
|
81
|
+
quality_profile = contract.worker.get("quality_profile", "")
|
|
82
|
+
if quality_profile == "adversarial_architecture_audit":
|
|
83
|
+
lines.append("ADVERSARIAL ARCHITECTURE AUDIT MODE:")
|
|
84
|
+
lines.append("- You are a SENIOR SYSTEMS ARCHITECT. Do NOT write a consulting-style summary.")
|
|
85
|
+
lines.append(
|
|
86
|
+
"- Your job is to CHALLENGE the system. Find contradictions, hidden assumptions, and over-engineering."
|
|
87
|
+
)
|
|
88
|
+
lines.append("- Disagree with the source where it is wrong, overstated, or internally inconsistent.")
|
|
89
|
+
lines.append(
|
|
90
|
+
"- Generate concrete implementation artifacts not present in the source (JSON schemas, risk tables, test plans)."
|
|
91
|
+
)
|
|
92
|
+
lines.append(
|
|
93
|
+
"- Enumerate specific edge case scenarios with mitigation strategies — not just categories, actual scenarios."
|
|
94
|
+
)
|
|
95
|
+
lines.append(
|
|
96
|
+
"- Propose at least one radically simpler alternative architecture that challenges the current design."
|
|
97
|
+
)
|
|
98
|
+
lines.append(
|
|
99
|
+
"- Produce implementable recommendations: each must target a specific file/module with an implementation shape."
|
|
100
|
+
)
|
|
101
|
+
lines.append("- Include a 90-day hardening plan with clear definitions of done per phase.")
|
|
102
|
+
lines.append("- If the source claims something the reviewer does not have evidence for, say so directly.")
|
|
103
|
+
lines.append("- 'Uncomfortable Truths' is a required section — write it honestly, do not soften the analysis.")
|
|
104
|
+
lines.append("")
|
|
105
|
+
|
|
106
|
+
lines.append("Acceptance criteria:")
|
|
107
|
+
for check in contract.acceptance_checks:
|
|
108
|
+
lines.append(f" - [{check['kind']}] {check.get('command', check.get('path', check['id']))}")
|
|
109
|
+
if "expected" in check:
|
|
110
|
+
lines.append(f" expected: {check['expected']}")
|
|
111
|
+
lines.append("")
|
|
112
|
+
lines.append("CONSTRAINTS:")
|
|
113
|
+
lines.append("- Output ONLY the raw content of the required output file inside a single ``` fenced code block.")
|
|
114
|
+
lines.append("- Do NOT output conversational preambles, summaries, or postambles outside the code block.")
|
|
115
|
+
lines.append("- Only modify files under the allowed paths above.")
|
|
116
|
+
lines.append("- Do NOT modify AGENTS.md, memory/, .opencode/, or global configs.")
|
|
117
|
+
lines.append("- Do NOT run git commands, deploy, publish, or access external APIs.")
|
|
118
|
+
lines.append("- Do NOT print secrets or credentials.")
|
|
119
|
+
lines.append("- Write all outputs to the paths listed above.")
|
|
120
|
+
lines.append("- Do NOT claim completion without producing all output files.")
|
|
121
|
+
lines.append("- Do NOT create any files beyond the Required outputs listed above.")
|
|
122
|
+
lines.append("- Do NOT produce self-verification, self-review, or self-assessment reports.")
|
|
123
|
+
|
|
124
|
+
quality_profile = contract.worker.get("quality_profile", "")
|
|
125
|
+
if quality_profile == "adversarial_architecture_audit":
|
|
126
|
+
input_paths = getattr(contract, "inputs", [])
|
|
127
|
+
if input_paths:
|
|
128
|
+
lines.append("")
|
|
129
|
+
lines.append("INPUT FILES TO ANALYZE (read these via your MCP tools):")
|
|
130
|
+
for inp in input_paths:
|
|
131
|
+
if isinstance(inp, dict):
|
|
132
|
+
path = inp.get("path", "")
|
|
133
|
+
else:
|
|
134
|
+
path = str(inp)
|
|
135
|
+
if path:
|
|
136
|
+
full = os.path.abspath(path) if not os.path.isabs(path) else path
|
|
137
|
+
if os.path.isfile(full):
|
|
138
|
+
try:
|
|
139
|
+
with open(full, "r", encoding="utf-8", errors="replace") as f:
|
|
140
|
+
content = f.read()
|
|
141
|
+
lines.append(f" {path} ({len(content)} bytes)")
|
|
142
|
+
lines.append(" First 3000 chars preview:")
|
|
143
|
+
lines.append(content[:3000])
|
|
144
|
+
if len(content) > 3000:
|
|
145
|
+
lines.append(" [... truncated, read the full file with MCP tools ...]")
|
|
146
|
+
except OSError as e:
|
|
147
|
+
lines.append(f" {path} (read error: {e})")
|
|
148
|
+
|
|
149
|
+
if previous_failures:
|
|
150
|
+
lines.append("")
|
|
151
|
+
lines.append("PREVIOUS ATTEMPT FAILED.")
|
|
152
|
+
lines.append("Failure evidence:")
|
|
153
|
+
for fail in previous_failures:
|
|
154
|
+
lines.append(f" - {fail.get('message', '')}")
|
|
155
|
+
if changed_approach:
|
|
156
|
+
lines.append("")
|
|
157
|
+
lines.append("REQUIRED: You MUST use a structurally different approach.")
|
|
158
|
+
lines.append(f"Changed approach required: {changed_approach}")
|
|
159
|
+
lines.append("The previous approach is not acceptable. Do something different.")
|
|
160
|
+
|
|
161
|
+
lines.append("")
|
|
162
|
+
lines.append("[CONTEXT_COMPLETE]")
|
|
163
|
+
|
|
164
|
+
return "\n".join(lines)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _cap_output(text, max_size=MAX_OUTPUT_SIZE):
|
|
168
|
+
if text and len(text) > max_size:
|
|
169
|
+
head_size = max_size // 2
|
|
170
|
+
tail_size = max_size - head_size
|
|
171
|
+
truncated_count = len(text) - (head_size + tail_size)
|
|
172
|
+
return text[:head_size] + f"\n... [{truncated_count} chars truncated] ...\n" + text[-tail_size:]
|
|
173
|
+
return text or ""
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _strip_code_fences(text):
|
|
177
|
+
"""Extract code block content or strip surrounding markdown code fences."""
|
|
178
|
+
text = (text or "").strip()
|
|
179
|
+
if not text:
|
|
180
|
+
return text
|
|
181
|
+
match = re.search(r"```(?:[a-zA-Z0-9_\-]+)?\s*\n(.*?)\n```", text, re.DOTALL)
|
|
182
|
+
if match:
|
|
183
|
+
return match.group(1).strip()
|
|
184
|
+
lines = text.splitlines()
|
|
185
|
+
if lines and lines[0].startswith("```"):
|
|
186
|
+
lines = lines[1:]
|
|
187
|
+
if lines and lines[-1].startswith("```"):
|
|
188
|
+
lines = lines[:-1]
|
|
189
|
+
return "\n".join(lines).strip()
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _materialize_outputs(contract, workspace_root, stdout):
|
|
193
|
+
"""Persist the worker's text response into the contract's declared output
|
|
194
|
+
paths so chat-completion workers can produce artifacts like CLI workers.
|
|
195
|
+
|
|
196
|
+
Supports both structured multi-file payloads ([{"path": ..., "content": ...}])
|
|
197
|
+
and single-file fenced code blocks.
|
|
198
|
+
"""
|
|
199
|
+
written = []
|
|
200
|
+
expected_paths = [
|
|
201
|
+
o.get("path", "") for o in getattr(contract, "outputs", []) if isinstance(o, dict) and o.get("path")
|
|
202
|
+
]
|
|
203
|
+
try:
|
|
204
|
+
from .hybrid_parser import parse_llm_artifacts
|
|
205
|
+
|
|
206
|
+
parse_res = parse_llm_artifacts(stdout, expected_paths)
|
|
207
|
+
if parse_res.ok and parse_res.artifacts:
|
|
208
|
+
for art in parse_res.artifacts:
|
|
209
|
+
full_path = os.path.join(workspace_root, art.path) if not os.path.isabs(art.path) else art.path
|
|
210
|
+
try:
|
|
211
|
+
os.makedirs(os.path.dirname(full_path), exist_ok=True)
|
|
212
|
+
with open(full_path, "w", encoding="utf-8") as f:
|
|
213
|
+
f.write(art.content)
|
|
214
|
+
written.append(full_path)
|
|
215
|
+
except OSError as e:
|
|
216
|
+
_safe_stderr(f"[worker] could not write artifact {art.path}: {e}")
|
|
217
|
+
if written:
|
|
218
|
+
return written
|
|
219
|
+
except Exception:
|
|
220
|
+
pass
|
|
221
|
+
|
|
222
|
+
clean_content = _strip_code_fences(stdout)
|
|
223
|
+
for out in getattr(contract, "outputs", []):
|
|
224
|
+
if not isinstance(out, dict) or not out.get("path"):
|
|
225
|
+
continue
|
|
226
|
+
out_path = out["path"]
|
|
227
|
+
full_path = os.path.join(workspace_root, out_path) if not os.path.isabs(out_path) else out_path
|
|
228
|
+
try:
|
|
229
|
+
os.makedirs(os.path.dirname(full_path), exist_ok=True)
|
|
230
|
+
with open(full_path, "w", encoding="utf-8") as f:
|
|
231
|
+
f.write(clean_content)
|
|
232
|
+
written.append(full_path)
|
|
233
|
+
except OSError as e:
|
|
234
|
+
_safe_stderr(f"[worker] could not materialize output {out_path}: {e}")
|
|
235
|
+
return written
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _run_llm_worker(
|
|
239
|
+
contract, workspace_root, run_dir, model, previous_failures=None, changed_approach=None, timeout_sec=900
|
|
240
|
+
):
|
|
241
|
+
"""Invoke the generic LLM transport with a contract-derived brief."""
|
|
242
|
+
task_id = contract.task_id
|
|
243
|
+
_safe_stderr(f"[worker] task={task_id} starting (model={model})")
|
|
244
|
+
|
|
245
|
+
brief = _build_brief(contract, previous_failures, changed_approach)
|
|
246
|
+
|
|
247
|
+
os.makedirs(run_dir, exist_ok=True)
|
|
248
|
+
brief_path = os.path.join(run_dir, "worker_brief.txt")
|
|
249
|
+
with open(brief_path, "w", encoding="utf-8") as f:
|
|
250
|
+
f.write(brief)
|
|
251
|
+
|
|
252
|
+
start = time.time()
|
|
253
|
+
try:
|
|
254
|
+
preflight(len(brief), None, caller=f"worker:{task_id}")
|
|
255
|
+
response = call_llm(brief, model, timeout_s=timeout_sec)
|
|
256
|
+
stdout = _cap_output(response["text"])
|
|
257
|
+
stderr = ""
|
|
258
|
+
exit_code = 0
|
|
259
|
+
except TokenGateError as e:
|
|
260
|
+
stdout = ""
|
|
261
|
+
stderr = str(e)
|
|
262
|
+
exit_code = 1
|
|
263
|
+
except LLMError as e:
|
|
264
|
+
elapsed = time.time() - start
|
|
265
|
+
_safe_stderr(f"[worker] task={task_id} model error: {e}")
|
|
266
|
+
return {
|
|
267
|
+
"success": False,
|
|
268
|
+
"stdout": "",
|
|
269
|
+
"stderr": str(e),
|
|
270
|
+
"exit_code": -1,
|
|
271
|
+
"elapsed_sec": elapsed,
|
|
272
|
+
"artifact_paths": [brief_path],
|
|
273
|
+
}
|
|
274
|
+
except Exception as e:
|
|
275
|
+
elapsed = time.time() - start
|
|
276
|
+
_safe_stderr(f"[worker] task={task_id} error: {e}")
|
|
277
|
+
return {
|
|
278
|
+
"success": False,
|
|
279
|
+
"stdout": "",
|
|
280
|
+
"stderr": f"worker invocation error: {e}",
|
|
281
|
+
"exit_code": -1,
|
|
282
|
+
"elapsed_sec": elapsed,
|
|
283
|
+
"artifact_paths": [brief_path],
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
elapsed = time.time() - start
|
|
287
|
+
|
|
288
|
+
materialized = []
|
|
289
|
+
if exit_code == 0 and contract.outputs:
|
|
290
|
+
materialized = _materialize_outputs(contract, workspace_root, stdout)
|
|
291
|
+
|
|
292
|
+
output_log_path = os.path.join(run_dir, "worker_output.log")
|
|
293
|
+
with open(output_log_path, "w", encoding="utf-8") as f:
|
|
294
|
+
f.write(f"EXIT CODE: {exit_code}\n")
|
|
295
|
+
f.write(f"ELAPSED: {elapsed:.2f}s\n")
|
|
296
|
+
if materialized:
|
|
297
|
+
f.write("MATERIALIZED OUTPUTS:\n")
|
|
298
|
+
for m in materialized:
|
|
299
|
+
f.write(f" {m}\n")
|
|
300
|
+
f.write("--- STDOUT ---\n")
|
|
301
|
+
f.write(stdout)
|
|
302
|
+
f.write("\n--- STDERR ---\n")
|
|
303
|
+
f.write(stderr)
|
|
304
|
+
f.write("\n")
|
|
305
|
+
|
|
306
|
+
_safe_stderr(f"[worker] task={task_id} finished (exit={exit_code}, elapsed={elapsed:.1f}s)")
|
|
307
|
+
|
|
308
|
+
return {
|
|
309
|
+
"success": exit_code == 0,
|
|
310
|
+
"stdout": stdout,
|
|
311
|
+
"stderr": stderr,
|
|
312
|
+
"exit_code": exit_code,
|
|
313
|
+
"elapsed_sec": elapsed,
|
|
314
|
+
"artifact_paths": [brief_path, output_log_path] + materialized,
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _fake_worker(contract, workspace_root, run_dir, previous_failures=None):
|
|
319
|
+
task_id = contract.task_id
|
|
320
|
+
_safe_stderr(f"[worker] task={task_id} starting (model=fake)")
|
|
321
|
+
fake_mode = os.environ.get("FAKE_WORKER", "")
|
|
322
|
+
content = "FAKE_WORKER_OUTPUT"
|
|
323
|
+
success = True
|
|
324
|
+
exit_code = 0
|
|
325
|
+
|
|
326
|
+
if fake_mode == "FAIL":
|
|
327
|
+
content = ""
|
|
328
|
+
success = False
|
|
329
|
+
exit_code = 1
|
|
330
|
+
elif fake_mode == "RETRY":
|
|
331
|
+
if previous_failures:
|
|
332
|
+
content = "FAKE_WORKER_OUTPUT"
|
|
333
|
+
success = True
|
|
334
|
+
exit_code = 0
|
|
335
|
+
else:
|
|
336
|
+
content = ""
|
|
337
|
+
success = False
|
|
338
|
+
exit_code = 1
|
|
339
|
+
|
|
340
|
+
os.makedirs(run_dir, exist_ok=True)
|
|
341
|
+
artifact_paths = []
|
|
342
|
+
for out in contract.outputs:
|
|
343
|
+
out_path = out["path"]
|
|
344
|
+
full_path = os.path.join(workspace_root, out_path) if not os.path.isabs(out_path) else out_path
|
|
345
|
+
os.makedirs(os.path.dirname(full_path), exist_ok=True)
|
|
346
|
+
with open(full_path, "w", encoding="utf-8") as f:
|
|
347
|
+
f.write(content)
|
|
348
|
+
artifact_paths.append(full_path)
|
|
349
|
+
|
|
350
|
+
_safe_stderr(f"[worker] task={task_id} finished (exit={exit_code}, elapsed=0.01s)")
|
|
351
|
+
return {
|
|
352
|
+
"success": success,
|
|
353
|
+
"stdout": "fake worker output",
|
|
354
|
+
"stderr": "",
|
|
355
|
+
"exit_code": exit_code,
|
|
356
|
+
"elapsed_sec": 0.01,
|
|
357
|
+
"artifact_paths": artifact_paths,
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def _dispatch_worker(
|
|
362
|
+
contract, workspace_root, run_dir, model, previous_failures=None, changed_approach=None, timeout_sec=300
|
|
363
|
+
):
|
|
364
|
+
"""Run one worker invocation with the given model string (no fallback)."""
|
|
365
|
+
return _run_llm_worker(contract, workspace_root, run_dir, model, previous_failures, changed_approach, timeout_sec)
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def _default_backup_model(model):
|
|
369
|
+
"""Default provider backup chain: primary <-> fallback, hybrid opt-out."""
|
|
370
|
+
if model.startswith("hybrid:"):
|
|
371
|
+
return None
|
|
372
|
+
if model == ModelRegistry.WORKER_PREFIXED:
|
|
373
|
+
return ModelRegistry.WORKER_FALLBACK
|
|
374
|
+
if model == ModelRegistry.QC_PREFIXED:
|
|
375
|
+
return ModelRegistry.QC_FALLBACK
|
|
376
|
+
if model == ModelRegistry.WORKER_FALLBACK:
|
|
377
|
+
return ModelRegistry.WORKER_PREFIXED
|
|
378
|
+
if model == ModelRegistry.FALLBACK:
|
|
379
|
+
return ModelRegistry.WORKER_PREFIXED
|
|
380
|
+
return ModelRegistry.WORKER_FALLBACK
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def _merge_fallback_log(run_dir, primary_model, primary_result, backup_model, backup_result):
|
|
384
|
+
"""Append a provider-fallback section to worker_output.log."""
|
|
385
|
+
try:
|
|
386
|
+
log_path = os.path.join(run_dir, "worker_output.log")
|
|
387
|
+
with open(log_path, "a", encoding="utf-8") as f:
|
|
388
|
+
f.write("\n=== PROVIDER FALLBACK ===\n")
|
|
389
|
+
f.write(f"PRIMARY: {primary_model} exit={primary_result.get('exit_code')}\n")
|
|
390
|
+
f.write(f"BACKUP: {backup_model} exit={backup_result.get('exit_code')}\n")
|
|
391
|
+
except OSError:
|
|
392
|
+
pass
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def run_worker(
|
|
396
|
+
contract,
|
|
397
|
+
workspace_root,
|
|
398
|
+
run_dir,
|
|
399
|
+
previous_failures=None,
|
|
400
|
+
changed_approach=None,
|
|
401
|
+
timeout_sec=300,
|
|
402
|
+
supervisor_attempt=1,
|
|
403
|
+
):
|
|
404
|
+
"""Invoke a worker with provider fallback.
|
|
405
|
+
|
|
406
|
+
Primary provider comes from contract.worker.model (or WORKER_MODEL env).
|
|
407
|
+
On invocation failure (non-zero exit, transport error, timeout) the same
|
|
408
|
+
brief is retried on a backup provider (default FALLBACK). The chain is
|
|
409
|
+
overridable per contract via contract.worker.fallback_model and disableable
|
|
410
|
+
via WORKER_NO_FALLBACK=1.
|
|
411
|
+
|
|
412
|
+
Returns dict with keys:
|
|
413
|
+
success: bool
|
|
414
|
+
stdout: str
|
|
415
|
+
stderr: str
|
|
416
|
+
exit_code: int
|
|
417
|
+
elapsed_sec: float
|
|
418
|
+
artifact_paths: list[str]
|
|
419
|
+
provider: str (model that produced the result)
|
|
420
|
+
fallback_used / fallback_from / fallback_to (only when fallback fired)
|
|
421
|
+
"""
|
|
422
|
+
if os.environ.get("FAKE_WORKER", "") in ("1", "FAIL", "RETRY"):
|
|
423
|
+
return _fake_worker(contract, workspace_root, run_dir, previous_failures)
|
|
424
|
+
|
|
425
|
+
model = contract.worker.get("model") or ModelRegistry.default_worker()
|
|
426
|
+
task_id = contract.task_id
|
|
427
|
+
|
|
428
|
+
if model.startswith("hybrid:"):
|
|
429
|
+
from .hybrid_worker import run_hybrid_worker
|
|
430
|
+
|
|
431
|
+
return run_hybrid_worker(
|
|
432
|
+
contract,
|
|
433
|
+
workspace_root,
|
|
434
|
+
run_dir,
|
|
435
|
+
previous_failures=previous_failures,
|
|
436
|
+
changed_approach=changed_approach,
|
|
437
|
+
timeout_sec=timeout_sec,
|
|
438
|
+
supervisor_attempt=supervisor_attempt,
|
|
439
|
+
)
|
|
440
|
+
|
|
441
|
+
result = _dispatch_worker(
|
|
442
|
+
contract, workspace_root, run_dir, model, previous_failures, changed_approach, timeout_sec
|
|
443
|
+
)
|
|
444
|
+
result["provider"] = model
|
|
445
|
+
|
|
446
|
+
if result.get("exit_code", -1) == 0:
|
|
447
|
+
return result
|
|
448
|
+
|
|
449
|
+
if os.environ.get("WORKER_NO_FALLBACK"):
|
|
450
|
+
return result
|
|
451
|
+
|
|
452
|
+
backup = contract.worker.get("fallback_model") or _default_backup_model(model)
|
|
453
|
+
if not backup or backup == model:
|
|
454
|
+
return result
|
|
455
|
+
|
|
456
|
+
_safe_stderr(
|
|
457
|
+
f"[worker] task={task_id} primary {model} failed (exit={result.get('exit_code')}); falling back to {backup}"
|
|
458
|
+
)
|
|
459
|
+
backup_result = _dispatch_worker(
|
|
460
|
+
contract, workspace_root, run_dir, backup, previous_failures, changed_approach, timeout_sec
|
|
461
|
+
)
|
|
462
|
+
_merge_fallback_log(run_dir, model, result, backup, backup_result)
|
|
463
|
+
backup_result["provider"] = backup
|
|
464
|
+
backup_result["fallback_used"] = True
|
|
465
|
+
backup_result["fallback_from"] = model
|
|
466
|
+
backup_result["fallback_to"] = backup
|
|
467
|
+
backup_result["primary_stderr"] = result.get("stderr", "")
|
|
468
|
+
backup_result["primary_stdout"] = result.get("stdout", "")
|
|
469
|
+
return backup_result
|