@ai-devkit/agent-manager 0.40.0 → 0.42.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.
Files changed (115) hide show
  1. package/dist/AgentManager.d.ts +12 -0
  2. package/dist/AgentManager.d.ts.map +1 -1
  3. package/dist/AgentManager.js +45 -10
  4. package/dist/AgentManager.js.map +1 -1
  5. package/dist/__tests__/AgentManager.test.js +111 -0
  6. package/dist/__tests__/AgentManager.test.js.map +1 -1
  7. package/dist/__tests__/fixtures.test.js +218 -0
  8. package/dist/__tests__/fixtures.test.js.map +1 -0
  9. package/dist/__tests__/harnesses/devin/DevinAdapter.test.js.map +1 -1
  10. package/dist/__tests__/harnesses/devin/DevinSessionParser.test.js.map +1 -1
  11. package/dist/__tests__/harnesses/muse/MuseAdapter.test.js +247 -0
  12. package/dist/__tests__/harnesses/muse/MuseAdapter.test.js.map +1 -0
  13. package/dist/__tests__/harnesses/muse/MuseAgentMapper.test.js +81 -0
  14. package/dist/__tests__/harnesses/muse/MuseAgentMapper.test.js.map +1 -0
  15. package/dist/__tests__/harnesses/muse/MuseSessionLocator.test.js +185 -0
  16. package/dist/__tests__/harnesses/muse/MuseSessionLocator.test.js.map +1 -0
  17. package/dist/__tests__/harnesses/muse/MuseSessionParser.test.js +328 -0
  18. package/dist/__tests__/harnesses/muse/MuseSessionParser.test.js.map +1 -0
  19. package/dist/__tests__/harnesses/opencode/OpenCodeSessionParser.test.js.map +1 -1
  20. package/dist/__tests__/harnesses/readiness/AgentReadiness.test.js +42 -1
  21. package/dist/__tests__/harnesses/readiness/AgentReadiness.test.js.map +1 -1
  22. package/dist/__tests__/harnesses/runtimeProfiles.test.js +12 -0
  23. package/dist/__tests__/harnesses/runtimeProfiles.test.js.map +1 -1
  24. package/dist/__tests__/readiness-fixtures.test.js +54 -0
  25. package/dist/__tests__/readiness-fixtures.test.js.map +1 -0
  26. package/dist/__tests__/utils/process.test.js +71 -1
  27. package/dist/__tests__/utils/process.test.js.map +1 -1
  28. package/dist/adapters/AgentAdapter.d.ts +8 -1
  29. package/dist/adapters/AgentAdapter.d.ts.map +1 -1
  30. package/dist/adapters/AgentAdapter.js +2 -1
  31. package/dist/adapters/AgentAdapter.js.map +1 -1
  32. package/dist/fixtures/bundle.d.ts +67 -0
  33. package/dist/fixtures/bundle.d.ts.map +1 -0
  34. package/dist/fixtures/bundle.js +86 -0
  35. package/dist/fixtures/bundle.js.map +1 -0
  36. package/dist/fixtures/capture.d.ts +11 -0
  37. package/dist/fixtures/capture.d.ts.map +1 -0
  38. package/dist/fixtures/capture.js +318 -0
  39. package/dist/fixtures/capture.js.map +1 -0
  40. package/dist/harnesses/devin/DevinAdapter.d.ts.map +1 -1
  41. package/dist/harnesses/devin/DevinAdapter.js.map +1 -1
  42. package/dist/harnesses/devin/DevinAgentMapper.d.ts.map +1 -1
  43. package/dist/harnesses/devin/DevinAgentMapper.js.map +1 -1
  44. package/dist/harnesses/devin/DevinSessionParser.d.ts.map +1 -1
  45. package/dist/harnesses/devin/DevinSessionParser.js.map +1 -1
  46. package/dist/harnesses/index.d.ts.map +1 -1
  47. package/dist/harnesses/index.js +3 -1
  48. package/dist/harnesses/index.js.map +1 -1
  49. package/dist/harnesses/muse/MuseAdapter.d.ts +33 -0
  50. package/dist/harnesses/muse/MuseAdapter.d.ts.map +1 -0
  51. package/dist/harnesses/muse/MuseAdapter.js +122 -0
  52. package/dist/harnesses/muse/MuseAdapter.js.map +1 -0
  53. package/dist/harnesses/muse/MuseAgentMapper.d.ts +15 -0
  54. package/dist/harnesses/muse/MuseAgentMapper.d.ts.map +1 -0
  55. package/dist/harnesses/muse/MuseAgentMapper.js +29 -0
  56. package/dist/harnesses/muse/MuseAgentMapper.js.map +1 -0
  57. package/dist/harnesses/muse/MuseSessionLocator.d.ts +61 -0
  58. package/dist/harnesses/muse/MuseSessionLocator.d.ts.map +1 -0
  59. package/dist/harnesses/muse/MuseSessionLocator.js +233 -0
  60. package/dist/harnesses/muse/MuseSessionLocator.js.map +1 -0
  61. package/dist/harnesses/muse/MuseSessionParser.d.ts +77 -0
  62. package/dist/harnesses/muse/MuseSessionParser.d.ts.map +1 -0
  63. package/dist/harnesses/muse/MuseSessionParser.js +350 -0
  64. package/dist/harnesses/muse/MuseSessionParser.js.map +1 -0
  65. package/dist/harnesses/muse/readiness.d.ts +3 -0
  66. package/dist/harnesses/muse/readiness.d.ts.map +1 -0
  67. package/dist/harnesses/muse/readiness.js +37 -0
  68. package/dist/harnesses/muse/readiness.js.map +1 -0
  69. package/dist/harnesses/readiness/AgentReadiness.d.ts.map +1 -1
  70. package/dist/harnesses/readiness/AgentReadiness.js +3 -1
  71. package/dist/harnesses/readiness/AgentReadiness.js.map +1 -1
  72. package/dist/harnesses/readiness/types.d.ts +1 -1
  73. package/dist/harnesses/readiness/types.d.ts.map +1 -1
  74. package/dist/harnesses/runtimeProfiles.d.ts.map +1 -1
  75. package/dist/harnesses/runtimeProfiles.js +2 -1
  76. package/dist/harnesses/runtimeProfiles.js.map +1 -1
  77. package/dist/harnesses/shared.d.ts +1 -1
  78. package/dist/harnesses/shared.d.ts.map +1 -1
  79. package/dist/harnesses/shared.js +7 -6
  80. package/dist/harnesses/shared.js.map +1 -1
  81. package/dist/utils/process.d.ts +23 -1
  82. package/dist/utils/process.d.ts.map +1 -1
  83. package/dist/utils/process.js +44 -8
  84. package/dist/utils/process.js.map +1 -1
  85. package/package.json +1 -1
  86. package/src/AgentManager.ts +71 -9
  87. package/src/__tests__/AgentManager.test.ts +84 -0
  88. package/src/__tests__/fixtures.test.ts +245 -0
  89. package/src/__tests__/harnesses/devin/DevinAdapter.test.ts +1 -3
  90. package/src/__tests__/harnesses/devin/DevinSessionParser.test.ts +3 -9
  91. package/src/__tests__/harnesses/muse/MuseAdapter.test.ts +197 -0
  92. package/src/__tests__/harnesses/muse/MuseAgentMapper.test.ts +83 -0
  93. package/src/__tests__/harnesses/muse/MuseSessionLocator.test.ts +177 -0
  94. package/src/__tests__/harnesses/muse/MuseSessionParser.test.ts +279 -0
  95. package/src/__tests__/harnesses/opencode/OpenCodeSessionParser.test.ts +3 -2
  96. package/src/__tests__/harnesses/readiness/AgentReadiness.test.ts +36 -0
  97. package/src/__tests__/harnesses/runtimeProfiles.test.ts +13 -0
  98. package/src/__tests__/readiness-fixtures.test.ts +79 -0
  99. package/src/__tests__/utils/process.test.ts +30 -0
  100. package/src/adapters/AgentAdapter.ts +9 -0
  101. package/src/fixtures/bundle.ts +130 -0
  102. package/src/fixtures/capture.ts +364 -0
  103. package/src/harnesses/devin/DevinAdapter.ts +3 -15
  104. package/src/harnesses/devin/DevinAgentMapper.ts +1 -5
  105. package/src/harnesses/devin/DevinSessionParser.ts +3 -12
  106. package/src/harnesses/index.ts +2 -0
  107. package/src/harnesses/muse/MuseAdapter.ts +157 -0
  108. package/src/harnesses/muse/MuseAgentMapper.ts +33 -0
  109. package/src/harnesses/muse/MuseSessionLocator.ts +286 -0
  110. package/src/harnesses/muse/MuseSessionParser.ts +435 -0
  111. package/src/harnesses/muse/readiness.ts +38 -0
  112. package/src/harnesses/readiness/AgentReadiness.ts +2 -0
  113. package/src/harnesses/runtimeProfiles.ts +1 -0
  114. package/src/harnesses/shared.ts +11 -6
  115. package/src/utils/process.ts +61 -9
@@ -8,6 +8,8 @@
8
8
  import type {
9
9
  AgentAdapter,
10
10
  AgentInfo,
11
+ AgentStatus,
12
+ AgentType,
11
13
  SessionSummary,
12
14
  ListSessionsOptions,
13
15
  ProcessInfo,
@@ -22,6 +24,7 @@ import {
22
24
  import {
23
25
  captureProcessSnapshot,
24
26
  filterByProcessNames,
27
+ snapshotOptions,
25
28
  type ProcessSnapshotCapture,
26
29
  } from "./utils/process.js";
27
30
  import {
@@ -31,6 +34,17 @@ import {
31
34
  type HerdrAgentPane,
32
35
  } from "./runtime/herdr/HerdrAgentDiscovery.js";
33
36
 
37
+ /** Discovery patterns of one adapter: exact names plus basename prefixes. */
38
+ function adapterPatterns(adapter: AgentAdapter): {
39
+ names: string[];
40
+ prefixes: string[];
41
+ } {
42
+ return {
43
+ names: adapter.processNames ? [...adapter.processNames] : [],
44
+ prefixes: adapter.processNamePrefixes ? [...adapter.processNamePrefixes] : [],
45
+ };
46
+ }
47
+
34
48
  export interface ListAgentsOptions {
35
49
  /**
36
50
  * Sort key for the returned list. Defaults to `status`, which orders
@@ -45,6 +59,20 @@ export interface AgentManagerOptions {
45
59
  | (() => AgentRuntimeProvider | Promise<AgentRuntimeProvider>);
46
60
  fetchHerdrAgentPanes?: () => Promise<readonly HerdrAgentPane[]>;
47
61
  onRuntimeDiscoveryError?: (error: unknown) => void;
62
+ /**
63
+ * Daemon-side enriched agents ({@link DaemonClient.listAgents} wire
64
+ * shape: `AgentInfo` with `lastActive` as an ISO string). A non-null
65
+ * result is authoritative for every harness type — all local adapters
66
+ * are skipped. Returning null or throwing forces the local path;
67
+ * omitting it disables daemon consumption.
68
+ */
69
+ fetchEnrichedAgents?: () => Promise<Array<
70
+ Omit<AgentInfo, "lastActive" | "type" | "status"> & {
71
+ type: string;
72
+ status: string;
73
+ lastActive: string;
74
+ }
75
+ > | null>;
48
76
  }
49
77
 
50
78
  class AgentNotRunningError extends Error {
@@ -162,18 +190,46 @@ export class AgentManager {
162
190
  const allAgents: AgentInfo[] = [];
163
191
  const errors: Array<{ type: string; error: Error }> = [];
164
192
 
165
- const adapters = Array.from(this.adapters.values());
193
+ // A non-null daemon answer is authoritative for every harness type, so
194
+ // local adapters only run when the daemon is absent.
195
+ let daemonAgents: AgentInfo[] | null = null;
196
+ if (this.options.fetchEnrichedAgents) {
197
+ try {
198
+ const enriched = await this.options.fetchEnrichedAgents();
199
+ if (enriched) {
200
+ daemonAgents = enriched.map((a) => ({
201
+ ...a,
202
+ type: a.type as AgentType,
203
+ status: a.status as AgentStatus,
204
+ lastActive: new Date(a.lastActive),
205
+ }));
206
+ }
207
+ } catch {
208
+ daemonAgents = null;
209
+ }
210
+ }
211
+ if (daemonAgents) allAgents.push(...daemonAgents);
212
+
213
+ const adapters = daemonAgents ? [] : Array.from(this.adapters.values());
166
214
  const processNames = Array.from(
167
215
  new Set(
168
216
  adapters.flatMap((adapter) => (adapter.processNames ? [...adapter.processNames] : [])),
169
217
  ),
170
218
  );
219
+ const namePrefixes = Array.from(
220
+ new Set(
221
+ adapters.flatMap((adapter) =>
222
+ adapter.processNamePrefixes ? [...adapter.processNamePrefixes] : [],
223
+ ),
224
+ ),
225
+ );
171
226
  let processes: readonly ProcessInfo[] = [];
172
- if (processNames.length > 0) {
227
+ if (processNames.length > 0 || namePrefixes.length > 0) {
173
228
  try {
174
- processes = await this.captureSnapshot(processNames, {
175
- isCandidate: (process) => this.isCandidateProcess(adapters, process),
176
- });
229
+ processes = await this.captureSnapshot(
230
+ processNames,
231
+ snapshotOptions(namePrefixes, (process) => this.isCandidateProcess(adapters, process)),
232
+ );
177
233
  } catch {
178
234
  processes = [];
179
235
  }
@@ -182,9 +238,12 @@ export class AgentManager {
182
238
  // Query all adapters in parallel using executable-scoped slices of the shared snapshot.
183
239
  const adapterPromises = adapters.map(async (adapter) => {
184
240
  try {
185
- const agents = adapter.processNames
241
+ const hasPatterns =
242
+ adapter.processNames !== undefined || adapter.processNamePrefixes !== undefined;
243
+ const { names, prefixes } = adapterPatterns(adapter);
244
+ const agents = hasPatterns
186
245
  ? await adapter.detectAgents({
187
- processes: filterByProcessNames(processes, adapter.processNames),
246
+ processes: filterByProcessNames(processes, names, prefixes),
188
247
  })
189
248
  : await adapter.detectAgents();
190
249
  return { type: adapter.type, agents, error: null };
@@ -248,8 +307,11 @@ export class AgentManager {
248
307
  */
249
308
  private isCandidateProcess(adapters: readonly AgentAdapter[], process: ProcessInfo): boolean {
250
309
  return adapters.some((adapter) => {
251
- if (!adapter.processNames) return false;
252
- if (filterByProcessNames([process], adapter.processNames).length === 0) return false;
310
+ if (adapter.processNames === undefined && adapter.processNamePrefixes === undefined) {
311
+ return false;
312
+ }
313
+ const { names, prefixes } = adapterPatterns(adapter);
314
+ if (filterByProcessNames([process], names, prefixes).length === 0) return false;
253
315
  try {
254
316
  return adapter.canHandle(process);
255
317
  } catch {
@@ -478,6 +478,90 @@ describe("AgentManager", () => {
478
478
  });
479
479
  });
480
480
 
481
+ describe("listAgents — daemon enrichment", () => {
482
+ const wireAgent = (overrides: Record<string, unknown> = {}) => ({
483
+ name: "daemon-claude",
484
+ type: "claude",
485
+ status: "waiting",
486
+ summary: "daemon summary",
487
+ pid: 777,
488
+ projectPath: "/daemon/proj",
489
+ sessionId: "daemon-sid",
490
+ lastActive: "2026-10-08T12:00:00.000Z",
491
+ ...overrides,
492
+ });
493
+
494
+ it("serves agents from the daemon and skips all local adapters", async () => {
495
+ const local = new MockAdapter("claude", [createMockAgent({ name: "local-claude" })]);
496
+ const detectSpy = vi.spyOn(local, "detectAgents");
497
+ const m = new AgentManager(new AgentRegistry(path.join(tmpDir, "agents.json")), undefined, {
498
+ fetchEnrichedAgents: async () => [wireAgent()],
499
+ });
500
+ m.registerAdapter(local);
501
+
502
+ const agents = await m.listAgents();
503
+ expect(detectSpy).not.toHaveBeenCalled();
504
+ expect(agents).toHaveLength(1);
505
+ expect(agents[0].name).toBe("daemon-claude");
506
+ expect(agents[0].lastActive).toEqual(new Date("2026-10-08T12:00:00.000Z"));
507
+ });
508
+
509
+ it("falls back to all-local when the daemon returns null", async () => {
510
+ const m = new AgentManager(new AgentRegistry(path.join(tmpDir, "agents.json")), undefined, {
511
+ fetchEnrichedAgents: async () => null,
512
+ });
513
+ m.registerAdapter(new MockAdapter("claude", [createMockAgent({ name: "local-claude" })]));
514
+ const agents = await m.listAgents();
515
+ expect(agents.map((a) => a.name)).toEqual(["local-claude"]);
516
+ });
517
+
518
+ it("falls back to all-local when the daemon call throws", async () => {
519
+ const m = new AgentManager(new AgentRegistry(path.join(tmpDir, "agents.json")), undefined, {
520
+ fetchEnrichedAgents: async () => {
521
+ throw new Error("socket gone");
522
+ },
523
+ });
524
+ m.registerAdapter(new MockAdapter("claude", [createMockAgent({ name: "local-claude" })]));
525
+ const agents = await m.listAgents();
526
+ expect(agents.map((a) => a.name)).toEqual(["local-claude"]);
527
+ });
528
+
529
+ it("serves every type from the daemon in one sweep", async () => {
530
+ const claudeLocal = new MockAdapter("claude", [createMockAgent({ name: "local-claude" })]);
531
+ const codexLocal = new MockAdapter("codex", [
532
+ createMockAgent({ name: "local-codex", type: "codex" }),
533
+ ]);
534
+ const claudeSpy = vi.spyOn(claudeLocal, "detectAgents");
535
+ const codexSpy = vi.spyOn(codexLocal, "detectAgents");
536
+ const m = new AgentManager(new AgentRegistry(path.join(tmpDir, "agents.json")), undefined, {
537
+ fetchEnrichedAgents: async () => [
538
+ wireAgent(),
539
+ wireAgent({ type: "codex", name: "daemon-codex", pid: 888 }),
540
+ ],
541
+ });
542
+ m.registerAdapter(claudeLocal);
543
+ m.registerAdapter(codexLocal);
544
+
545
+ const agents = await m.listAgents();
546
+ expect(claudeSpy).not.toHaveBeenCalled();
547
+ expect(codexSpy).not.toHaveBeenCalled();
548
+ expect(agents.map((a) => a.name).sort()).toEqual(["daemon-claude", "daemon-codex"]);
549
+ });
550
+
551
+ it("treats an empty daemon answer as authoritative", async () => {
552
+ const local = new MockAdapter("claude", [createMockAgent({ name: "local-claude" })]);
553
+ const detectSpy = vi.spyOn(local, "detectAgents");
554
+ const m = new AgentManager(new AgentRegistry(path.join(tmpDir, "agents.json")), undefined, {
555
+ fetchEnrichedAgents: async () => [],
556
+ });
557
+ m.registerAdapter(local);
558
+
559
+ const agents = await m.listAgents();
560
+ expect(detectSpy).not.toHaveBeenCalled();
561
+ expect(agents).toEqual([]);
562
+ });
563
+ });
564
+
481
565
  describe("listAgents — registry persistence", () => {
482
566
  let tmpDir: string;
483
567
  let regPath: string;
@@ -0,0 +1,245 @@
1
+ /**
2
+ * Fixture replay: materialize each committed bundle into a fake HOME,
3
+ * run the adapter's detectAgents with the recorded processes + frozen
4
+ * clock, and require byte-identical output to `expected`.
5
+ *
6
+ * The same bundles are consumed by devkit-harness Rust tests — this file is
7
+ * the TS↔TS side of the parity oracle.
8
+ */
9
+
10
+ import { describe, it, expect, afterEach } from "vitest";
11
+ import * as fs from "node:fs";
12
+ import * as os from "node:os";
13
+ import * as path from "node:path";
14
+ import Database from "better-sqlite3";
15
+ import { createBuiltinAdapters } from "../harnesses/index.js";
16
+ import { CodexAdapter } from "../harnesses/codex/CodexAdapter.js";
17
+ import { PiAdapter } from "../harnesses/pi/PiAdapter.js";
18
+ import { GeminiCliAdapter } from "../harnesses/gemini/GeminiCliAdapter.js";
19
+ import { CopilotAdapter } from "../harnesses/copilot/CopilotAdapter.js";
20
+ import { AgentRegistry, type RegistryEntry } from "../utils/AgentRegistry.js";
21
+ import { expand, expandNow, normalizeAgents, withFrozenClock } from "../fixtures/bundle.js";
22
+ import type { FixtureBundle } from "../fixtures/bundle.js";
23
+ import { captureLive, FIXTURES_ROOT } from "../fixtures/capture.js";
24
+
25
+ const bundlePaths = fs.existsSync(FIXTURES_ROOT)
26
+ ? fs.readdirSync(FIXTURES_ROOT, { withFileTypes: true }).flatMap((d) =>
27
+ d.isDirectory()
28
+ ? fs
29
+ .readdirSync(path.join(FIXTURES_ROOT, d.name))
30
+ .filter((f) => f.endsWith(".json"))
31
+ .map((f) => path.join(FIXTURES_ROOT, d.name, f))
32
+ : [],
33
+ )
34
+ : [];
35
+
36
+ /** Adapters whose detect path consults AgentRegistry. */
37
+ const REGISTRY_AWARE = new Set(["codex", "pi", "gemini_cli", "copilot"]);
38
+
39
+ function adapterFor(type: string, registry?: AgentRegistry) {
40
+ // Adapters that consult the registry during detection get the seeded
41
+ // isolated instance so replay never reads real ~/.ai-devkit state.
42
+ if (type === "codex" && registry) return new CodexAdapter(registry);
43
+ if (type === "pi" && registry) return new PiAdapter(registry);
44
+ if (type === "gemini_cli" && registry) return new GeminiCliAdapter(registry);
45
+ if (type === "copilot" && registry) return new CopilotAdapter(registry);
46
+ const adapter = createBuiltinAdapters().find((a) => a.type === type);
47
+ if (!adapter) throw new Error(`no builtin adapter for "${type}"`);
48
+ return adapter;
49
+ }
50
+
51
+ /** Seed an isolated registry at `<home>/.ai-devkit/agents.json`. */
52
+ function seedRegistry(
53
+ bundle: FixtureBundle,
54
+ home: string,
55
+ nowIso: string,
56
+ ): AgentRegistry | undefined {
57
+ if (!REGISTRY_AWARE.has(bundle.adapter)) return undefined;
58
+ const registry = new AgentRegistry(path.join(home, ".ai-devkit", "agents.json"));
59
+ const entries = (bundle.registry ?? []).map(
60
+ (e) =>
61
+ ({
62
+ name: "",
63
+ type: bundle.adapter,
64
+ runtime: "tmux",
65
+ runtimeRef: null,
66
+ cwd: "",
67
+ startedAt: nowIso,
68
+ sessionId: "",
69
+ sessionFilePath: "",
70
+ pinned: false,
71
+ ...expand(expandNow(e as Record<string, unknown>, nowIso), home),
72
+ }) as RegistryEntry,
73
+ );
74
+ registry.registerBatch(entries);
75
+ return registry;
76
+ }
77
+
78
+ /** Materialize a bundle into a temp HOME; returns cleanup + replay inputs. */
79
+ function materialize(bundle: FixtureBundle) {
80
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "fixture-home-"));
81
+ // "$TODAY" resolves to the local `YYYY/MM/DD` day key at write time — Codex
82
+ // date-dir discovery derives day keys from process start times in local
83
+ // time, so static dirs would drift across replay days/timezones.
84
+ const now = new Date();
85
+ const todayKey = [
86
+ String(now.getFullYear()).padStart(4, "0"),
87
+ String(now.getMonth() + 1).padStart(2, "0"),
88
+ String(now.getDate()).padStart(2, "0"),
89
+ ].join("/");
90
+ for (const [rel, content] of Object.entries(bundle.home)) {
91
+ const p = path.join(home, expand(rel.split("$TODAY").join(todayKey), home));
92
+ fs.mkdirSync(path.dirname(p), { recursive: true });
93
+ fs.writeFileSync(p, expand(content.split("$TODAY").join(todayKey), home));
94
+ }
95
+ // SQLite stores (OpenCode's opencode.db) materialize from ordered SQL
96
+ // statements — binary dbs can't travel in the JSON `home` map.
97
+ for (const [rel, stmts] of Object.entries(bundle.sqlite ?? {})) {
98
+ const p = path.join(home, expand(rel.split("$TODAY").join(todayKey), home));
99
+ fs.mkdirSync(path.dirname(p), { recursive: true });
100
+ const db = new Database(p);
101
+ try {
102
+ for (const stmt of stmts) {
103
+ db.exec(expand(stmt.split("$TODAY").join(todayKey), home));
104
+ }
105
+ } finally {
106
+ db.close();
107
+ }
108
+ }
109
+ // "$NOW" resolves to the instant home files were written — legacy
110
+ // cwd+birthtime matching compares process start times against real file
111
+ // creation times, so a static timestamp would drift out of tolerance.
112
+ const nowIso = new Date().toISOString();
113
+ // Deterministic mtimes for adapters that read them (Grok lastActive /
114
+ // latest-session pick) — "$NOW" resolves like the process sentinel.
115
+ for (const [rel, mt] of Object.entries(bundle.mtimes ?? {})) {
116
+ const p = path.join(home, expand(rel.split("$TODAY").join(todayKey), home));
117
+ const ms = mt === "$NOW" ? Date.parse(nowIso) : mt;
118
+ fs.utimesSync(p, ms / 1000, ms / 1000);
119
+ }
120
+ // JSON round-tripped Date fields (e.g. ProcessInfo.startTime) come back as
121
+ // ISO strings — adapters expect real Date instances.
122
+ const processes = expandNow(expand(bundle.processes, home), nowIso).map((p) => ({
123
+ ...p,
124
+ startTime: p.startTime ? new Date(p.startTime) : undefined,
125
+ }));
126
+ const frozenNow = bundle.frozenNow === "$NOW" ? Date.parse(nowIso) : bundle.frozenNow;
127
+ // Pids whose startTime resolves to the materialization instant — Codex
128
+ // derives session day-dirs from start times, so only these paths contain
129
+ // the replay-day key and normalize to $TODAY.
130
+ const nowPids = new Set(bundle.processes.filter((p) => p.startTime === "$NOW").map((p) => p.pid));
131
+ return {
132
+ home,
133
+ processes,
134
+ frozenNow,
135
+ todayKey,
136
+ // Only $NOW resolves — $FIXTURE_HOME and $TODAY stay literal to match
137
+ // the normalized actual form.
138
+ expected: expandNow(bundle.expected, nowIso),
139
+ cleanup: () => fs.rmSync(home, { recursive: true, force: true }),
140
+ nowIso,
141
+ nowPids,
142
+ };
143
+ }
144
+
145
+ describe("fixture replay (TS parity oracle)", () => {
146
+ const saved = process.env.HOME;
147
+ afterEach(() => {
148
+ if (saved === undefined) delete process.env.HOME;
149
+ else process.env.HOME = saved;
150
+ });
151
+
152
+ if (bundlePaths.length === 0) {
153
+ it.todo("no fixture bundles committed yet — run AI_DEVKIT_FIXTURE_CAPTURE=1");
154
+ return;
155
+ }
156
+
157
+ for (const bundlePath of bundlePaths) {
158
+ it(`replays ${path.relative(FIXTURES_ROOT, bundlePath)}`, async () => {
159
+ const bundle: FixtureBundle = JSON.parse(fs.readFileSync(bundlePath, "utf8"));
160
+ const { home, processes, frozenNow, expected, cleanup, todayKey, nowIso, nowPids } =
161
+ materialize(bundle);
162
+ // Pin XDG to the fixture's canonical share dir — an ambient
163
+ // XDG_DATA_HOME would resolve the real opencode.db into replay.
164
+ const savedXdg = process.env.XDG_DATA_HOME;
165
+ // Same for ANTIGRAVITY_CLI_HOME — clearing it falls the adapter
166
+ // back to the pinned HOME's canonical base dir.
167
+ const savedAgy = process.env.ANTIGRAVITY_CLI_HOME;
168
+ try {
169
+ process.env.HOME = home;
170
+ process.env.XDG_DATA_HOME = path.join(home, ".local", "share");
171
+ delete process.env.ANTIGRAVITY_CLI_HOME;
172
+ const registry = seedRegistry(bundle, home, nowIso);
173
+ const agents = await withFrozenClock(frozenNow, () =>
174
+ adapterFor(bundle.adapter, registry).detectAgents({ processes }),
175
+ );
176
+ // Day-key dirs normalize back to $TODAY only for agents whose
177
+ // process startTime was $NOW — static-start agents keep concrete
178
+ // dates so live bundles stay replayable on any day.
179
+ const actual = JSON.parse(JSON.stringify(normalizeAgents(agents, home))).map((a) =>
180
+ nowPids.has(a.pid) ? JSON.parse(JSON.stringify(a).split(todayKey).join("$TODAY")) : a,
181
+ );
182
+ expect(actual).toEqual(expected);
183
+ } finally {
184
+ if (savedXdg === undefined) delete process.env.XDG_DATA_HOME;
185
+ else process.env.XDG_DATA_HOME = savedXdg;
186
+ if (savedAgy === undefined) delete process.env.ANTIGRAVITY_CLI_HOME;
187
+ else process.env.ANTIGRAVITY_CLI_HOME = savedAgy;
188
+ cleanup();
189
+ }
190
+ });
191
+ }
192
+ });
193
+
194
+ // Opt-in live capture: AI_DEVKIT_FIXTURE_CAPTURE=1 npx vitest run fixtures
195
+ describe.runIf(process.env.AI_DEVKIT_FIXTURE_CAPTURE === "1")("fixture capture (live)", () => {
196
+ it("captures claude bundle from the live machine", async () => {
197
+ const out = await captureLive(adapterFor("claude"), "live");
198
+ expect(fs.existsSync(out)).toBe(true);
199
+ }, 30000);
200
+
201
+ it("captures codex bundle from the live machine", async () => {
202
+ const out = await captureLive(adapterFor("codex"), "live");
203
+ expect(fs.existsSync(out)).toBe(true);
204
+ }, 30000);
205
+
206
+ it("captures pi bundle from the live machine", async () => {
207
+ const out = await captureLive(adapterFor("pi"), "live");
208
+ expect(fs.existsSync(out)).toBe(true);
209
+ }, 30000);
210
+
211
+ it("captures gemini_cli bundle from the live machine", async () => {
212
+ const out = await captureLive(adapterFor("gemini_cli"), "live");
213
+ expect(fs.existsSync(out)).toBe(true);
214
+ }, 30000);
215
+
216
+ it("captures copilot bundle from the live machine", async () => {
217
+ const out = await captureLive(adapterFor("copilot"), "live");
218
+ expect(fs.existsSync(out)).toBe(true);
219
+ }, 30000);
220
+
221
+ it("captures grok_cli bundle from the live machine", async () => {
222
+ const out = await captureLive(adapterFor("grok_cli"), "live");
223
+ expect(fs.existsSync(out)).toBe(true);
224
+ }, 30000);
225
+
226
+ it("captures opencode bundle from the live machine", async () => {
227
+ const out = await captureLive(adapterFor("opencode"), "live");
228
+ expect(fs.existsSync(out)).toBe(true);
229
+ }, 30000);
230
+
231
+ it("captures devin bundle from the live machine", async () => {
232
+ const out = await captureLive(adapterFor("devin"), "live");
233
+ expect(fs.existsSync(out)).toBe(true);
234
+ }, 30000);
235
+
236
+ it("captures kiro bundle from the live machine", async () => {
237
+ const out = await captureLive(adapterFor("kiro"), "live");
238
+ expect(fs.existsSync(out)).toBe(true);
239
+ }, 30000);
240
+
241
+ it("captures antigravity_cli bundle from the live machine", async () => {
242
+ const out = await captureLive(adapterFor("antigravity_cli"), "live");
243
+ expect(fs.existsSync(out)).toBe(true);
244
+ }, 30000);
245
+ });
@@ -239,9 +239,7 @@ describe("DevinAdapter", () => {
239
239
  { id: "newer", directory: "/repo", timeCreated: now - 200, lastActivityAt: now - 60 },
240
240
  { id: "hidden-sess", directory: "/repo", timeCreated: now - 10, hidden: 1 },
241
241
  ],
242
- nodes: [
243
- { sessionId: "newer", nodeId: 1, role: "user", content: "hi", createdAt: now - 60 },
244
- ],
242
+ nodes: [{ sessionId: "newer", nodeId: 1, role: "user", content: "hi", createdAt: now - 60 }],
245
243
  });
246
244
 
247
245
  const agents = await adapter.detectAgents({
@@ -59,9 +59,7 @@ describe("DevinSessionParser", () => {
59
59
  });
60
60
  const db = openDb();
61
61
  try {
62
- expect(parser.getConversation(db, "s")).toEqual([
63
- { role: "assistant", content: "final" },
64
- ]);
62
+ expect(parser.getConversation(db, "s")).toEqual([{ role: "assistant", content: "final" }]);
65
63
  } finally {
66
64
  db.close();
67
65
  }
@@ -99,9 +97,7 @@ describe("DevinSessionParser", () => {
99
97
  });
100
98
  const db = openDb();
101
99
  try {
102
- expect(parser.getConversation(db, "s")).toEqual([
103
- { role: "assistant", content: "working" },
104
- ]);
100
+ expect(parser.getConversation(db, "s")).toEqual([{ role: "assistant", content: "working" }]);
105
101
  expect(parser.getConversation(db, "s", { verbose: true })).toEqual([
106
102
  { role: "assistant", content: "[thinking] hmm" },
107
103
  { role: "assistant", content: "working" },
@@ -145,9 +141,7 @@ describe("DevinSessionParser", () => {
145
141
  });
146
142
  const db = openDb();
147
143
  try {
148
- expect(parser.getConversation(db, "s")).toEqual([
149
- { role: "assistant", content: "ok" },
150
- ]);
144
+ expect(parser.getConversation(db, "s")).toEqual([{ role: "assistant", content: "ok" }]);
151
145
  expect(parser.getConversation(db, "missing")).toEqual([]);
152
146
  } finally {
153
147
  db.close();