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
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""Thread-pool worker pool for parallel execution of independent contracts."""
|
|
2
|
+
|
|
3
|
+
import concurrent.futures
|
|
4
|
+
import os
|
|
5
|
+
import threading
|
|
6
|
+
from typing import Any, Callable, Dict, List, Optional
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class WorkerPool:
|
|
10
|
+
"""Manages concurrent execution of independent contracts.
|
|
11
|
+
|
|
12
|
+
Each contract writes to its own state directory (task_dir = run_dir/<task_id>),
|
|
13
|
+
so concurrent execution is safe as long as shared mutable state
|
|
14
|
+
(results dict, graph node statuses) is protected by a lock.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
def __init__(self, max_workers: int = 3):
|
|
18
|
+
self.max_workers = max_workers
|
|
19
|
+
self._lock = threading.Lock()
|
|
20
|
+
|
|
21
|
+
@property
|
|
22
|
+
def max_workers(self) -> int:
|
|
23
|
+
return self._max_workers
|
|
24
|
+
|
|
25
|
+
@max_workers.setter
|
|
26
|
+
def max_workers(self, value: int) -> None:
|
|
27
|
+
self._max_workers = max(1, min(value, 8))
|
|
28
|
+
|
|
29
|
+
def execute_batch(
|
|
30
|
+
self,
|
|
31
|
+
tasks: List[Dict[str, Any]],
|
|
32
|
+
execute_fn: Callable[[str], str],
|
|
33
|
+
on_result: Optional[Callable[[str, str], None]] = None,
|
|
34
|
+
) -> Dict[str, str]:
|
|
35
|
+
"""Run a batch of tasks in parallel.
|
|
36
|
+
|
|
37
|
+
Args:
|
|
38
|
+
tasks: list of contract-info dicts (must contain 'task_id')
|
|
39
|
+
execute_fn: callable(task_id) -> status string
|
|
40
|
+
on_result: optional callback(task_id, status) after each completion
|
|
41
|
+
|
|
42
|
+
Returns:
|
|
43
|
+
dict mapping task_id -> status
|
|
44
|
+
"""
|
|
45
|
+
if not tasks:
|
|
46
|
+
return {}
|
|
47
|
+
|
|
48
|
+
results: Dict[str, str] = {}
|
|
49
|
+
pending = len(tasks)
|
|
50
|
+
|
|
51
|
+
with concurrent.futures.ThreadPoolExecutor(max_workers=min(self._max_workers, len(tasks))) as pool:
|
|
52
|
+
fut_map = {pool.submit(self._safe_execute, t["task_id"], execute_fn): t["task_id"] for t in tasks}
|
|
53
|
+
|
|
54
|
+
for fut in concurrent.futures.as_completed(fut_map):
|
|
55
|
+
tid = fut_map[fut]
|
|
56
|
+
status = fut.result()
|
|
57
|
+
with self._lock:
|
|
58
|
+
results[tid] = status
|
|
59
|
+
if on_result:
|
|
60
|
+
on_result(tid, status)
|
|
61
|
+
pending -= 1
|
|
62
|
+
|
|
63
|
+
return results
|
|
64
|
+
|
|
65
|
+
def _safe_execute(self, task_id: str, fn: Callable[[str], str]) -> str:
|
|
66
|
+
try:
|
|
67
|
+
return fn(task_id)
|
|
68
|
+
except Exception as e:
|
|
69
|
+
return f"FAILED: {e}"
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def filter_independent_tasks(
|
|
73
|
+
ready_tasks: List[str],
|
|
74
|
+
graph,
|
|
75
|
+
) -> List[str]:
|
|
76
|
+
"""Filter ready_tasks to exclude those that depend on each other.
|
|
77
|
+
|
|
78
|
+
Pre-normalizes all output paths once, then uses an O(n) indexed
|
|
79
|
+
collision check (path -> task_id) instead of per-task set intersection.
|
|
80
|
+
All ready tasks have their dependencies satisfied, so they're all
|
|
81
|
+
mutually independent by definition. Returns all ready tasks.
|
|
82
|
+
"""
|
|
83
|
+
if not ready_tasks:
|
|
84
|
+
return []
|
|
85
|
+
seen_paths: Dict[str, str] = {}
|
|
86
|
+
result = []
|
|
87
|
+
for tid in ready_tasks:
|
|
88
|
+
node = graph.nodes.get(tid, {})
|
|
89
|
+
contract = node.get("contract", {})
|
|
90
|
+
outputs = contract.get("outputs", [])
|
|
91
|
+
collision = False
|
|
92
|
+
for o in outputs:
|
|
93
|
+
raw = o.get("path", "")
|
|
94
|
+
if not raw:
|
|
95
|
+
continue
|
|
96
|
+
normal = os.path.normcase(os.path.normpath(raw))
|
|
97
|
+
if normal in seen_paths:
|
|
98
|
+
collision = True
|
|
99
|
+
break
|
|
100
|
+
if collision:
|
|
101
|
+
continue
|
|
102
|
+
for o in outputs:
|
|
103
|
+
raw = o.get("path", "")
|
|
104
|
+
if raw:
|
|
105
|
+
normal = os.path.normcase(os.path.normpath(raw))
|
|
106
|
+
seen_paths[normal] = tid
|
|
107
|
+
result.append(tid)
|
|
108
|
+
return result
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def format_pool_status(results: Dict[str, str]) -> str:
|
|
112
|
+
"""Format pool execution results."""
|
|
113
|
+
if not results:
|
|
114
|
+
return "No tasks executed."
|
|
115
|
+
total = len(results)
|
|
116
|
+
completed = sum(1 for s in results.values() if str(s).upper() in ("COMPLETE", "SUCCESS"))
|
|
117
|
+
failed = total - completed
|
|
118
|
+
lines = [f"Pool: {total} tasks, {completed} completed, {failed} failed"]
|
|
119
|
+
for tid, status in results.items():
|
|
120
|
+
lines.append(f" {tid}: {status}")
|
|
121
|
+
return "\n".join(lines)
|
orchestrator/worktree.py
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
"""Ephemeral Git Worktree Sandboxing for letitloop.
|
|
2
|
+
|
|
3
|
+
Provides zero-pollution, isolated execution environments for contracts.
|
|
4
|
+
Workers mutate files inside an isolated git worktree branch; only when
|
|
5
|
+
acceptance verifiers and quality plane pass are changes merged to the host branch.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
import os
|
|
12
|
+
import shutil
|
|
13
|
+
import subprocess
|
|
14
|
+
import sys
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from typing import Any, Dict, List, Optional
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger(__name__)
|
|
19
|
+
|
|
20
|
+
GIT_TIMEOUT_SEC = 60
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class SandboxHandle:
|
|
25
|
+
"""Reference to an ephemeral contract-execution worktree."""
|
|
26
|
+
|
|
27
|
+
path: str
|
|
28
|
+
branch: str
|
|
29
|
+
base_commit: str
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class WorktreeError(Exception):
|
|
33
|
+
"""Base exception for worktree operations."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class WorktreeManager:
|
|
37
|
+
"""Manages ephemeral Git worktrees for zero-pollution contract execution."""
|
|
38
|
+
|
|
39
|
+
def __init__(self, workspace_root: str, worktrees_dir: Optional[str] = None):
|
|
40
|
+
self.workspace_root = os.path.abspath(workspace_root)
|
|
41
|
+
self.worktrees_dir = os.path.abspath(
|
|
42
|
+
worktrees_dir or os.path.join(self.workspace_root, ".letitloop", "worktrees")
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
def _is_git_repo(self) -> bool:
|
|
46
|
+
"""Check if workspace_root is inside a valid git repository."""
|
|
47
|
+
try:
|
|
48
|
+
res = subprocess.run(
|
|
49
|
+
["git", "rev-parse", "--is-inside-work-tree"],
|
|
50
|
+
cwd=self.workspace_root,
|
|
51
|
+
capture_output=True,
|
|
52
|
+
text=True,
|
|
53
|
+
check=False,
|
|
54
|
+
)
|
|
55
|
+
return res.returncode == 0 and res.stdout.strip() == "true"
|
|
56
|
+
except (OSError, ValueError):
|
|
57
|
+
return False
|
|
58
|
+
|
|
59
|
+
def create_worktree(self, task_id: str, branch_name: Optional[str] = None) -> str:
|
|
60
|
+
"""Create an ephemeral worktree branch for a contract task.
|
|
61
|
+
|
|
62
|
+
Returns the absolute path to the created worktree directory.
|
|
63
|
+
"""
|
|
64
|
+
clean_task_id = "".join(c if c.isalnum() or c in ("-", "_") else "_" for c in task_id)
|
|
65
|
+
worktree_path = os.path.join(self.worktrees_dir, clean_task_id)
|
|
66
|
+
target_branch = branch_name or f"lil-worktree-{clean_task_id}"
|
|
67
|
+
|
|
68
|
+
if not self._is_git_repo():
|
|
69
|
+
logger.warning(
|
|
70
|
+
"Workspace '%s' is not a git repository; falling back to file copy sandbox.",
|
|
71
|
+
self.workspace_root,
|
|
72
|
+
)
|
|
73
|
+
os.makedirs(worktree_path, exist_ok=True)
|
|
74
|
+
return worktree_path
|
|
75
|
+
|
|
76
|
+
os.makedirs(self.worktrees_dir, exist_ok=True)
|
|
77
|
+
|
|
78
|
+
# If worktree already exists, prune or remove it first
|
|
79
|
+
if os.path.exists(worktree_path):
|
|
80
|
+
self.remove_worktree(clean_task_id, force=True)
|
|
81
|
+
|
|
82
|
+
# Create new worktree with isolated branch
|
|
83
|
+
cmd = ["git", "worktree", "add", "-b", target_branch, worktree_path, "HEAD"]
|
|
84
|
+
res = subprocess.run(
|
|
85
|
+
cmd,
|
|
86
|
+
cwd=self.workspace_root,
|
|
87
|
+
capture_output=True,
|
|
88
|
+
text=True,
|
|
89
|
+
check=False,
|
|
90
|
+
)
|
|
91
|
+
if res.returncode != 0:
|
|
92
|
+
# If branch already exists, try without -b
|
|
93
|
+
cmd_fallback = ["git", "worktree", "add", worktree_path, target_branch]
|
|
94
|
+
res_fb = subprocess.run(
|
|
95
|
+
cmd_fallback,
|
|
96
|
+
cwd=self.workspace_root,
|
|
97
|
+
capture_output=True,
|
|
98
|
+
text=True,
|
|
99
|
+
check=False,
|
|
100
|
+
)
|
|
101
|
+
if res_fb.returncode != 0:
|
|
102
|
+
raise WorktreeError(f"Failed to create git worktree at {worktree_path}: {res.stderr} / {res_fb.stderr}")
|
|
103
|
+
|
|
104
|
+
return worktree_path
|
|
105
|
+
|
|
106
|
+
def remove_worktree(self, task_id: str, force: bool = True, delete_branch: bool = True) -> bool:
|
|
107
|
+
"""Remove an ephemeral worktree and optionally delete its branch."""
|
|
108
|
+
clean_task_id = "".join(c if c.isalnum() or c in ("-", "_") else "_" for c in task_id)
|
|
109
|
+
worktree_path = os.path.join(self.worktrees_dir, clean_task_id)
|
|
110
|
+
target_branch = f"lil-worktree-{clean_task_id}"
|
|
111
|
+
|
|
112
|
+
if not self._is_git_repo():
|
|
113
|
+
if os.path.exists(worktree_path):
|
|
114
|
+
shutil.rmtree(worktree_path, ignore_errors=True)
|
|
115
|
+
return True
|
|
116
|
+
|
|
117
|
+
if os.path.exists(worktree_path):
|
|
118
|
+
cmd = ["git", "worktree", "remove", worktree_path]
|
|
119
|
+
if force:
|
|
120
|
+
cmd.append("--force")
|
|
121
|
+
res = subprocess.run(cmd, cwd=self.workspace_root, capture_output=True, text=True, check=False)
|
|
122
|
+
if res.returncode != 0:
|
|
123
|
+
# Fallback manual rmtree & prune
|
|
124
|
+
shutil.rmtree(worktree_path, ignore_errors=True)
|
|
125
|
+
subprocess.run(["git", "worktree", "prune"], cwd=self.workspace_root, capture_output=True, check=False)
|
|
126
|
+
|
|
127
|
+
if delete_branch:
|
|
128
|
+
subprocess.run(
|
|
129
|
+
["git", "branch", "-D", target_branch],
|
|
130
|
+
cwd=self.workspace_root,
|
|
131
|
+
capture_output=True,
|
|
132
|
+
check=False,
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
return True
|
|
136
|
+
|
|
137
|
+
def list_worktrees(self) -> List[Dict[str, Any]]:
|
|
138
|
+
"""List all active git worktrees."""
|
|
139
|
+
if not self._is_git_repo():
|
|
140
|
+
return []
|
|
141
|
+
|
|
142
|
+
res = subprocess.run(
|
|
143
|
+
["git", "worktree", "list", "--porcelain"],
|
|
144
|
+
cwd=self.workspace_root,
|
|
145
|
+
capture_output=True,
|
|
146
|
+
text=True,
|
|
147
|
+
check=False,
|
|
148
|
+
)
|
|
149
|
+
if res.returncode != 0:
|
|
150
|
+
return []
|
|
151
|
+
|
|
152
|
+
worktrees = []
|
|
153
|
+
current: Dict[str, Any] = {}
|
|
154
|
+
for line in res.stdout.splitlines():
|
|
155
|
+
line = line.strip()
|
|
156
|
+
if not line:
|
|
157
|
+
if current:
|
|
158
|
+
worktrees.append(current)
|
|
159
|
+
current = {}
|
|
160
|
+
continue
|
|
161
|
+
if line.startswith("worktree "):
|
|
162
|
+
current["path"] = line.split(" ", 1)[1]
|
|
163
|
+
elif line.startswith("HEAD "):
|
|
164
|
+
current["head"] = line.split(" ", 1)[1]
|
|
165
|
+
elif line.startswith("branch "):
|
|
166
|
+
current["branch"] = line.split(" ", 1)[1]
|
|
167
|
+
elif line == "bare":
|
|
168
|
+
current["bare"] = True
|
|
169
|
+
|
|
170
|
+
if current:
|
|
171
|
+
worktrees.append(current)
|
|
172
|
+
return worktrees
|
|
173
|
+
|
|
174
|
+
# ------------------------------------------------------------------
|
|
175
|
+
# Contract sandboxing (issue #15): isolated attempt worktrees that are
|
|
176
|
+
# merged back into the base branch only on PASS.
|
|
177
|
+
# ------------------------------------------------------------------
|
|
178
|
+
|
|
179
|
+
def _git(self, *args: str, cwd: Optional[str] = None) -> subprocess.CompletedProcess:
|
|
180
|
+
"""Run a bounded git command; never raises on nonzero exit."""
|
|
181
|
+
return subprocess.run(
|
|
182
|
+
["git", *args],
|
|
183
|
+
cwd=cwd or self.workspace_root,
|
|
184
|
+
capture_output=True,
|
|
185
|
+
text=True,
|
|
186
|
+
check=False,
|
|
187
|
+
timeout=GIT_TIMEOUT_SEC,
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
@staticmethod
|
|
191
|
+
def _sanitize_task_id(task_id: str) -> str:
|
|
192
|
+
return "".join(c if c.isalnum() or c in ("-", "_") else "_" for c in task_id)
|
|
193
|
+
|
|
194
|
+
def sandbox_create(self, task_id: str, attempt: int = 1) -> Optional[SandboxHandle]:
|
|
195
|
+
"""Create an isolated worktree for one contract attempt.
|
|
196
|
+
|
|
197
|
+
Returns None when workspace_root is not a git repository (caller is
|
|
198
|
+
expected to skip sandboxing); raises WorktreeError on git failure.
|
|
199
|
+
"""
|
|
200
|
+
clean_full = f"{self._sanitize_task_id(str(task_id))}_{int(attempt)}"
|
|
201
|
+
worktree_path = os.path.join(self.worktrees_dir, clean_full)
|
|
202
|
+
target_branch = f"letitloop/{clean_full}"
|
|
203
|
+
|
|
204
|
+
if not self._is_git_repo():
|
|
205
|
+
logger.warning(
|
|
206
|
+
"Workspace '%s' is not a git repository; skipping worktree sandboxing.",
|
|
207
|
+
self.workspace_root,
|
|
208
|
+
)
|
|
209
|
+
return None
|
|
210
|
+
|
|
211
|
+
base_res = self._git("rev-parse", "HEAD")
|
|
212
|
+
if base_res.returncode != 0:
|
|
213
|
+
raise WorktreeError(f"Failed to resolve HEAD in {self.workspace_root}: {base_res.stderr}")
|
|
214
|
+
base_commit = base_res.stdout.strip()
|
|
215
|
+
|
|
216
|
+
os.makedirs(self.worktrees_dir, exist_ok=True)
|
|
217
|
+
|
|
218
|
+
# A stale worktree from a previous run of the same attempt must not
|
|
219
|
+
# block creation (mirrors create_worktree's pre-cleanup).
|
|
220
|
+
if os.path.exists(worktree_path):
|
|
221
|
+
self._force_remove_worktree(worktree_path, target_branch)
|
|
222
|
+
|
|
223
|
+
cmd = ["git", "worktree", "add", "-b", target_branch, worktree_path, "HEAD"]
|
|
224
|
+
res = subprocess.run(
|
|
225
|
+
cmd,
|
|
226
|
+
cwd=self.workspace_root,
|
|
227
|
+
capture_output=True,
|
|
228
|
+
text=True,
|
|
229
|
+
check=False,
|
|
230
|
+
timeout=GIT_TIMEOUT_SEC,
|
|
231
|
+
)
|
|
232
|
+
if res.returncode != 0:
|
|
233
|
+
# If branch already exists, try without -b (mirrors create_worktree).
|
|
234
|
+
res_fb = self._git("worktree", "add", worktree_path, target_branch)
|
|
235
|
+
if res_fb.returncode != 0:
|
|
236
|
+
raise WorktreeError(
|
|
237
|
+
f"Failed to create sandbox worktree at {worktree_path}: {res.stderr} / {res_fb.stderr}"
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
return SandboxHandle(path=worktree_path, branch=target_branch, base_commit=base_commit)
|
|
241
|
+
|
|
242
|
+
def merge_on_pass(self, handle: SandboxHandle, base_branch: Optional[str] = None) -> bool:
|
|
243
|
+
"""Merge a passed attempt's worktree back into the base branch.
|
|
244
|
+
|
|
245
|
+
Commits any uncommitted changes inside the worktree first, then
|
|
246
|
+
fast-forwards the base branch when possible, else squash-merges as a
|
|
247
|
+
single-parent commit. On ANY failure the base branch is left untouched
|
|
248
|
+
and False is returned (the caller decides whether to prune). On
|
|
249
|
+
success the worktree and its branch are cleaned up.
|
|
250
|
+
"""
|
|
251
|
+
try:
|
|
252
|
+
return self._merge_on_pass_impl(handle, base_branch)
|
|
253
|
+
except (WorktreeError, subprocess.TimeoutExpired, OSError, ValueError) as exc:
|
|
254
|
+
print(f"[worktree] merge_on_pass failed for {handle.branch}: {exc}", file=sys.stderr)
|
|
255
|
+
return False
|
|
256
|
+
|
|
257
|
+
def _merge_on_pass_impl(self, handle: SandboxHandle, base_branch: Optional[str]) -> bool:
|
|
258
|
+
if base_branch is None:
|
|
259
|
+
sym = self._git("symbolic-ref", "--short", "HEAD")
|
|
260
|
+
if sym.returncode != 0:
|
|
261
|
+
return False
|
|
262
|
+
base_branch = sym.stdout.strip()
|
|
263
|
+
|
|
264
|
+
# 1. Commit pending changes inside the worktree (allow-empty tolerated:
|
|
265
|
+
# a PASS with no edits must still be mergeable).
|
|
266
|
+
add_res = self._git("add", "-A", cwd=handle.path)
|
|
267
|
+
if add_res.returncode != 0:
|
|
268
|
+
return False
|
|
269
|
+
branch_short = handle.branch.split("/", 1)[-1]
|
|
270
|
+
commit_res = self._git(
|
|
271
|
+
"-c",
|
|
272
|
+
"user.name=letitloop",
|
|
273
|
+
"-c",
|
|
274
|
+
"user.email=letitloop@local",
|
|
275
|
+
"commit",
|
|
276
|
+
"-m",
|
|
277
|
+
f"letitloop: {branch_short}",
|
|
278
|
+
"--allow-empty",
|
|
279
|
+
cwd=handle.path,
|
|
280
|
+
)
|
|
281
|
+
if commit_res.returncode != 0:
|
|
282
|
+
return False
|
|
283
|
+
|
|
284
|
+
# 2. Refuse to touch a dirty host checkout — merging could destroy
|
|
285
|
+
# uncommitted user work. Fail closed instead. Entries under our own
|
|
286
|
+
# worktrees_dir are sandbox plumbing, not user work.
|
|
287
|
+
head_sha = self._git("rev-parse", "HEAD")
|
|
288
|
+
if head_sha.returncode != 0:
|
|
289
|
+
return False
|
|
290
|
+
base_head = head_sha.stdout.strip()
|
|
291
|
+
status_res = self._git("status", "--porcelain")
|
|
292
|
+
if status_res.returncode != 0:
|
|
293
|
+
return False
|
|
294
|
+
try:
|
|
295
|
+
rel_worktrees = os.path.relpath(self.worktrees_dir, self.workspace_root).replace(os.sep, "/")
|
|
296
|
+
except ValueError:
|
|
297
|
+
rel_worktrees = None
|
|
298
|
+
for line in status_res.stdout.splitlines():
|
|
299
|
+
if not line.strip() or line.startswith("??"):
|
|
300
|
+
continue
|
|
301
|
+
entry_path = line[3:].strip().strip('"').replace("\\", "/").lower()
|
|
302
|
+
if rel_worktrees and (
|
|
303
|
+
entry_path == rel_worktrees.lower() or entry_path.startswith(rel_worktrees.lower() + "/")
|
|
304
|
+
):
|
|
305
|
+
continue
|
|
306
|
+
return False
|
|
307
|
+
|
|
308
|
+
# 3. Fast-forward when possible...
|
|
309
|
+
ff_res = self._git("merge", "--ff-only", handle.branch)
|
|
310
|
+
if ff_res.returncode == 0:
|
|
311
|
+
self._force_remove_worktree(handle.path, handle.branch)
|
|
312
|
+
return True
|
|
313
|
+
|
|
314
|
+
# 4. ...else squash-style single-parent merge. Any failure rolls the
|
|
315
|
+
# base branch back to exactly where it was.
|
|
316
|
+
squash_res = self._git("merge", "--squash", handle.branch)
|
|
317
|
+
if squash_res.returncode != 0:
|
|
318
|
+
self._git("reset", "--hard", base_head)
|
|
319
|
+
return False
|
|
320
|
+
squash_commit = self._git(
|
|
321
|
+
"-c",
|
|
322
|
+
"user.name=letitloop",
|
|
323
|
+
"-c",
|
|
324
|
+
"user.email=letitloop@local",
|
|
325
|
+
"commit",
|
|
326
|
+
"-m",
|
|
327
|
+
f"letitloop: {branch_short}",
|
|
328
|
+
)
|
|
329
|
+
if squash_commit.returncode != 0:
|
|
330
|
+
# An attempt whose content already matches base (empty diff) is a
|
|
331
|
+
# legitimate PASS: git reports "nothing to commit" and the base is
|
|
332
|
+
# semantically correct already.
|
|
333
|
+
if "nothing to commit" in f"{squash_commit.stdout} {squash_commit.stderr}".lower():
|
|
334
|
+
self._force_remove_worktree(handle.path, handle.branch)
|
|
335
|
+
return True
|
|
336
|
+
self._git("reset", "--hard", base_head)
|
|
337
|
+
return False
|
|
338
|
+
|
|
339
|
+
self._force_remove_worktree(handle.path, handle.branch)
|
|
340
|
+
return True
|
|
341
|
+
|
|
342
|
+
def prune_on_fail(self, handle: SandboxHandle) -> bool:
|
|
343
|
+
"""Discard a failed attempt: force-remove its worktree and branch."""
|
|
344
|
+
return self._force_remove_worktree(handle.path, handle.branch)
|
|
345
|
+
|
|
346
|
+
def _force_remove_worktree(self, worktree_path: str, branch: Optional[str]) -> bool:
|
|
347
|
+
"""Force-remove a worktree dir and optionally delete its branch."""
|
|
348
|
+
removed_dir = True
|
|
349
|
+
if os.path.exists(worktree_path):
|
|
350
|
+
res = self._git("worktree", "remove", worktree_path, "--force")
|
|
351
|
+
if res.returncode != 0:
|
|
352
|
+
removed_dir = False
|
|
353
|
+
# Fallback manual rmtree & prune (mirrors remove_worktree).
|
|
354
|
+
shutil.rmtree(worktree_path, ignore_errors=True)
|
|
355
|
+
self._git("worktree", "prune")
|
|
356
|
+
if os.path.exists(worktree_path):
|
|
357
|
+
shutil.rmtree(worktree_path, ignore_errors=True)
|
|
358
|
+
removed_dir = removed_dir and not os.path.exists(worktree_path)
|
|
359
|
+
|
|
360
|
+
deleted_branch = True
|
|
361
|
+
if branch:
|
|
362
|
+
br_res = self._git("branch", "-D", branch)
|
|
363
|
+
deleted_branch = br_res.returncode == 0
|
|
364
|
+
return removed_dir and deleted_branch
|