fleetdeck 0.3.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.
- fleetdeck/__init__.py +3 -0
- fleetdeck/__main__.py +232 -0
- fleetdeck/accounts.py +115 -0
- fleetdeck/adapters/__init__.py +0 -0
- fleetdeck/adapters/base.py +71 -0
- fleetdeck/adapters/claude_cli.py +187 -0
- fleetdeck/adapters/codex_cli.py +362 -0
- fleetdeck/adapters/demo.py +331 -0
- fleetdeck/config.py +323 -0
- fleetdeck/db.py +511 -0
- fleetdeck/gitinfo.py +169 -0
- fleetdeck/models.py +178 -0
- fleetdeck/paths.py +64 -0
- fleetdeck/proc.py +92 -0
- fleetdeck/redact.py +51 -0
- fleetdeck/services/__init__.py +0 -0
- fleetdeck/services/dispatcher.py +382 -0
- fleetdeck/services/fleet.py +65 -0
- fleetdeck/services/monitor.py +253 -0
- fleetdeck/services/notifier.py +71 -0
- fleetdeck/status.py +97 -0
- fleetdeck/terminal.py +235 -0
- fleetdeck/termrender.py +129 -0
- fleetdeck/ui/__init__.py +0 -0
- fleetdeck/ui/app.py +1295 -0
- fleetdeck/ui/app.tcss +263 -0
- fleetdeck/ui/commands.py +63 -0
- fleetdeck/ui/screens/__init__.py +0 -0
- fleetdeck/ui/screens/modals.py +623 -0
- fleetdeck/ui/style.py +150 -0
- fleetdeck/ui/views.py +230 -0
- fleetdeck/ui/widgets/__init__.py +0 -0
- fleetdeck/ui/widgets/agent_table.py +185 -0
- fleetdeck/ui/widgets/bottom.py +27 -0
- fleetdeck/ui/widgets/details.py +295 -0
- fleetdeck/ui/widgets/header.py +87 -0
- fleetdeck/ui/widgets/sidebar.py +227 -0
- fleetdeck/ui/widgets/splitter.py +66 -0
- fleetdeck/ui/widgets/terminal.py +119 -0
- fleetdeck-0.3.0.dist-info/METADATA +245 -0
- fleetdeck-0.3.0.dist-info/RECORD +44 -0
- fleetdeck-0.3.0.dist-info/WHEEL +4 -0
- fleetdeck-0.3.0.dist-info/entry_points.txt +2 -0
- fleetdeck-0.3.0.dist-info/licenses/LICENSE +21 -0
fleetdeck/db.py
ADDED
|
@@ -0,0 +1,511 @@
|
|
|
1
|
+
"""SQLite store: projects, task queues, templates, launches and activity.
|
|
2
|
+
|
|
3
|
+
All access happens on the UI event loop thread; every statement is a small
|
|
4
|
+
indexed lookup on a local file, so it never blocks perceptibly.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import sqlite3
|
|
12
|
+
import time
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Iterable
|
|
15
|
+
|
|
16
|
+
from .models import Activity, Project, Task, TaskStatus, Template
|
|
17
|
+
from .redact import redact
|
|
18
|
+
|
|
19
|
+
MIGRATIONS: list[str] = [
|
|
20
|
+
# v1
|
|
21
|
+
"""
|
|
22
|
+
CREATE TABLE projects (
|
|
23
|
+
id INTEGER PRIMARY KEY,
|
|
24
|
+
name TEXT NOT NULL,
|
|
25
|
+
path TEXT NOT NULL UNIQUE,
|
|
26
|
+
grp TEXT NOT NULL DEFAULT 'personal',
|
|
27
|
+
pinned INTEGER NOT NULL DEFAULT 0,
|
|
28
|
+
environment TEXT NOT NULL DEFAULT 'default',
|
|
29
|
+
instructions TEXT NOT NULL DEFAULT '',
|
|
30
|
+
always_worktree INTEGER NOT NULL DEFAULT 0,
|
|
31
|
+
test_command TEXT NOT NULL DEFAULT '',
|
|
32
|
+
env_json TEXT NOT NULL DEFAULT '{}',
|
|
33
|
+
created_at REAL NOT NULL
|
|
34
|
+
);
|
|
35
|
+
CREATE TABLE tasks (
|
|
36
|
+
id INTEGER PRIMARY KEY,
|
|
37
|
+
project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
|
38
|
+
title TEXT NOT NULL,
|
|
39
|
+
prompt TEXT NOT NULL,
|
|
40
|
+
priority INTEGER NOT NULL DEFAULT 2,
|
|
41
|
+
status TEXT NOT NULL DEFAULT 'queued',
|
|
42
|
+
agent_id TEXT,
|
|
43
|
+
agent_name TEXT,
|
|
44
|
+
model TEXT,
|
|
45
|
+
permission_mode TEXT,
|
|
46
|
+
use_worktree INTEGER NOT NULL DEFAULT 0,
|
|
47
|
+
attempts INTEGER NOT NULL DEFAULT 0,
|
|
48
|
+
error TEXT,
|
|
49
|
+
created_at REAL NOT NULL,
|
|
50
|
+
started_at REAL,
|
|
51
|
+
finished_at REAL
|
|
52
|
+
);
|
|
53
|
+
CREATE INDEX idx_tasks_status ON tasks(status, priority, created_at);
|
|
54
|
+
CREATE TABLE templates (
|
|
55
|
+
id INTEGER PRIMARY KEY,
|
|
56
|
+
name TEXT NOT NULL UNIQUE,
|
|
57
|
+
body TEXT NOT NULL,
|
|
58
|
+
created_at REAL NOT NULL
|
|
59
|
+
);
|
|
60
|
+
CREATE TABLE launches (
|
|
61
|
+
name TEXT PRIMARY KEY,
|
|
62
|
+
agent_id TEXT,
|
|
63
|
+
project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL,
|
|
64
|
+
task_id INTEGER REFERENCES tasks(id) ON DELETE SET NULL,
|
|
65
|
+
model TEXT,
|
|
66
|
+
permission_mode TEXT,
|
|
67
|
+
worktree TEXT,
|
|
68
|
+
prompt TEXT,
|
|
69
|
+
launched_at REAL NOT NULL
|
|
70
|
+
);
|
|
71
|
+
CREATE INDEX idx_launches_agent ON launches(agent_id);
|
|
72
|
+
CREATE TABLE activity (
|
|
73
|
+
id INTEGER PRIMARY KEY,
|
|
74
|
+
ts REAL NOT NULL,
|
|
75
|
+
level TEXT NOT NULL,
|
|
76
|
+
message TEXT NOT NULL,
|
|
77
|
+
project_id INTEGER
|
|
78
|
+
);
|
|
79
|
+
CREATE TABLE kv (k TEXT PRIMARY KEY, v TEXT NOT NULL);
|
|
80
|
+
""",
|
|
81
|
+
# v2: task chains + follow-up prompts to existing sessions
|
|
82
|
+
"""
|
|
83
|
+
ALTER TABLE tasks ADD COLUMN depends_on INTEGER REFERENCES tasks(id) ON DELETE SET NULL;
|
|
84
|
+
ALTER TABLE tasks ADD COLUMN resume_session TEXT;
|
|
85
|
+
ALTER TABLE tasks ADD COLUMN resume_agent TEXT;
|
|
86
|
+
CREATE INDEX idx_tasks_depends ON tasks(depends_on);
|
|
87
|
+
""",
|
|
88
|
+
# v3: accounts (multiple Claude / Codex logins) + Codex runs we launch
|
|
89
|
+
"""
|
|
90
|
+
ALTER TABLE projects ADD COLUMN account TEXT;
|
|
91
|
+
ALTER TABLE tasks ADD COLUMN account TEXT;
|
|
92
|
+
CREATE TABLE codex_runs (
|
|
93
|
+
id TEXT PRIMARY KEY,
|
|
94
|
+
account TEXT NOT NULL,
|
|
95
|
+
name TEXT,
|
|
96
|
+
cwd TEXT NOT NULL,
|
|
97
|
+
pid INTEGER,
|
|
98
|
+
log_path TEXT NOT NULL,
|
|
99
|
+
thread_id TEXT,
|
|
100
|
+
model TEXT,
|
|
101
|
+
sandbox TEXT,
|
|
102
|
+
prompt TEXT,
|
|
103
|
+
started_at REAL NOT NULL,
|
|
104
|
+
stopped INTEGER NOT NULL DEFAULT 0,
|
|
105
|
+
hidden INTEGER NOT NULL DEFAULT 0
|
|
106
|
+
);
|
|
107
|
+
CREATE INDEX idx_codex_runs_account ON codex_runs(account, hidden);
|
|
108
|
+
CREATE INDEX idx_codex_runs_thread ON codex_runs(thread_id);
|
|
109
|
+
""",
|
|
110
|
+
]
|
|
111
|
+
|
|
112
|
+
DEFAULT_TEMPLATES = {
|
|
113
|
+
"Fix failing tests": "Run the test suite, find the root cause of each failure, fix it, "
|
|
114
|
+
"and re-run until green. Do not delete or skip tests.",
|
|
115
|
+
"Code review": "Review the uncommitted changes and recent commits on this branch for "
|
|
116
|
+
"correctness, security and test coverage. Report findings ranked by severity; "
|
|
117
|
+
"do not modify files.",
|
|
118
|
+
"Add tests": "Identify untested code paths in {area} and add focused unit tests "
|
|
119
|
+
"following the project's existing test conventions.",
|
|
120
|
+
"Refactor": "Refactor {area} for readability without changing behaviour. Keep the "
|
|
121
|
+
"public API stable and keep the build and tests green.",
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class Store:
|
|
126
|
+
def __init__(self, path: Path | str) -> None:
|
|
127
|
+
self.path = str(path)
|
|
128
|
+
if self.path != ":memory:":
|
|
129
|
+
Path(self.path).parent.mkdir(parents=True, exist_ok=True)
|
|
130
|
+
self.conn = sqlite3.connect(self.path, isolation_level=None, check_same_thread=False)
|
|
131
|
+
self.conn.row_factory = sqlite3.Row
|
|
132
|
+
self.conn.execute("PRAGMA foreign_keys = ON")
|
|
133
|
+
self.conn.execute("PRAGMA journal_mode = WAL")
|
|
134
|
+
self._migrate()
|
|
135
|
+
if self.path != ":memory:":
|
|
136
|
+
# WAL side files hold the same data as the main file.
|
|
137
|
+
for suffix in ("", "-wal", "-shm"):
|
|
138
|
+
try:
|
|
139
|
+
os.chmod(self.path + suffix, 0o600)
|
|
140
|
+
except OSError:
|
|
141
|
+
pass
|
|
142
|
+
|
|
143
|
+
# ------------------------------------------------------------- schema
|
|
144
|
+
def _migrate(self) -> None:
|
|
145
|
+
version = self.conn.execute("PRAGMA user_version").fetchone()[0]
|
|
146
|
+
for i, script in enumerate(MIGRATIONS[version:], start=version + 1):
|
|
147
|
+
# executescript commits any open transaction itself; wrap the
|
|
148
|
+
# migration and the version bump in one explicit transaction.
|
|
149
|
+
self.conn.executescript(f"BEGIN;\n{script}\nPRAGMA user_version = {i};\nCOMMIT;")
|
|
150
|
+
if i == 1:
|
|
151
|
+
self._seed_templates()
|
|
152
|
+
|
|
153
|
+
def _seed_templates(self) -> None:
|
|
154
|
+
now = time.time()
|
|
155
|
+
for name, body in DEFAULT_TEMPLATES.items():
|
|
156
|
+
self.conn.execute(
|
|
157
|
+
"INSERT OR IGNORE INTO templates(name, body, created_at) VALUES (?,?,?)",
|
|
158
|
+
(name, body, now),
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
def close(self) -> None:
|
|
162
|
+
self.conn.close()
|
|
163
|
+
|
|
164
|
+
# ----------------------------------------------------------- projects
|
|
165
|
+
@staticmethod
|
|
166
|
+
def _project(r: sqlite3.Row) -> Project:
|
|
167
|
+
return Project(
|
|
168
|
+
id=r["id"],
|
|
169
|
+
name=r["name"],
|
|
170
|
+
path=r["path"],
|
|
171
|
+
group=r["grp"],
|
|
172
|
+
pinned=bool(r["pinned"]),
|
|
173
|
+
environment=r["environment"],
|
|
174
|
+
instructions=r["instructions"],
|
|
175
|
+
always_worktree=bool(r["always_worktree"]),
|
|
176
|
+
test_command=r["test_command"],
|
|
177
|
+
env=json.loads(r["env_json"] or "{}"),
|
|
178
|
+
created_at=r["created_at"],
|
|
179
|
+
account=r["account"],
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
def list_projects(self) -> list[Project]:
|
|
183
|
+
rows = self.conn.execute(
|
|
184
|
+
"SELECT * FROM projects ORDER BY pinned DESC, lower(name)"
|
|
185
|
+
).fetchall()
|
|
186
|
+
return [self._project(r) for r in rows]
|
|
187
|
+
|
|
188
|
+
def get_project(self, project_id: int) -> Project | None:
|
|
189
|
+
r = self.conn.execute("SELECT * FROM projects WHERE id = ?", (project_id,)).fetchone()
|
|
190
|
+
return self._project(r) if r else None
|
|
191
|
+
|
|
192
|
+
def add_project(
|
|
193
|
+
self,
|
|
194
|
+
name: str,
|
|
195
|
+
path: str,
|
|
196
|
+
group: str = "personal",
|
|
197
|
+
*,
|
|
198
|
+
environment: str | None = None,
|
|
199
|
+
pinned: bool = False,
|
|
200
|
+
always_worktree: bool = False,
|
|
201
|
+
test_command: str = "",
|
|
202
|
+
instructions: str = "",
|
|
203
|
+
account: str | None = None,
|
|
204
|
+
) -> Project:
|
|
205
|
+
resolved = str(Path(path).expanduser().resolve())
|
|
206
|
+
cur = self.conn.execute(
|
|
207
|
+
"INSERT INTO projects(name, path, grp, pinned, environment, always_worktree,"
|
|
208
|
+
" test_command, instructions, account, created_at) VALUES (?,?,?,?,?,?,?,?,?,?)",
|
|
209
|
+
(
|
|
210
|
+
name.strip(),
|
|
211
|
+
resolved,
|
|
212
|
+
group,
|
|
213
|
+
int(pinned),
|
|
214
|
+
environment or group,
|
|
215
|
+
int(always_worktree),
|
|
216
|
+
test_command,
|
|
217
|
+
instructions,
|
|
218
|
+
account,
|
|
219
|
+
time.time(),
|
|
220
|
+
),
|
|
221
|
+
)
|
|
222
|
+
return self.get_project(cur.lastrowid) # type: ignore[arg-type] # row was just inserted
|
|
223
|
+
|
|
224
|
+
def update_project(self, project_id: int, **fields) -> None:
|
|
225
|
+
mapping = {
|
|
226
|
+
"name": "name",
|
|
227
|
+
"group": "grp",
|
|
228
|
+
"pinned": "pinned",
|
|
229
|
+
"environment": "environment",
|
|
230
|
+
"instructions": "instructions",
|
|
231
|
+
"always_worktree": "always_worktree",
|
|
232
|
+
"test_command": "test_command",
|
|
233
|
+
"account": "account",
|
|
234
|
+
}
|
|
235
|
+
sets, vals = [], []
|
|
236
|
+
for key, value in fields.items():
|
|
237
|
+
if key == "env":
|
|
238
|
+
sets.append("env_json = ?")
|
|
239
|
+
vals.append(json.dumps(value))
|
|
240
|
+
elif key in mapping:
|
|
241
|
+
sets.append(f"{mapping[key]} = ?")
|
|
242
|
+
vals.append(int(value) if isinstance(value, bool) else value)
|
|
243
|
+
else:
|
|
244
|
+
raise KeyError(key)
|
|
245
|
+
if sets:
|
|
246
|
+
vals.append(project_id)
|
|
247
|
+
self.conn.execute(f"UPDATE projects SET {', '.join(sets)} WHERE id = ?", vals)
|
|
248
|
+
|
|
249
|
+
def remove_project(self, project_id: int) -> None:
|
|
250
|
+
self.conn.execute("DELETE FROM projects WHERE id = ?", (project_id,))
|
|
251
|
+
|
|
252
|
+
# -------------------------------------------------------------- tasks
|
|
253
|
+
@staticmethod
|
|
254
|
+
def _task(r: sqlite3.Row) -> Task:
|
|
255
|
+
return Task(
|
|
256
|
+
id=r["id"],
|
|
257
|
+
project_id=r["project_id"],
|
|
258
|
+
title=r["title"],
|
|
259
|
+
prompt=r["prompt"],
|
|
260
|
+
priority=r["priority"],
|
|
261
|
+
status=TaskStatus(r["status"]),
|
|
262
|
+
agent_id=r["agent_id"],
|
|
263
|
+
agent_name=r["agent_name"],
|
|
264
|
+
model=r["model"],
|
|
265
|
+
permission_mode=r["permission_mode"],
|
|
266
|
+
use_worktree=bool(r["use_worktree"]),
|
|
267
|
+
attempts=r["attempts"],
|
|
268
|
+
error=r["error"],
|
|
269
|
+
created_at=r["created_at"],
|
|
270
|
+
started_at=r["started_at"],
|
|
271
|
+
finished_at=r["finished_at"],
|
|
272
|
+
depends_on=r["depends_on"],
|
|
273
|
+
resume_session=r["resume_session"],
|
|
274
|
+
resume_agent=r["resume_agent"],
|
|
275
|
+
account=r["account"],
|
|
276
|
+
)
|
|
277
|
+
|
|
278
|
+
def add_task(
|
|
279
|
+
self,
|
|
280
|
+
project_id: int,
|
|
281
|
+
title: str,
|
|
282
|
+
prompt: str,
|
|
283
|
+
*,
|
|
284
|
+
priority: int = 2,
|
|
285
|
+
model: str | None = None,
|
|
286
|
+
permission_mode: str | None = None,
|
|
287
|
+
use_worktree: bool = False,
|
|
288
|
+
depends_on: int | None = None,
|
|
289
|
+
resume_session: str | None = None,
|
|
290
|
+
resume_agent: str | None = None,
|
|
291
|
+
account: str | None = None,
|
|
292
|
+
) -> Task:
|
|
293
|
+
cur = self.conn.execute(
|
|
294
|
+
"INSERT INTO tasks(project_id, title, prompt, priority, model, permission_mode,"
|
|
295
|
+
" use_worktree, depends_on, resume_session, resume_agent, account, created_at)"
|
|
296
|
+
" VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
|
|
297
|
+
(
|
|
298
|
+
project_id,
|
|
299
|
+
title.strip() or prompt.strip()[:60],
|
|
300
|
+
prompt,
|
|
301
|
+
max(1, min(4, priority)),
|
|
302
|
+
model,
|
|
303
|
+
permission_mode,
|
|
304
|
+
int(use_worktree),
|
|
305
|
+
depends_on,
|
|
306
|
+
resume_session,
|
|
307
|
+
resume_agent,
|
|
308
|
+
account,
|
|
309
|
+
time.time(),
|
|
310
|
+
),
|
|
311
|
+
)
|
|
312
|
+
return self.get_task(cur.lastrowid) # type: ignore[arg-type,return-value] # just inserted
|
|
313
|
+
|
|
314
|
+
def get_task(self, task_id: int) -> Task | None:
|
|
315
|
+
r = self.conn.execute("SELECT * FROM tasks WHERE id = ?", (task_id,)).fetchone()
|
|
316
|
+
return self._task(r) if r else None
|
|
317
|
+
|
|
318
|
+
def list_tasks(
|
|
319
|
+
self, project_id: int | None = None, statuses: Iterable[TaskStatus] | None = None
|
|
320
|
+
) -> list[Task]:
|
|
321
|
+
q = "SELECT * FROM tasks"
|
|
322
|
+
clauses, vals = [], []
|
|
323
|
+
if project_id is not None:
|
|
324
|
+
clauses.append("project_id = ?")
|
|
325
|
+
vals.append(project_id)
|
|
326
|
+
if statuses:
|
|
327
|
+
st = [s.value for s in statuses]
|
|
328
|
+
clauses.append(f"status IN ({','.join('?' * len(st))})")
|
|
329
|
+
vals.extend(st)
|
|
330
|
+
if clauses:
|
|
331
|
+
q += " WHERE " + " AND ".join(clauses)
|
|
332
|
+
q += " ORDER BY CASE status WHEN 'running' THEN 0 WHEN 'blocked' THEN 0 " \
|
|
333
|
+
"WHEN 'dispatching' THEN 1 WHEN 'queued' THEN 2 ELSE 3 END, priority, created_at"
|
|
334
|
+
return [self._task(r) for r in self.conn.execute(q, vals).fetchall()]
|
|
335
|
+
|
|
336
|
+
def next_queued(self, exclude_projects: Iterable[int] = (),
|
|
337
|
+
exclude_tasks: Iterable[int] = ()) -> Task | None:
|
|
338
|
+
"""Highest-priority queued task whose dependency (if any) has completed."""
|
|
339
|
+
ex, ext = list(exclude_projects), list(exclude_tasks)
|
|
340
|
+
q = ("SELECT * FROM tasks t WHERE status = 'queued' AND (t.depends_on IS NULL OR"
|
|
341
|
+
" EXISTS (SELECT 1 FROM tasks d WHERE d.id = t.depends_on"
|
|
342
|
+
" AND d.status = 'completed'))")
|
|
343
|
+
if ex:
|
|
344
|
+
q += f" AND project_id NOT IN ({','.join('?' * len(ex))})"
|
|
345
|
+
if ext:
|
|
346
|
+
q += f" AND id NOT IN ({','.join('?' * len(ext))})"
|
|
347
|
+
q += " ORDER BY priority, created_at LIMIT 1"
|
|
348
|
+
r = self.conn.execute(q, [*ex, *ext]).fetchone()
|
|
349
|
+
return self._task(r) if r else None
|
|
350
|
+
|
|
351
|
+
def cancel_orphaned_dependents(self) -> list[Task]:
|
|
352
|
+
"""Cancel queued tasks whose prerequisite failed or was cancelled."""
|
|
353
|
+
rows = self.conn.execute(
|
|
354
|
+
"SELECT t.* FROM tasks t JOIN tasks d ON d.id = t.depends_on"
|
|
355
|
+
" WHERE t.status = 'queued' AND d.status IN ('failed', 'cancelled')"
|
|
356
|
+
).fetchall()
|
|
357
|
+
out = []
|
|
358
|
+
now = time.time()
|
|
359
|
+
for r in rows:
|
|
360
|
+
self.conn.execute(
|
|
361
|
+
"UPDATE tasks SET status = 'cancelled', finished_at = ?, error = ?"
|
|
362
|
+
" WHERE id = ? AND status = 'queued'",
|
|
363
|
+
(now, f"prerequisite task #{r['depends_on']} did not complete", r["id"]))
|
|
364
|
+
out.append(self._task(r))
|
|
365
|
+
return out
|
|
366
|
+
|
|
367
|
+
def update_task(self, task_id: int, **fields) -> None:
|
|
368
|
+
allowed = {
|
|
369
|
+
"status", "agent_id", "agent_name", "error", "started_at", "finished_at",
|
|
370
|
+
"attempts", "priority", "title", "prompt", "model", "permission_mode",
|
|
371
|
+
"use_worktree", "depends_on", "account",
|
|
372
|
+
}
|
|
373
|
+
sets, vals = [], []
|
|
374
|
+
for key, value in fields.items():
|
|
375
|
+
if key not in allowed:
|
|
376
|
+
raise KeyError(key)
|
|
377
|
+
if isinstance(value, TaskStatus):
|
|
378
|
+
value = value.value
|
|
379
|
+
elif isinstance(value, bool):
|
|
380
|
+
value = int(value)
|
|
381
|
+
sets.append(f"{key} = ?")
|
|
382
|
+
vals.append(value)
|
|
383
|
+
if sets:
|
|
384
|
+
vals.append(task_id)
|
|
385
|
+
self.conn.execute(f"UPDATE tasks SET {', '.join(sets)} WHERE id = ?", vals)
|
|
386
|
+
|
|
387
|
+
def claim_task(self, task_id: int) -> bool:
|
|
388
|
+
"""Atomically move a QUEUED task to DISPATCHING. Exactly one caller wins,
|
|
389
|
+
which makes a double launch of the same task impossible."""
|
|
390
|
+
cur = self.conn.execute(
|
|
391
|
+
"UPDATE tasks SET status = 'dispatching', started_at = ?, finished_at = NULL,"
|
|
392
|
+
" attempts = attempts + 1, error = NULL WHERE id = ? AND status = 'queued'",
|
|
393
|
+
(time.time(), task_id),
|
|
394
|
+
)
|
|
395
|
+
return cur.rowcount == 1
|
|
396
|
+
|
|
397
|
+
# --------------------------------------------------------- codex runs
|
|
398
|
+
def add_codex_run(self, run_id: str, *, account: str, name: str, cwd: str,
|
|
399
|
+
log_path: str, pid: int | None, prompt: str, model: str | None,
|
|
400
|
+
sandbox: str, thread_id: str | None = None) -> None:
|
|
401
|
+
self.conn.execute(
|
|
402
|
+
"INSERT INTO codex_runs(id, account, name, cwd, pid, log_path, thread_id, model,"
|
|
403
|
+
" sandbox, prompt, started_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)",
|
|
404
|
+
(run_id, account, name, cwd, pid, log_path, thread_id, model, sandbox, prompt,
|
|
405
|
+
time.time()))
|
|
406
|
+
|
|
407
|
+
def codex_runs(self, account: str | None = None, *, include_hidden: bool = False,
|
|
408
|
+
thread_id: str | None = None) -> list[sqlite3.Row]:
|
|
409
|
+
q, vals = "SELECT * FROM codex_runs WHERE 1=1", []
|
|
410
|
+
if account is not None:
|
|
411
|
+
q += " AND account = ?"
|
|
412
|
+
vals.append(account)
|
|
413
|
+
if thread_id is not None:
|
|
414
|
+
q += " AND thread_id = ?"
|
|
415
|
+
vals.append(thread_id)
|
|
416
|
+
if not include_hidden:
|
|
417
|
+
q += " AND hidden = 0"
|
|
418
|
+
return self.conn.execute(q + " ORDER BY started_at", vals).fetchall()
|
|
419
|
+
|
|
420
|
+
def get_codex_run(self, run_id: str) -> sqlite3.Row | None:
|
|
421
|
+
return self.conn.execute("SELECT * FROM codex_runs WHERE id = ?", (run_id,)).fetchone()
|
|
422
|
+
|
|
423
|
+
def update_codex_run(self, run_id: str, **fields) -> None:
|
|
424
|
+
allowed = {"pid", "thread_id", "stopped", "hidden"}
|
|
425
|
+
sets = []
|
|
426
|
+
for k in fields:
|
|
427
|
+
if k not in allowed:
|
|
428
|
+
raise KeyError(k)
|
|
429
|
+
sets.append(f"{k} = ?")
|
|
430
|
+
if sets:
|
|
431
|
+
self.conn.execute(f"UPDATE codex_runs SET {', '.join(sets)} WHERE id = ?",
|
|
432
|
+
[*fields.values(), run_id])
|
|
433
|
+
|
|
434
|
+
def delete_task(self, task_id: int) -> None:
|
|
435
|
+
self.conn.execute("DELETE FROM tasks WHERE id = ?", (task_id,))
|
|
436
|
+
|
|
437
|
+
# ---------------------------------------------------------- templates
|
|
438
|
+
def list_templates(self) -> list[Template]:
|
|
439
|
+
rows = self.conn.execute("SELECT * FROM templates ORDER BY lower(name)").fetchall()
|
|
440
|
+
return [Template(r["id"], r["name"], r["body"], r["created_at"]) for r in rows]
|
|
441
|
+
|
|
442
|
+
def save_template(self, name: str, body: str) -> None:
|
|
443
|
+
self.conn.execute(
|
|
444
|
+
"INSERT INTO templates(name, body, created_at) VALUES (?,?,?) "
|
|
445
|
+
"ON CONFLICT(name) DO UPDATE SET body = excluded.body",
|
|
446
|
+
(name.strip(), body, time.time()),
|
|
447
|
+
)
|
|
448
|
+
|
|
449
|
+
def delete_template(self, template_id: int) -> None:
|
|
450
|
+
self.conn.execute("DELETE FROM templates WHERE id = ?", (template_id,))
|
|
451
|
+
|
|
452
|
+
# ----------------------------------------------------------- launches
|
|
453
|
+
def record_launch(
|
|
454
|
+
self,
|
|
455
|
+
name: str,
|
|
456
|
+
*,
|
|
457
|
+
project_id: int | None,
|
|
458
|
+
task_id: int | None = None,
|
|
459
|
+
model: str | None = None,
|
|
460
|
+
permission_mode: str | None = None,
|
|
461
|
+
worktree: str | None = None,
|
|
462
|
+
prompt: str | None = None,
|
|
463
|
+
agent_id: str | None = None,
|
|
464
|
+
) -> None:
|
|
465
|
+
self.conn.execute(
|
|
466
|
+
"INSERT OR REPLACE INTO launches(name, agent_id, project_id, task_id, model,"
|
|
467
|
+
" permission_mode, worktree, prompt, launched_at) VALUES (?,?,?,?,?,?,?,?,?)",
|
|
468
|
+
(name, agent_id, project_id, task_id, model, permission_mode, worktree, prompt,
|
|
469
|
+
time.time()),
|
|
470
|
+
)
|
|
471
|
+
|
|
472
|
+
def bind_launch(self, name: str, agent_id: str) -> None:
|
|
473
|
+
self.conn.execute("UPDATE launches SET agent_id = ? WHERE name = ?", (agent_id, name))
|
|
474
|
+
|
|
475
|
+
def launches(self) -> dict[str, sqlite3.Row]:
|
|
476
|
+
"""Launch records keyed by session name."""
|
|
477
|
+
rows = self.conn.execute("SELECT * FROM launches").fetchall()
|
|
478
|
+
return {r["name"]: r for r in rows}
|
|
479
|
+
|
|
480
|
+
# ----------------------------------------------------------- activity
|
|
481
|
+
def log(self, level: str, message: str, project_id: int | None = None) -> Activity:
|
|
482
|
+
ts = time.time()
|
|
483
|
+
message = redact(message)
|
|
484
|
+
cur = self.conn.execute(
|
|
485
|
+
"INSERT INTO activity(ts, level, message, project_id) VALUES (?,?,?,?)",
|
|
486
|
+
(ts, level, message, project_id),
|
|
487
|
+
)
|
|
488
|
+
# keep history bounded
|
|
489
|
+
if cur.lastrowid and cur.lastrowid % 500 == 0:
|
|
490
|
+
self.conn.execute(
|
|
491
|
+
"DELETE FROM activity WHERE id <= (SELECT max(id) - 5000 FROM activity)"
|
|
492
|
+
)
|
|
493
|
+
return Activity(cur.lastrowid or 0, ts, level, message, project_id)
|
|
494
|
+
|
|
495
|
+
def recent_activity(self, limit: int = 100) -> list[Activity]:
|
|
496
|
+
rows = self.conn.execute(
|
|
497
|
+
"SELECT * FROM activity ORDER BY id DESC LIMIT ?", (limit,)
|
|
498
|
+
).fetchall()
|
|
499
|
+
return [Activity(r["id"], r["ts"], r["level"], r["message"], r["project_id"])
|
|
500
|
+
for r in reversed(rows)]
|
|
501
|
+
|
|
502
|
+
# ----------------------------------------------------------------- kv
|
|
503
|
+
def get_kv(self, key: str, default: str | None = None) -> str | None:
|
|
504
|
+
r = self.conn.execute("SELECT v FROM kv WHERE k = ?", (key,)).fetchone()
|
|
505
|
+
return r["v"] if r else default
|
|
506
|
+
|
|
507
|
+
def set_kv(self, key: str, value: str) -> None:
|
|
508
|
+
self.conn.execute(
|
|
509
|
+
"INSERT INTO kv(k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v",
|
|
510
|
+
(key, value),
|
|
511
|
+
)
|
fleetdeck/gitinfo.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""Async, read-only git queries with a small TTL cache."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import re
|
|
7
|
+
import time
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
|
|
10
|
+
from .proc import run
|
|
11
|
+
|
|
12
|
+
_BRACE_RENAME = re.compile(r"\{([^{}]*) => ([^{}]*)\}")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(slots=True)
|
|
16
|
+
class FileChange:
|
|
17
|
+
path: str
|
|
18
|
+
status: str # porcelain XY code, e.g. " M", "??", "A "
|
|
19
|
+
added: int | None = None
|
|
20
|
+
deleted: int | None = None
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(slots=True)
|
|
24
|
+
class GitSnapshot:
|
|
25
|
+
is_repo: bool
|
|
26
|
+
root: str | None = None
|
|
27
|
+
branch: str | None = None
|
|
28
|
+
changes: list[FileChange] = field(default_factory=list)
|
|
29
|
+
ahead: int | None = None
|
|
30
|
+
behind: int | None = None
|
|
31
|
+
error: str | None = None
|
|
32
|
+
taken_at: float = 0.0
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def total_added(self) -> int:
|
|
36
|
+
return sum(c.added or 0 for c in self.changes)
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def total_deleted(self) -> int:
|
|
40
|
+
return sum(c.deleted or 0 for c in self.changes)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
async def _git(cwd: str, *args: str, timeout: float = 8.0) -> tuple[int, str, str]:
|
|
44
|
+
return await run(
|
|
45
|
+
["git", "-C", cwd, "--no-optional-locks", *args],
|
|
46
|
+
timeout=timeout,
|
|
47
|
+
env={"GIT_TERMINAL_PROMPT": "0", "GIT_PAGER": "cat", "LC_ALL": "C"},
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def parse_porcelain(text: str) -> tuple[str | None, int | None, int | None, list[FileChange]]:
|
|
52
|
+
"""Parse `git status --porcelain=v1 -b` output."""
|
|
53
|
+
branch = ahead = behind = None
|
|
54
|
+
changes: list[FileChange] = []
|
|
55
|
+
for line in text.splitlines():
|
|
56
|
+
if line.startswith("## "):
|
|
57
|
+
head = line[3:]
|
|
58
|
+
info = ""
|
|
59
|
+
if " [" in head:
|
|
60
|
+
head, info = head.split(" [", 1)
|
|
61
|
+
branch = head.split("...", 1)[0]
|
|
62
|
+
if branch.startswith("No commits yet on "):
|
|
63
|
+
branch = branch.removeprefix("No commits yet on ")
|
|
64
|
+
elif branch.startswith("HEAD (no branch)"):
|
|
65
|
+
branch = "(detached)"
|
|
66
|
+
for part in info.rstrip("]").split(", "):
|
|
67
|
+
if part.startswith("ahead "):
|
|
68
|
+
ahead = int(part[6:])
|
|
69
|
+
elif part.startswith("behind "):
|
|
70
|
+
behind = int(part[7:])
|
|
71
|
+
elif len(line) > 3:
|
|
72
|
+
path = line[3:]
|
|
73
|
+
if " -> " in path:
|
|
74
|
+
path = path.split(" -> ", 1)[1]
|
|
75
|
+
changes.append(FileChange(path=path.strip('"'), status=line[:2]))
|
|
76
|
+
return branch, ahead, behind, changes
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def parse_numstat(text: str) -> dict[str, tuple[int | None, int | None]]:
|
|
80
|
+
out: dict[str, tuple[int | None, int | None]] = {}
|
|
81
|
+
for line in text.splitlines():
|
|
82
|
+
parts = line.split("\t")
|
|
83
|
+
if len(parts) < 3:
|
|
84
|
+
continue
|
|
85
|
+
a, d, path = parts[0], parts[1], parts[-1]
|
|
86
|
+
if " => " in path: # rename: "dir/{old => new}.py" or "old => new"
|
|
87
|
+
if "{" in path:
|
|
88
|
+
path = _BRACE_RENAME.sub(lambda m: m.group(2), path).replace("//", "/")
|
|
89
|
+
else:
|
|
90
|
+
path = path.split(" => ")[-1]
|
|
91
|
+
out[path] = (int(a) if a.isdigit() else None, int(d) if d.isdigit() else None)
|
|
92
|
+
return out
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
async def snapshot(cwd: str) -> GitSnapshot:
|
|
96
|
+
code, out, err = await _git(cwd, "rev-parse", "--show-toplevel")
|
|
97
|
+
if code != 0:
|
|
98
|
+
return GitSnapshot(is_repo=False, taken_at=time.time())
|
|
99
|
+
root = out.strip()
|
|
100
|
+
(c1, status_out, e1), (c2, numstat_out, _) = await asyncio.gather(
|
|
101
|
+
_git(cwd, "status", "--porcelain=v1", "-b", "--untracked-files=normal"),
|
|
102
|
+
_git(cwd, "diff", "HEAD", "--numstat"),
|
|
103
|
+
)
|
|
104
|
+
if c1 != 0:
|
|
105
|
+
return GitSnapshot(is_repo=True, root=root, error=e1.strip(), taken_at=time.time())
|
|
106
|
+
branch, ahead, behind, changes = parse_porcelain(status_out)
|
|
107
|
+
stats = parse_numstat(numstat_out) if c2 == 0 else {}
|
|
108
|
+
for ch in changes:
|
|
109
|
+
if ch.path in stats:
|
|
110
|
+
ch.added, ch.deleted = stats[ch.path]
|
|
111
|
+
return GitSnapshot(
|
|
112
|
+
is_repo=True, root=root, branch=branch, changes=changes,
|
|
113
|
+
ahead=ahead, behind=behind, taken_at=time.time(),
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
async def diff(cwd: str, max_bytes: int = 400_000) -> str:
|
|
118
|
+
"""Working-tree diff against HEAD (falls back to the index for new repos)."""
|
|
119
|
+
code, out, err = await _git(cwd, "diff", "HEAD", "--no-color", "--stat", "--patch")
|
|
120
|
+
if code != 0:
|
|
121
|
+
code, out, err = await _git(cwd, "diff", "--no-color", "--stat", "--patch")
|
|
122
|
+
if code != 0:
|
|
123
|
+
return f"git diff failed: {err.strip()}"
|
|
124
|
+
if len(out) > max_bytes:
|
|
125
|
+
out = out[:max_bytes] + f"\n… diff truncated at {max_bytes // 1000} kB …\n"
|
|
126
|
+
return out
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
async def has_commits(cwd: str) -> bool:
|
|
130
|
+
code, _, _ = await _git(cwd, "rev-parse", "--verify", "--quiet", "HEAD")
|
|
131
|
+
return code == 0
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
async def repo_root(cwd: str) -> str | None:
|
|
135
|
+
code, out, _ = await _git(cwd, "rev-parse", "--show-toplevel")
|
|
136
|
+
return out.strip() if code == 0 else None
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class GitCache:
|
|
140
|
+
"""Per-directory snapshot cache so polling never fans out git calls."""
|
|
141
|
+
|
|
142
|
+
def __init__(self, ttl: float = 5.0) -> None:
|
|
143
|
+
self.ttl = ttl
|
|
144
|
+
self._data: dict[str, GitSnapshot] = {}
|
|
145
|
+
self._inflight: dict[str, asyncio.Task[GitSnapshot]] = {}
|
|
146
|
+
|
|
147
|
+
def peek(self, cwd: str) -> GitSnapshot | None:
|
|
148
|
+
return self._data.get(cwd)
|
|
149
|
+
|
|
150
|
+
async def get(self, cwd: str, *, force: bool = False) -> GitSnapshot:
|
|
151
|
+
snap = self._data.get(cwd)
|
|
152
|
+
if snap and not force and time.time() - snap.taken_at < self.ttl:
|
|
153
|
+
return snap
|
|
154
|
+
task = self._inflight.get(cwd)
|
|
155
|
+
if task is None:
|
|
156
|
+
task = asyncio.ensure_future(snapshot(cwd))
|
|
157
|
+
self._inflight[cwd] = task
|
|
158
|
+
try:
|
|
159
|
+
snap = await task
|
|
160
|
+
finally:
|
|
161
|
+
self._inflight.pop(cwd, None)
|
|
162
|
+
self._data[cwd] = snap
|
|
163
|
+
return snap
|
|
164
|
+
|
|
165
|
+
def invalidate(self, cwd: str | None = None) -> None:
|
|
166
|
+
if cwd is None:
|
|
167
|
+
self._data.clear()
|
|
168
|
+
else:
|
|
169
|
+
self._data.pop(cwd, None)
|