@ai-devkit/agent-manager 0.40.0 → 0.41.0

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.
@@ -0,0 +1,349 @@
1
+ /**
2
+ * Capture a live fixture bundle for an adapter: snapshot the real process
3
+ * list, run detectAgents with a frozen clock, and record expected output
4
+ * plus the session files the detection touched.
5
+ *
6
+ * Run via `AI_DEVKIT_FIXTURE_CAPTURE=1 npx vitest run fixtures.capture`.
7
+ */
8
+
9
+ import * as fs from "node:fs";
10
+ import * as os from "node:os";
11
+ import * as path from "node:path";
12
+ import { fileURLToPath } from "node:url";
13
+ import Database from "better-sqlite3";
14
+ import type { AgentAdapter, AgentInfo } from "../adapters/AgentAdapter.js";
15
+ import { AgentRegistry } from "../utils/AgentRegistry.js";
16
+ import { captureProcessSnapshot } from "../utils/process.js";
17
+ import { FixtureBundle, normalizeAgents, sanitize, withFrozenClock } from "./bundle.js";
18
+
19
+ const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../../..");
20
+ export const FIXTURES_ROOT = path.join(repoRoot, "fixtures", "harness");
21
+
22
+ /** Session-file trees each harness consults during detection. */
23
+ const HARNESS_DIRS: Record<string, string[]> = {
24
+ claude: [".claude/sessions", ".claude/projects"],
25
+ codex: [".codex/sessions", ".codex/archived_sessions", ".codex/ai-devkit"],
26
+ pi: [".pi/agent/sessions"],
27
+ // tmp/<shortId>/{.project_root,chats/*} — small tree; index-style capture
28
+ // keeps the ownership markers replay needs for slug-dir attribution.
29
+ gemini_cli: [".gemini/tmp"],
30
+ // session-state/<id>/{inuse.*.lock,events.jsonl,workspace.yaml} — the lock
31
+ // files drive attribution, so the whole tree must materialize on replay.
32
+ copilot: [".copilot/session-state"],
33
+ grok_cli: [".grok/sessions"],
34
+ // session_locks/<slug>.lock — pid-holder files read on every detect.
35
+ devin: [".local/share/devin/cli/session_locks"],
36
+ // sessions/cli/<id>.{lock,json,jsonl} — locks drive attribution; the
37
+ // whole flat dir is lightweight enough for index-style capture.
38
+ kiro: [".kiro/sessions/cli"],
39
+ // antigravity-cli/{cache,brain} — last_conversations.json (small .json
40
+ // aux) plus only the transcripts referenced by matched agents; the
41
+ // brain tree is tens of MB so it stays referenced-only (not index).
42
+ antigravity_cli: [".gemini/antigravity-cli"],
43
+ };
44
+
45
+ /**
46
+ * Dirs captured wholesale (lock/index trees where every file matters —
47
+ * copilot lock dirs, kiro/devin locks, the codex mapping dir, the gemini
48
+ * tmp tree). Everything else captures agent-referenced session files
49
+ * plus small .json aux files.
50
+ */
51
+ const HARNESS_INDEX_DIRS = new Set([
52
+ ".gemini/tmp",
53
+ ".copilot/session-state",
54
+ ".codex/ai-devkit",
55
+ ".local/share/devin/cli/session_locks",
56
+ ".kiro/sessions/cli",
57
+ ]);
58
+
59
+ /** Individual files (not dirs) each harness consults during detection. */
60
+ const HARNESS_FILES: Record<string, string[]> = {
61
+ pi: [".pi/agent/sessions.json"],
62
+ grok_cli: [".grok/active_sessions.json"],
63
+ };
64
+
65
+ /**
66
+ * Copy the harness's session dirs into `home` — only files the detection
67
+ * actually touched (referenced sessionFilePath) plus index/pid files.
68
+ * Transcript trees can be large; we include full files only for sessions
69
+ * that produced an agent, plus every file in lightweight index dirs.
70
+ */
71
+ function collectHomeFiles(
72
+ adapterType: string,
73
+ realHome: string,
74
+ agents: AgentInfo[],
75
+ ): { home: Record<string, string>; mtimes: Record<string, number> } {
76
+ const home: Record<string, string> = {};
77
+ const mtimes: Record<string, number> = {};
78
+ const referenced = new Set(
79
+ agents.map((a) => a.sessionFilePath).filter((p): p is string => Boolean(p)),
80
+ );
81
+
82
+ const put = (rel: string, file: string) => {
83
+ home[rel] = sanitize(fs.readFileSync(file, "utf8"), realHome);
84
+ // Real mtimes are captured too — adapters that read them (Grok
85
+ // lastActive, latest-session pick) replay deterministically.
86
+ mtimes[rel] = fs.statSync(file).mtimeMs;
87
+ };
88
+
89
+ for (const relDir of HARNESS_DIRS[adapterType] ?? []) {
90
+ const dir = path.join(realHome, relDir);
91
+ if (!fs.existsSync(dir)) continue;
92
+ // Session trees can hold months of transcripts; files that produced no
93
+ // agent cannot influence replayed output, so only agent-referenced
94
+ // session files plus small aux/index files are copied.
95
+ const isIndexDir = HARNESS_INDEX_DIRS.has(relDir);
96
+ walk(dir, (file) => {
97
+ const rel = path.join(relDir, path.relative(dir, file));
98
+ const isAuxIndex = rel.endsWith("sessions.json") || rel.endsWith(".json");
99
+ if (isIndexDir || referenced.has(file) || (isAuxIndex && fileSize(file) < 64 * 1024)) {
100
+ put(rel, file);
101
+ }
102
+ });
103
+ }
104
+ for (const relFile of HARNESS_FILES[adapterType] ?? []) {
105
+ const file = path.join(realHome, relFile);
106
+ if (fs.existsSync(file) && fileSize(file) < 64 * 1024) {
107
+ put(relFile, file);
108
+ }
109
+ }
110
+ return { home, mtimes };
111
+ }
112
+
113
+ /**
114
+ * SQLite stores adapters consult (OpenCode's opencode.db). Sessions are
115
+ * reachable only through captured processes' cwds, so the dump keeps the
116
+ * table DDL plus every session row for those directories and their
117
+ * message/part rows — replay answers identical queries against the same
118
+ * view. Rows are serialized as executable SQL (binary dbs can't travel in
119
+ * the JSON `home` map); the key is the canonical `~/.local/share` relpath,
120
+ * which replay pins via XDG_DATA_HOME.
121
+ */
122
+ function collectSqliteDumps(
123
+ adapterType: string,
124
+ realHome: string,
125
+ processes: { cwd?: string | null }[],
126
+ ): Record<string, string[]> {
127
+ const share = process.env.XDG_DATA_HOME || path.join(realHome, ".local", "share");
128
+ if (adapterType === "opencode") {
129
+ return dumpSqliteDb(
130
+ path.join(share, "opencode", "opencode.db"),
131
+ ".local/share/opencode/opencode.db",
132
+ realHome,
133
+ (dump) => {
134
+ const dirs = uniqueCwds(processes);
135
+ if (dirs.length === 0) return;
136
+ const sessions = dump.rows("session", `WHERE directory IN ${dump.inList(dirs)} ORDER BY rowid`, dirs);
137
+ const sids = sessions.map((s) => s.id);
138
+ dump.insertRows("session", sessions);
139
+ if (sids.length === 0) return;
140
+ dump.insertRows("message", dump.rows("message", `WHERE session_id IN ${dump.inList(sids)} ORDER BY rowid`, sids));
141
+ dump.insertRows("part", dump.rows("part", `WHERE session_id IN ${dump.inList(sids)} ORDER BY rowid`, sids));
142
+ },
143
+ ["session", "message", "part"],
144
+ );
145
+ }
146
+ if (adapterType === "devin") {
147
+ const dbPath = path.join(share, "devin", "cli", "sessions.db");
148
+ // Locks are captured separately as text files; slugs here widen the
149
+ // session row set so lock-slug lookups resolve identically on replay.
150
+ const lockSids = fs.existsSync(path.join(path.dirname(dbPath), "session_locks"))
151
+ ? fs
152
+ .readdirSync(path.join(path.dirname(dbPath), "session_locks"))
153
+ .filter((f) => f.endsWith(".lock"))
154
+ .map((f) => f.slice(0, -".lock".length))
155
+ .filter(Boolean)
156
+ : [];
157
+ return dumpSqliteDb(
158
+ dbPath,
159
+ ".local/share/devin/cli/sessions.db",
160
+ realHome,
161
+ (dump) => {
162
+ const dirs = uniqueCwds(processes);
163
+ const clauses: string[] = [];
164
+ const args: unknown[] = [];
165
+ if (dirs.length) {
166
+ clauses.push(`working_directory IN ${dump.inList(dirs)}`);
167
+ args.push(...dirs);
168
+ }
169
+ if (lockSids.length) {
170
+ clauses.push(`id IN ${dump.inList(lockSids)}`);
171
+ args.push(...lockSids);
172
+ }
173
+ const sessions = clauses.length ? dump.rows("sessions", `WHERE ${clauses.join(" OR ")} ORDER BY rowid`, args) : [];
174
+ const sids = sessions.map((s) => s.id);
175
+ dump.insertRows("sessions", sessions);
176
+ if (sids.length === 0) return;
177
+ // Only the rows getSessionStats can reach: the frontier node, the
178
+ // MAX(created_at) node, the 8 newest role='user' nodes, and the
179
+ // newest non-shell non-slash prompt — identical query results on
180
+ // replay without hauling full transcripts into the bundle.
181
+ for (const sid of sids) {
182
+ const reachable = [
183
+ ...dump.rows("message_nodes", "WHERE session_id = ? ORDER BY node_id DESC LIMIT 1", [sid]),
184
+ // The newest-created_at row — `MAX(created_at)` reads only the
185
+ // value, and `= MAX(...)` unbounded explodes when batch-written
186
+ // nodes share a timestamp.
187
+ ...dump.rows("message_nodes", "WHERE session_id = ? ORDER BY created_at DESC, node_id DESC LIMIT 1", [sid]),
188
+ ...dump.rows(
189
+ "message_nodes",
190
+ "WHERE session_id = ? AND json_extract(chat_message, '$.role') = 'user' ORDER BY node_id DESC LIMIT 8",
191
+ [sid],
192
+ ),
193
+ ];
194
+ const seen = new Set<unknown>();
195
+ dump.insertRows(
196
+ "message_nodes",
197
+ reachable.filter((r) => (seen.has(r.node_id) ? false : (seen.add(r.node_id), true))),
198
+ );
199
+ dump.insertRows(
200
+ "prompt_history",
201
+ dump.rows(
202
+ "prompt_history",
203
+ "WHERE session_id = ? AND is_shell = 0 AND content NOT LIKE '/%' ORDER BY timestamp DESC LIMIT 1",
204
+ [sid],
205
+ ),
206
+ );
207
+ }
208
+ },
209
+ ["sessions", "message_nodes", "prompt_history"],
210
+ );
211
+ }
212
+ return {};
213
+ }
214
+
215
+ function uniqueCwds(processes: { cwd?: string | null }[]): string[] {
216
+ return [...new Set(processes.map((p) => p.cwd).filter((c): c is string => Boolean(c)))];
217
+ }
218
+
219
+ /**
220
+ * Dump `dbPath`'s tables (DDL + caller-selected rows) as executable SQL,
221
+ * keyed under `relKey`. `fill` receives helpers that append INSERTs for
222
+ * the rows the adapter's detection can reach.
223
+ */
224
+ function dumpSqliteDb(
225
+ dbPath: string,
226
+ relKey: string,
227
+ realHome: string,
228
+ fill: (dump: {
229
+ inList: (xs: unknown[]) => string;
230
+ rows: (table: string, where: string, args: unknown[]) => Record<string, unknown>[];
231
+ insertRows: (table: string, rs: Record<string, unknown>[]) => void;
232
+ }) => void,
233
+ tables: string[],
234
+ ): Record<string, string[]> {
235
+ if (!fs.existsSync(dbPath)) return {};
236
+ const db = new Database(dbPath, { readonly: true });
237
+ try {
238
+ const stmts = (
239
+ db
240
+ .prepare(
241
+ `SELECT sql FROM sqlite_master WHERE type='table' AND name IN (${tables.map(() => "?").join(",")})`,
242
+ )
243
+ .all(...tables) as { sql: string }[]
244
+ ).map((r) => `${r.sql};`);
245
+ const dump = {
246
+ inList: (xs: unknown[]) => `(${xs.map(() => "?").join(",")})`,
247
+ rows: (table: string, clause: string, args: unknown[]) =>
248
+ db.prepare(`SELECT * FROM "${table}" ${clause}`).all(...args) as Record<
249
+ string,
250
+ unknown
251
+ >[],
252
+ insertRows: (table: string, rs: Record<string, unknown>[]) => {
253
+ for (const r of rs) {
254
+ stmts.push(
255
+ `INSERT INTO "${table}" VALUES (${Object.values(r).map(sqlLit).join(",")});`,
256
+ );
257
+ }
258
+ },
259
+ };
260
+ fill(dump);
261
+ return { [relKey]: stmts.map((s) => sanitize(s, realHome)) };
262
+ } finally {
263
+ db.close();
264
+ }
265
+ }
266
+
267
+ function sqlLit(v: unknown): string {
268
+ if (v === null || v === undefined) return "NULL";
269
+ if (typeof v === "number" || typeof v === "bigint") return String(v);
270
+ if (v instanceof Uint8Array) return `X'${Buffer.from(v).toString("hex")}'`;
271
+ return `'${String(v).split("'").join("''")}'`;
272
+ }
273
+
274
+ /**
275
+ * Registry rows keyed to captured pids — adapters' registry caches consult
276
+ * them during detection, so replay must see the same view (otherwise
277
+ * ordering/attribution diverges: cache hits precede locator matches).
278
+ */
279
+ function collectRegistryEntries(
280
+ realHome: string,
281
+ processes: { pid: number }[],
282
+ ): Record<string, unknown>[] {
283
+ const pids = new Set(processes.map((p) => p.pid));
284
+ try {
285
+ return AgentRegistry.default()
286
+ .list()
287
+ .filter((e) => pids.has(e.pid))
288
+ .map((e) => sanitize({ ...e }, realHome) as Record<string, unknown>);
289
+ } catch {
290
+ return [];
291
+ }
292
+ }
293
+
294
+ function fileSize(file: string): number {
295
+ try {
296
+ return fs.statSync(file).size;
297
+ } catch {
298
+ return Infinity;
299
+ }
300
+ }
301
+
302
+ function walk(dir: string, visit: (file: string) => void, depth = 0) {
303
+ if (depth > 4) return;
304
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
305
+ const p = path.join(dir, entry.name);
306
+ if (entry.isDirectory()) walk(p, visit, depth + 1);
307
+ else if (entry.isFile()) visit(p);
308
+ }
309
+ }
310
+
311
+ export async function captureLive(adapter: AgentAdapter, caseName = "live"): Promise<string> {
312
+ const realHome = os.homedir();
313
+ const frozenNow = Date.now();
314
+ const names = adapter.processNames;
315
+ if (!names?.length) {
316
+ throw new Error(`adapter ${adapter.type} has no processNames — can't snapshot`);
317
+ }
318
+
319
+ const { processes, agents, registry } = await withFrozenClock(frozenNow, async () => {
320
+ const snapshot = await captureProcessSnapshot([...names], {
321
+ isCandidate: (p) => adapter.canHandle(p),
322
+ });
323
+ // Registry read must precede detection — detectAgents persists its own
324
+ // results, which would poison the captured view.
325
+ const registryBefore = collectRegistryEntries(realHome, snapshot);
326
+ const detected = await adapter.detectAgents({ processes: snapshot });
327
+ return { processes: snapshot, agents: detected, registry: registryBefore };
328
+ });
329
+
330
+ const { home, mtimes } = collectHomeFiles(adapter.type, realHome, agents);
331
+ const sqlite = collectSqliteDumps(adapter.type, realHome, processes);
332
+ const bundle: FixtureBundle = {
333
+ adapter: adapter.type,
334
+ capturedAt: new Date(frozenNow).toISOString(),
335
+ frozenNow,
336
+ processes: sanitize(processes, realHome),
337
+ home,
338
+ mtimes,
339
+ registry,
340
+ sqlite: Object.keys(sqlite).length > 0 ? sqlite : undefined,
341
+ expected: normalizeAgents(agents, realHome),
342
+ };
343
+
344
+ const dir = path.join(FIXTURES_ROOT, adapter.type);
345
+ fs.mkdirSync(dir, { recursive: true });
346
+ const out = path.join(dir, `${caseName}.json`);
347
+ fs.writeFileSync(out, JSON.stringify(bundle, null, 2));
348
+ return out;
349
+ }
@@ -67,7 +67,7 @@ export function matchesExecutable(command: string, name: string): boolean {
67
67
  export function processOnlyAgent(
68
68
  type: AgentType,
69
69
  processInfo: ProcessInfo,
70
- { summary, cwd = processInfo.cwd }: { summary: string; cwd?: string },
70
+ { summary, cwd = processInfo.cwd ?? "" }: { summary: string; cwd?: string },
71
71
  ): AgentInfo {
72
72
  return {
73
73
  name: generateAgentName(cwd, processInfo.pid),