delimit-cli 4.0.2 → 4.0.4
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.
- package/README.md +9 -242
- package/bin/delimit-cli.js +352 -4
- package/bin/delimit-setup.js +37 -6
- package/gateway/ai/agent_dispatch.py +34 -2
- package/gateway/ai/github_scanner.py +1 -1
- package/gateway/ai/ledger_manager.py +13 -3
- package/gateway/ai/ledger_propose.py +240 -0
- package/gateway/ai/loop_engine.py +175 -372
- package/gateway/ai/notify.py +700 -13
- package/gateway/ai/reddit_proxy.py +106 -0
- package/gateway/ai/reddit_scanner.py +34 -0
- package/gateway/ai/server.py +343 -81
- package/gateway/ai/siem_streaming.py +290 -0
- package/gateway/ai/social_daemon.py +189 -0
- package/gateway/ai/swarm.py +434 -0
- package/lib/continuity-resolver.js +325 -0
- package/lib/cross-model-hooks.js +214 -2
- package/lib/delimit-template.js +5 -0
- package/lib/session-shell.js +655 -0
- package/lib/session-worker.js +479 -0
- package/package.json +1 -1
- package/scripts/security-check.sh +12 -0
|
@@ -1,408 +1,211 @@
|
|
|
1
|
-
"""
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
-
|
|
5
|
-
-
|
|
6
|
-
-
|
|
7
|
-
-
|
|
8
|
-
|
|
9
|
-
|
|
1
|
+
"""Governed Executor for Continuous Build (LED-239).
|
|
2
|
+
|
|
3
|
+
Requirements (Consensus 123):
|
|
4
|
+
- root ledger in /root/.delimit is authoritative
|
|
5
|
+
- select only build-safe open items (feat, fix, task)
|
|
6
|
+
- resolve venture + repo before dispatch
|
|
7
|
+
- use Delimit swarm/governance as control plane
|
|
8
|
+
- every iteration must update ledger, audit trail, and session state
|
|
9
|
+
- no deploy/secrets/destructive actions without explicit gate
|
|
10
|
+
- enforce max-iteration, max-error, and max-cost safeguards
|
|
10
11
|
"""
|
|
11
12
|
|
|
12
13
|
import json
|
|
14
|
+
import logging
|
|
15
|
+
from datetime import datetime, timezone
|
|
13
16
|
import os
|
|
14
17
|
import time
|
|
15
18
|
import uuid
|
|
16
19
|
from pathlib import Path
|
|
17
20
|
from typing import Any, Dict, List, Optional
|
|
18
21
|
|
|
19
|
-
|
|
20
|
-
SESSIONS_DIR = LOOP_DIR / "sessions"
|
|
21
|
-
|
|
22
|
-
# Actions the AI model must never auto-execute without human approval
|
|
23
|
-
DEFAULT_REQUIRE_APPROVAL = ["deploy", "social_post", "outreach", "publish"]
|
|
24
|
-
|
|
25
|
-
VALID_STATUSES = {"running", "paused", "stopped", "circuit_broken"}
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
def _ensure_dir():
|
|
29
|
-
"""Create the loop sessions directory if it doesn't exist."""
|
|
30
|
-
SESSIONS_DIR.mkdir(parents=True, exist_ok=True)
|
|
22
|
+
logger = logging.getLogger("delimit.ai.loop_engine")
|
|
31
23
|
|
|
24
|
+
# ── Configuration ────────────────────────────────────────────────────
|
|
25
|
+
ROOT_LEDGER_PATH = Path("/root/.delimit")
|
|
26
|
+
BUILD_SAFE_TYPES = ["feat", "fix", "task"]
|
|
27
|
+
MAX_ITERATIONS_DEFAULT = 10
|
|
28
|
+
MAX_COST_DEFAULT = 2.0
|
|
29
|
+
MAX_ERRORS_DEFAULT = 2
|
|
32
30
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
return SESSIONS_DIR / f"{session_id}.json"
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
def _load_session(session_id: str) -> Optional[Dict[str, Any]]:
|
|
39
|
-
"""Load session state from disk. Returns None if not found."""
|
|
40
|
-
path = _session_path(session_id)
|
|
41
|
-
if not path.exists():
|
|
42
|
-
return None
|
|
43
|
-
try:
|
|
44
|
-
return json.loads(path.read_text())
|
|
45
|
-
except (json.JSONDecodeError, OSError):
|
|
46
|
-
return None
|
|
31
|
+
# ── Session State ────────────────────────────────────────────────────
|
|
32
|
+
SESSION_DIR = Path.home() / ".delimit" / "loop" / "sessions"
|
|
47
33
|
|
|
34
|
+
def _ensure_session_dir():
|
|
35
|
+
SESSION_DIR.mkdir(parents=True, exist_ok=True)
|
|
48
36
|
|
|
49
37
|
def _save_session(session: Dict[str, Any]):
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
path = _session_path(session["session_id"])
|
|
38
|
+
_ensure_session_dir()
|
|
39
|
+
path = SESSION_DIR / f"{session['session_id']}.json"
|
|
53
40
|
path.write_text(json.dumps(session, indent=2))
|
|
54
41
|
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
"""Create a new loop session with default safeguards."""
|
|
58
|
-
if not session_id:
|
|
59
|
-
session_id = str(uuid.uuid4())[:12]
|
|
42
|
+
def create_governed_session() -> Dict[str, Any]:
|
|
43
|
+
session_id = f"build-{uuid.uuid4().hex[:8]}"
|
|
60
44
|
session = {
|
|
61
45
|
"session_id": session_id,
|
|
62
|
-
"
|
|
46
|
+
"type": "governed_build",
|
|
47
|
+
"started_at": datetime.now(timezone.utc).isoformat(),
|
|
63
48
|
"iterations": 0,
|
|
64
|
-
"max_iterations":
|
|
49
|
+
"max_iterations": MAX_ITERATIONS_DEFAULT,
|
|
65
50
|
"cost_incurred": 0.0,
|
|
66
|
-
"cost_cap":
|
|
51
|
+
"cost_cap": MAX_COST_DEFAULT,
|
|
67
52
|
"errors": 0,
|
|
68
|
-
"error_threshold":
|
|
53
|
+
"error_threshold": MAX_ERRORS_DEFAULT,
|
|
69
54
|
"tasks_completed": [],
|
|
70
|
-
"
|
|
71
|
-
"require_approval_for": list(DEFAULT_REQUIRE_APPROVAL),
|
|
72
|
-
"status": "running",
|
|
55
|
+
"status": "running"
|
|
73
56
|
}
|
|
74
57
|
_save_session(session)
|
|
75
58
|
return session
|
|
76
59
|
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
"
|
|
100
|
-
"
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
if session["iterations"] >= session["max_iterations"]:
|
|
111
|
-
return {
|
|
112
|
-
"action": "STOP",
|
|
113
|
-
"reason": f"Reached max iterations ({session['max_iterations']}).",
|
|
114
|
-
"safeguard": "max_iterations",
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
if session["cost_incurred"] >= session["cost_cap"]:
|
|
118
|
-
return {
|
|
119
|
-
"action": "STOP",
|
|
120
|
-
"reason": f"Cost cap reached (${session['cost_incurred']:.2f} >= ${session['cost_cap']:.2f}).",
|
|
121
|
-
"safeguard": "cost_cap",
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
if session["errors"] >= session["error_threshold"]:
|
|
125
|
-
session["status"] = "circuit_broken"
|
|
126
|
-
_save_session(session)
|
|
127
|
-
return {
|
|
128
|
-
"action": "STOP",
|
|
129
|
-
"reason": f"Circuit breaker: {session['errors']} errors hit threshold ({session['error_threshold']}).",
|
|
130
|
-
"safeguard": "circuit_breaker",
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
return None
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
def _get_open_items(venture: str = "", project_path: str = ".") -> List[Dict[str, Any]]:
|
|
137
|
-
"""Query the ledger for open items, sorted by priority."""
|
|
60
|
+
# ── Venture & Repo Resolution ─────────────────────────────────────────
|
|
61
|
+
|
|
62
|
+
def resolve_venture_context(venture_name: str) -> Dict[str, str]:
|
|
63
|
+
"""Resolve a venture name to its project path and repo URL."""
|
|
64
|
+
from ai.ledger_manager import list_ventures
|
|
65
|
+
|
|
66
|
+
ventures = list_ventures().get("ventures", {})
|
|
67
|
+
context = {"path": ".", "repo": "", "name": venture_name or "root"}
|
|
68
|
+
|
|
69
|
+
if not venture_name or venture_name == "root":
|
|
70
|
+
context["path"] = str(ROOT_LEDGER_PATH)
|
|
71
|
+
return context
|
|
72
|
+
|
|
73
|
+
if venture_name in ventures:
|
|
74
|
+
v = ventures[venture_name]
|
|
75
|
+
context["path"] = v.get("path", ".")
|
|
76
|
+
context["repo"] = v.get("repo", "")
|
|
77
|
+
return context
|
|
78
|
+
|
|
79
|
+
# Fallback to fuzzy match
|
|
80
|
+
for name, info in ventures.items():
|
|
81
|
+
if venture_name.lower() in name.lower():
|
|
82
|
+
context["path"] = info.get("path", ".")
|
|
83
|
+
context["repo"] = info.get("repo", "")
|
|
84
|
+
context["name"] = name
|
|
85
|
+
return context
|
|
86
|
+
|
|
87
|
+
return context
|
|
88
|
+
|
|
89
|
+
# ── Governed Selection ───────────────────────────────────────────────
|
|
90
|
+
|
|
91
|
+
def get_next_build_task(session: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
|
92
|
+
"""Select the next build-safe item from the authoritative root ledger."""
|
|
138
93
|
from ai.ledger_manager import list_items
|
|
139
|
-
|
|
94
|
+
|
|
95
|
+
# Authoritative root ledger check
|
|
96
|
+
result = list_items(status="open", project_path=str(ROOT_LEDGER_PATH))
|
|
140
97
|
items = []
|
|
141
98
|
for ledger_items in result.get("items", {}).values():
|
|
142
99
|
items.extend(ledger_items)
|
|
143
|
-
|
|
144
|
-
#
|
|
145
|
-
|
|
146
|
-
items.sort(key=lambda x: priority_order.get(x.get("priority", "P2"), 9))
|
|
147
|
-
return items
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
def _filter_actionable(items: List[Dict[str, Any]], max_risk: str = "") -> List[Dict[str, Any]]:
|
|
151
|
-
"""Filter out owner-only items and apply risk filtering.
|
|
152
|
-
|
|
153
|
-
Owner-only items are those with source='owner' or tags containing 'owner-action'.
|
|
154
|
-
"""
|
|
155
|
-
filtered = []
|
|
100
|
+
|
|
101
|
+
# Filter build-safe items only
|
|
102
|
+
actionable = []
|
|
156
103
|
for item in items:
|
|
157
|
-
|
|
158
|
-
tags = item.get("tags", [])
|
|
159
|
-
if "owner-action" in tags or "owner-only" in tags:
|
|
104
|
+
if item.get("type") not in BUILD_SAFE_TYPES:
|
|
160
105
|
continue
|
|
161
|
-
|
|
106
|
+
# Skip items that explicitly require owner action or are not for AI
|
|
107
|
+
tags = item.get("tags", [])
|
|
108
|
+
if "owner-action" in tags or "manual" in tags:
|
|
162
109
|
continue
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
if max_risk:
|
|
166
|
-
item_risk = item.get("risk", "")
|
|
167
|
-
if item_risk and _risk_level(item_risk) > _risk_level(max_risk):
|
|
168
|
-
continue
|
|
169
|
-
|
|
170
|
-
filtered.append(item)
|
|
171
|
-
return filtered
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
def _resolve_project_path(venture: str) -> str:
|
|
175
|
-
"""Resolve a venture name or path to a project directory path."""
|
|
176
|
-
if not venture:
|
|
177
|
-
return "."
|
|
178
|
-
# Direct path — use as-is
|
|
179
|
-
if venture.startswith("/") or venture.startswith("~"):
|
|
180
|
-
return str(Path(venture).expanduser())
|
|
181
|
-
if venture.startswith(".") or os.sep in venture:
|
|
182
|
-
return str(Path(venture).resolve())
|
|
183
|
-
# Try registered ventures
|
|
184
|
-
try:
|
|
185
|
-
from ai.ledger_manager import list_ventures
|
|
186
|
-
ventures = list_ventures()
|
|
187
|
-
for name, info in ventures.get("ventures", {}).items():
|
|
188
|
-
if name == venture or venture in name:
|
|
189
|
-
return info.get("path", ".")
|
|
190
|
-
except Exception:
|
|
191
|
-
pass
|
|
192
|
-
return "."
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
def _risk_level(risk: str) -> int:
|
|
196
|
-
"""Convert risk string to numeric level for comparison."""
|
|
197
|
-
levels = {"low": 1, "medium": 2, "high": 3, "critical": 4}
|
|
198
|
-
return levels.get(risk.lower(), 2)
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
def next_task(
|
|
202
|
-
venture: str = "",
|
|
203
|
-
max_risk: str = "",
|
|
204
|
-
session_id: str = "",
|
|
205
|
-
) -> Dict[str, Any]:
|
|
206
|
-
"""Get the next task to work on with safeguard checks.
|
|
207
|
-
|
|
208
|
-
Returns:
|
|
209
|
-
Dict with action: BUILD (with task), CONSENSUS (generate new items), or STOP.
|
|
210
|
-
"""
|
|
211
|
-
session = _get_or_create_session(session_id)
|
|
212
|
-
|
|
213
|
-
# Check safeguards
|
|
214
|
-
stop = _check_safeguards(session)
|
|
215
|
-
if stop:
|
|
216
|
-
stop["session"] = _session_summary(session)
|
|
217
|
-
return stop
|
|
218
|
-
|
|
219
|
-
# Resolve venture path
|
|
220
|
-
project_path = _resolve_project_path(venture)
|
|
221
|
-
|
|
222
|
-
# Get open items
|
|
223
|
-
items = _get_open_items(venture=venture, project_path=project_path)
|
|
224
|
-
actionable = _filter_actionable(items, max_risk=max_risk)
|
|
225
|
-
|
|
110
|
+
actionable.append(item)
|
|
111
|
+
|
|
226
112
|
if not actionable:
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
#
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
"
|
|
253
|
-
|
|
254
|
-
"
|
|
255
|
-
|
|
256
|
-
if
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
"
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
113
|
+
return None
|
|
114
|
+
|
|
115
|
+
# Sort by priority
|
|
116
|
+
priority_map = {"P0": 0, "P1": 1, "P2": 2, "P3": 3}
|
|
117
|
+
actionable.sort(key=lambda x: priority_map.get(x.get("priority", "P2"), 9))
|
|
118
|
+
|
|
119
|
+
return actionable[0]
|
|
120
|
+
|
|
121
|
+
# ── Swarm Dispatch & Execution ───────────────────────────────────────
|
|
122
|
+
|
|
123
|
+
def run_governed_iteration(session_id: str) -> Dict[str, Any]:
|
|
124
|
+
"""Execute one governed build iteration."""
|
|
125
|
+
from datetime import datetime, timezone
|
|
126
|
+
from ai.swarm import dispatch_task
|
|
127
|
+
|
|
128
|
+
# 1. Load Session & Check Safeguards
|
|
129
|
+
path = SESSION_DIR / f"{session_id}.json"
|
|
130
|
+
if not path.exists():
|
|
131
|
+
return {"error": f"Session {session_id} not found"}
|
|
132
|
+
session = json.loads(path.read_text())
|
|
133
|
+
|
|
134
|
+
if session["status"] != "running":
|
|
135
|
+
return {"status": "stopped", "reason": f"Session status is {session['status']}"}
|
|
136
|
+
|
|
137
|
+
if session["iterations"] >= session["max_iterations"]:
|
|
138
|
+
session["status"] = "finished"
|
|
139
|
+
_save_session(session)
|
|
140
|
+
return {"status": "finished", "reason": "Max iterations reached"}
|
|
141
|
+
|
|
142
|
+
if session["cost_incurred"] >= session["cost_cap"]:
|
|
143
|
+
session["status"] = "stopped"
|
|
144
|
+
_save_session(session)
|
|
145
|
+
return {"status": "stopped", "reason": "Cost cap reached"}
|
|
146
|
+
|
|
147
|
+
# 2. Select Task
|
|
148
|
+
task = get_next_build_task(session)
|
|
149
|
+
if not task:
|
|
150
|
+
return {"status": "idle", "reason": "No build-safe items in ledger"}
|
|
151
|
+
|
|
152
|
+
# 3. Resolve Context
|
|
153
|
+
v_name = task.get("venture", "root")
|
|
154
|
+
ctx = resolve_venture_context(v_name)
|
|
155
|
+
|
|
156
|
+
# 4. Dispatch through Swarm (Control Plane)
|
|
157
|
+
logger.info(f"Dispatching build task {task['id']} for venture {v_name}")
|
|
158
|
+
|
|
159
|
+
start_time = time.time()
|
|
160
|
+
try:
|
|
161
|
+
# Note: Swarm dispatch is the central point of governance
|
|
162
|
+
dispatch_result = dispatch_task(
|
|
163
|
+
title=task["title"],
|
|
164
|
+
description=task["description"],
|
|
165
|
+
context=f"Executing governed build loop for {v_name}. Ledger ID: {task['id']}",
|
|
166
|
+
project_path=ctx["path"],
|
|
167
|
+
priority=task["priority"]
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
# 5. Update State & Ledger
|
|
171
|
+
duration = time.time() - start_time
|
|
172
|
+
cost = dispatch_result.get("estimated_cost", 0.05) # Default placeholder if missing
|
|
173
|
+
|
|
174
|
+
session["iterations"] += 1
|
|
175
|
+
session["cost_incurred"] += cost
|
|
176
|
+
|
|
177
|
+
from ai.ledger_manager import update_item
|
|
178
|
+
if dispatch_result.get("status") == "completed":
|
|
179
|
+
update_item(
|
|
180
|
+
item_id=task["id"],
|
|
181
|
+
status="done",
|
|
182
|
+
note=f"Completed via governed build loop. Result: {dispatch_result.get('summary', 'OK')}",
|
|
183
|
+
project_path=str(ROOT_LEDGER_PATH)
|
|
184
|
+
)
|
|
185
|
+
session["tasks_completed"].append({
|
|
186
|
+
"id": task["id"],
|
|
187
|
+
"status": "success",
|
|
188
|
+
"duration": duration,
|
|
189
|
+
"cost": cost
|
|
190
|
+
})
|
|
191
|
+
else:
|
|
192
|
+
session["errors"] += 1
|
|
193
|
+
if session["errors"] >= session["error_threshold"]:
|
|
194
|
+
session["status"] = "circuit_broken"
|
|
195
|
+
session["tasks_completed"].append({
|
|
196
|
+
"id": task["id"],
|
|
197
|
+
"status": "failed",
|
|
198
|
+
"error": dispatch_result.get("error", "Dispatch failed")
|
|
199
|
+
})
|
|
200
|
+
|
|
201
|
+
_save_session(session)
|
|
202
|
+
return {"status": "continued", "task_id": task["id"], "result": dispatch_result}
|
|
203
|
+
|
|
204
|
+
except Exception as e:
|
|
282
205
|
session["errors"] += 1
|
|
283
|
-
session
|
|
284
|
-
|
|
285
|
-
"status": "error",
|
|
286
|
-
"error": error,
|
|
287
|
-
"completed_at": time.strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
288
|
-
"cost": cost_incurred,
|
|
289
|
-
})
|
|
290
|
-
else:
|
|
291
|
-
session["tasks_completed"].append({
|
|
292
|
-
"task_id": task_id,
|
|
293
|
-
"status": "done",
|
|
294
|
-
"result": result[:500] if result else "",
|
|
295
|
-
"completed_at": time.strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
296
|
-
"cost": cost_incurred,
|
|
297
|
-
})
|
|
298
|
-
|
|
299
|
-
_save_session(session)
|
|
300
|
-
|
|
301
|
-
# Mark ledger item as done (best-effort)
|
|
302
|
-
if not error:
|
|
303
|
-
try:
|
|
304
|
-
from ai.ledger_manager import update_item
|
|
305
|
-
project_path = _resolve_project_path(venture)
|
|
306
|
-
update_item(item_id=task_id, status="done", note=result[:200] if result else "Completed via build loop", project_path=project_path)
|
|
307
|
-
except Exception:
|
|
308
|
-
pass # Never let ledger sync break the loop
|
|
309
|
-
|
|
310
|
-
# Return the next task
|
|
311
|
-
return next_task(venture=venture, session_id=session["session_id"])
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
def loop_status(session_id: str = "") -> Dict[str, Any]:
|
|
315
|
-
"""Return current session metrics."""
|
|
316
|
-
if not session_id:
|
|
317
|
-
# Try to find the most recent session
|
|
318
|
-
sessions = _list_sessions()
|
|
319
|
-
if not sessions:
|
|
320
|
-
return {"error": "No active loop sessions found."}
|
|
321
|
-
session_id = sessions[0]["session_id"]
|
|
322
|
-
|
|
323
|
-
session = _load_session(session_id)
|
|
324
|
-
if not session:
|
|
325
|
-
return {"error": f"Session {session_id} not found."}
|
|
326
|
-
|
|
327
|
-
return {
|
|
328
|
-
"session": _session_summary(session),
|
|
329
|
-
"tasks_completed": session.get("tasks_completed", []),
|
|
330
|
-
"safeguards": {
|
|
331
|
-
"max_iterations": session["max_iterations"],
|
|
332
|
-
"cost_cap": session["cost_cap"],
|
|
333
|
-
"error_threshold": session["error_threshold"],
|
|
334
|
-
"require_approval_for": session.get("require_approval_for", []),
|
|
335
|
-
},
|
|
336
|
-
}
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
def loop_config(
|
|
340
|
-
session_id: str = "",
|
|
341
|
-
max_iterations: int = 0,
|
|
342
|
-
cost_cap: float = 0.0,
|
|
343
|
-
auto_consensus: Optional[bool] = None,
|
|
344
|
-
error_threshold: int = 0,
|
|
345
|
-
status: str = "",
|
|
346
|
-
require_approval_for: Optional[List[str]] = None,
|
|
347
|
-
) -> Dict[str, Any]:
|
|
348
|
-
"""Update session configuration. Only provided values are changed."""
|
|
349
|
-
session = _get_or_create_session(session_id)
|
|
350
|
-
|
|
351
|
-
changes = {}
|
|
352
|
-
if max_iterations > 0:
|
|
353
|
-
session["max_iterations"] = max_iterations
|
|
354
|
-
changes["max_iterations"] = max_iterations
|
|
355
|
-
if cost_cap > 0:
|
|
356
|
-
session["cost_cap"] = cost_cap
|
|
357
|
-
changes["cost_cap"] = cost_cap
|
|
358
|
-
if auto_consensus is not None:
|
|
359
|
-
session["auto_consensus"] = auto_consensus
|
|
360
|
-
changes["auto_consensus"] = auto_consensus
|
|
361
|
-
if error_threshold > 0:
|
|
362
|
-
session["error_threshold"] = error_threshold
|
|
363
|
-
changes["error_threshold"] = error_threshold
|
|
364
|
-
if status and status in VALID_STATUSES:
|
|
365
|
-
session["status"] = status
|
|
366
|
-
changes["status"] = status
|
|
367
|
-
if require_approval_for is not None:
|
|
368
|
-
session["require_approval_for"] = require_approval_for
|
|
369
|
-
changes["require_approval_for"] = require_approval_for
|
|
370
|
-
|
|
371
|
-
_save_session(session)
|
|
372
|
-
|
|
373
|
-
return {
|
|
374
|
-
"session_id": session["session_id"],
|
|
375
|
-
"changes": changes,
|
|
376
|
-
"current_config": _session_summary(session),
|
|
377
|
-
}
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
def _session_summary(session: Dict[str, Any]) -> Dict[str, Any]:
|
|
381
|
-
"""Return a concise session summary for inclusion in responses."""
|
|
382
|
-
return {
|
|
383
|
-
"session_id": session["session_id"],
|
|
384
|
-
"status": session["status"],
|
|
385
|
-
"iterations": session["iterations"],
|
|
386
|
-
"max_iterations": session["max_iterations"],
|
|
387
|
-
"cost_incurred": round(session["cost_incurred"], 4),
|
|
388
|
-
"cost_cap": session["cost_cap"],
|
|
389
|
-
"errors": session["errors"],
|
|
390
|
-
"error_threshold": session["error_threshold"],
|
|
391
|
-
"tasks_done": len(session.get("tasks_completed", [])),
|
|
392
|
-
"auto_consensus": session.get("auto_consensus", False),
|
|
393
|
-
}
|
|
394
|
-
|
|
206
|
+
_save_session(session)
|
|
207
|
+
return {"error": str(e)}
|
|
395
208
|
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
return []
|
|
400
|
-
sessions = []
|
|
401
|
-
for f in SESSIONS_DIR.glob("*.json"):
|
|
402
|
-
try:
|
|
403
|
-
s = json.loads(f.read_text())
|
|
404
|
-
sessions.append(s)
|
|
405
|
-
except (json.JSONDecodeError, OSError):
|
|
406
|
-
continue
|
|
407
|
-
sessions.sort(key=lambda x: x.get("started_at", ""), reverse=True)
|
|
408
|
-
return sessions
|
|
209
|
+
if __name__ == "__main__":
|
|
210
|
+
# Test pass if run directly
|
|
211
|
+
pass
|