@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,247 @@
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
27
+ .readdirSync(FIXTURES_ROOT, { withFileTypes: true })
28
+ .flatMap((d) =>
29
+ d.isDirectory()
30
+ ? fs
31
+ .readdirSync(path.join(FIXTURES_ROOT, d.name))
32
+ .filter((f) => f.endsWith(".json"))
33
+ .map((f) => path.join(FIXTURES_ROOT, d.name, f))
34
+ : [],
35
+ )
36
+ : [];
37
+
38
+ /** Adapters whose detect path consults AgentRegistry. */
39
+ const REGISTRY_AWARE = new Set(["codex", "pi", "gemini_cli", "copilot"]);
40
+
41
+ function adapterFor(type: string, registry?: AgentRegistry) {
42
+ // Adapters that consult the registry during detection get the seeded
43
+ // isolated instance so replay never reads real ~/.ai-devkit state.
44
+ if (type === "codex" && registry) return new CodexAdapter(registry);
45
+ if (type === "pi" && registry) return new PiAdapter(registry);
46
+ if (type === "gemini_cli" && registry) return new GeminiCliAdapter(registry);
47
+ if (type === "copilot" && registry) return new CopilotAdapter(registry);
48
+ const adapter = createBuiltinAdapters().find((a) => a.type === type);
49
+ if (!adapter) throw new Error(`no builtin adapter for "${type}"`);
50
+ return adapter;
51
+ }
52
+
53
+ /** Seed an isolated registry at `<home>/.ai-devkit/agents.json`. */
54
+ function seedRegistry(bundle: FixtureBundle, home: string, nowIso: string): AgentRegistry | undefined {
55
+ if (!REGISTRY_AWARE.has(bundle.adapter)) return undefined;
56
+ const registry = new AgentRegistry(path.join(home, ".ai-devkit", "agents.json"));
57
+ const entries = (bundle.registry ?? []).map(
58
+ (e) =>
59
+ ({
60
+ name: "",
61
+ type: bundle.adapter,
62
+ runtime: "tmux",
63
+ runtimeRef: null,
64
+ cwd: "",
65
+ startedAt: nowIso,
66
+ sessionId: "",
67
+ sessionFilePath: "",
68
+ pinned: false,
69
+ ...expand(expandNow(e as Record<string, unknown>, nowIso), home),
70
+ }) as RegistryEntry,
71
+ );
72
+ registry.registerBatch(entries);
73
+ return registry;
74
+ }
75
+
76
+ /** Materialize a bundle into a temp HOME; returns cleanup + replay inputs. */
77
+ function materialize(bundle: FixtureBundle) {
78
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "fixture-home-"));
79
+ // "$TODAY" resolves to the local `YYYY/MM/DD` day key at write time — Codex
80
+ // date-dir discovery derives day keys from process start times in local
81
+ // time, so static dirs would drift across replay days/timezones.
82
+ const now = new Date();
83
+ const todayKey = [
84
+ String(now.getFullYear()).padStart(4, "0"),
85
+ String(now.getMonth() + 1).padStart(2, "0"),
86
+ String(now.getDate()).padStart(2, "0"),
87
+ ].join("/");
88
+ for (const [rel, content] of Object.entries(bundle.home)) {
89
+ const p = path.join(home, expand(rel.split("$TODAY").join(todayKey), home));
90
+ fs.mkdirSync(path.dirname(p), { recursive: true });
91
+ fs.writeFileSync(p, expand(content.split("$TODAY").join(todayKey), home));
92
+ }
93
+ // SQLite stores (OpenCode's opencode.db) materialize from ordered SQL
94
+ // statements — binary dbs can't travel in the JSON `home` map.
95
+ for (const [rel, stmts] of Object.entries(bundle.sqlite ?? {})) {
96
+ const p = path.join(home, expand(rel.split("$TODAY").join(todayKey), home));
97
+ fs.mkdirSync(path.dirname(p), { recursive: true });
98
+ const db = new Database(p);
99
+ try {
100
+ for (const stmt of stmts) {
101
+ db.exec(expand(stmt.split("$TODAY").join(todayKey), home));
102
+ }
103
+ } finally {
104
+ db.close();
105
+ }
106
+ }
107
+ // "$NOW" resolves to the instant home files were written — legacy
108
+ // cwd+birthtime matching compares process start times against real file
109
+ // creation times, so a static timestamp would drift out of tolerance.
110
+ const nowIso = new Date().toISOString();
111
+ // Deterministic mtimes for adapters that read them (Grok lastActive /
112
+ // latest-session pick) — "$NOW" resolves like the process sentinel.
113
+ for (const [rel, mt] of Object.entries(bundle.mtimes ?? {})) {
114
+ const p = path.join(home, expand(rel.split("$TODAY").join(todayKey), home));
115
+ const ms = mt === "$NOW" ? Date.parse(nowIso) : mt;
116
+ fs.utimesSync(p, ms / 1000, ms / 1000);
117
+ }
118
+ // JSON round-tripped Date fields (e.g. ProcessInfo.startTime) come back as
119
+ // ISO strings — adapters expect real Date instances.
120
+ const processes = expandNow(expand(bundle.processes, home), nowIso).map((p) => ({
121
+ ...p,
122
+ startTime: p.startTime ? new Date(p.startTime) : undefined,
123
+ }));
124
+ const frozenNow = bundle.frozenNow === "$NOW" ? Date.parse(nowIso) : bundle.frozenNow;
125
+ // Pids whose startTime resolves to the materialization instant — Codex
126
+ // derives session day-dirs from start times, so only these paths contain
127
+ // the replay-day key and normalize to $TODAY.
128
+ const nowPids = new Set(
129
+ bundle.processes.filter((p) => p.startTime === "$NOW").map((p) => p.pid),
130
+ );
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)
181
+ ? JSON.parse(JSON.stringify(a).split(todayKey).join("$TODAY"))
182
+ : a,
183
+ );
184
+ expect(actual).toEqual(expected);
185
+ } finally {
186
+ if (savedXdg === undefined) delete process.env.XDG_DATA_HOME;
187
+ else process.env.XDG_DATA_HOME = savedXdg;
188
+ if (savedAgy === undefined) delete process.env.ANTIGRAVITY_CLI_HOME;
189
+ else process.env.ANTIGRAVITY_CLI_HOME = savedAgy;
190
+ cleanup();
191
+ }
192
+ });
193
+ }
194
+ });
195
+
196
+ // Opt-in live capture: AI_DEVKIT_FIXTURE_CAPTURE=1 npx vitest run fixtures
197
+ describe.runIf(process.env.AI_DEVKIT_FIXTURE_CAPTURE === "1")("fixture capture (live)", () => {
198
+ it("captures claude bundle from the live machine", async () => {
199
+ const out = await captureLive(adapterFor("claude"), "live");
200
+ expect(fs.existsSync(out)).toBe(true);
201
+ }, 30000);
202
+
203
+ it("captures codex bundle from the live machine", async () => {
204
+ const out = await captureLive(adapterFor("codex"), "live");
205
+ expect(fs.existsSync(out)).toBe(true);
206
+ }, 30000);
207
+
208
+ it("captures pi bundle from the live machine", async () => {
209
+ const out = await captureLive(adapterFor("pi"), "live");
210
+ expect(fs.existsSync(out)).toBe(true);
211
+ }, 30000);
212
+
213
+ it("captures gemini_cli bundle from the live machine", async () => {
214
+ const out = await captureLive(adapterFor("gemini_cli"), "live");
215
+ expect(fs.existsSync(out)).toBe(true);
216
+ }, 30000);
217
+
218
+ it("captures copilot bundle from the live machine", async () => {
219
+ const out = await captureLive(adapterFor("copilot"), "live");
220
+ expect(fs.existsSync(out)).toBe(true);
221
+ }, 30000);
222
+
223
+ it("captures grok_cli bundle from the live machine", async () => {
224
+ const out = await captureLive(adapterFor("grok_cli"), "live");
225
+ expect(fs.existsSync(out)).toBe(true);
226
+ }, 30000);
227
+
228
+ it("captures opencode bundle from the live machine", async () => {
229
+ const out = await captureLive(adapterFor("opencode"), "live");
230
+ expect(fs.existsSync(out)).toBe(true);
231
+ }, 30000);
232
+
233
+ it("captures devin bundle from the live machine", async () => {
234
+ const out = await captureLive(adapterFor("devin"), "live");
235
+ expect(fs.existsSync(out)).toBe(true);
236
+ }, 30000);
237
+
238
+ it("captures kiro bundle from the live machine", async () => {
239
+ const out = await captureLive(adapterFor("kiro"), "live");
240
+ expect(fs.existsSync(out)).toBe(true);
241
+ }, 30000);
242
+
243
+ it("captures antigravity_cli bundle from the live machine", async () => {
244
+ const out = await captureLive(adapterFor("antigravity_cli"), "live");
245
+ expect(fs.existsSync(out)).toBe(true);
246
+ }, 30000);
247
+ });
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Readiness fixture replay: each committed bundle under
3
+ * `fixtures/readiness/` provides the injectable seams (files,
4
+ * executables, command outputs, codexAuth) plus `expected` — the
5
+ * byte-identical reports the readiness probes must produce replaying
6
+ * the same bundle through their injectable seams.
7
+ */
8
+
9
+ import { describe, it, expect } from "vitest";
10
+ import * as fs from "node:fs";
11
+ import * as path from "node:path";
12
+ import {
13
+ getAgentReadinessReports,
14
+ type AgentReadinessOptions,
15
+ } from "../harnesses/readiness/AgentReadiness.js";
16
+
17
+ interface ReadinessBundle {
18
+ options: {
19
+ homeDir: string;
20
+ path: string;
21
+ assetRoot?: string;
22
+ builtInSkillNames?: string[];
23
+ skillRoots?: Record<string, string>;
24
+ };
25
+ /** Absolute path → contents, or "<dir>" for a directory entry. */
26
+ files: Record<string, string>;
27
+ /** Paths that answer X_OK access. */
28
+ executables: string[];
29
+ /** `"command arg1 arg2"` → output; `ok: false` rejects like execFile. */
30
+ commands: Record<string, { stdout: string; stderr?: string; ok?: boolean }>;
31
+ codexAuth?: boolean | null;
32
+ expected: Record<string, unknown>;
33
+ }
34
+
35
+ const READINESS_ROOT = path.resolve(__dirname, "../../../..", "fixtures", "readiness");
36
+
37
+ const bundlePaths = fs.existsSync(READINESS_ROOT)
38
+ ? fs
39
+ .readdirSync(READINESS_ROOT)
40
+ .filter((f) => f.endsWith(".json") && !f.startsWith("live"))
41
+ .sort()
42
+ .map((f) => path.join(READINESS_ROOT, f))
43
+ : [];
44
+
45
+ function replay(bundle: ReadinessBundle): Promise<Record<string, unknown>> {
46
+ const executableSet = new Set(bundle.executables);
47
+ const options: AgentReadinessOptions = {
48
+ homeDir: bundle.options.homeDir,
49
+ path: bundle.options.path,
50
+ assetRoot: bundle.options.assetRoot,
51
+ builtInSkillNames: bundle.options.builtInSkillNames ?? [],
52
+ skillRoots: bundle.options.skillRoots ?? {},
53
+ readFile: async (target) => {
54
+ if (!(target in bundle.files)) throw new Error("missing");
55
+ return bundle.files[target];
56
+ },
57
+ access: async (target) => {
58
+ if (executableSet.has(target) || target in bundle.files) return;
59
+ throw new Error("missing");
60
+ },
61
+ runCommand: async (command, args) => {
62
+ const key = [command, ...args].join(" ");
63
+ const stub = bundle.commands[key];
64
+ if (!stub) throw new Error(`unexpected command ${key}`);
65
+ if (stub.ok === false) throw new Error(`command failed: ${key}`);
66
+ return { stdout: stub.stdout, stderr: stub.stderr ?? "" };
67
+ },
68
+ codexAuth: async () => bundle.codexAuth ?? null,
69
+ };
70
+ return getAgentReadinessReports(options);
71
+ }
72
+
73
+ describe("readiness fixture replay", () => {
74
+ it.each(bundlePaths)("%s", async (bundlePath) => {
75
+ const bundle = JSON.parse(fs.readFileSync(bundlePath, "utf8")) as ReadinessBundle;
76
+ const reports = await replay(bundle);
77
+ expect(reports).toEqual(bundle.expected);
78
+ });
79
+ });
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Golden-fixture bundles: the parity oracle for the devkit-harness Rust port.
3
+ * A bundle records everything `detectAgents` consumed and produced so both
4
+ * the TS adapter and its Rust port can be run against identical inputs.
5
+ *
6
+ * Format (committed under fixtures/harness/<type>/<case>.json):
7
+ * {
8
+ * adapter, capturedAt, frozenNow,
9
+ * processes: ProcessInfo[],
10
+ * home: { "<relpath under $FIXTURE_HOME>": "<content with $FIXTURE_HOME refs>" },
11
+ * expected: AgentInfo[] (dates as ISO strings)
12
+ * }
13
+ */
14
+
15
+ import type { AgentInfo, ProcessInfo } from "../adapters/AgentAdapter.js";
16
+
17
+ export const HOME_PLACEHOLDER = "$FIXTURE_HOME";
18
+ /** Resolves to the instant home files were written (birthtime matching). */
19
+ export const NOW_PLACEHOLDER = "$NOW";
20
+ /** Resolves to the local `YYYY/MM/DD` day dir at replay (Codex sessions). */
21
+ export const TODAY_PLACEHOLDER = "$TODAY";
22
+
23
+ export interface FixtureBundle {
24
+ adapter: string;
25
+ capturedAt: string;
26
+ /** Epoch ms the clock was frozen at; `"$NOW"` = materialization instant. */
27
+ frozenNow: number | string;
28
+ processes: ProcessInfo[];
29
+ /** Files under the fixture HOME; content may embed HOME_PLACEHOLDER. */
30
+ home: Record<string, string>;
31
+ /**
32
+ * mtime overrides keyed by `home` relpath — epoch ms, or "$NOW" for the
33
+ * materialization instant. Adapters whose output derives from file mtimes
34
+ * (Grok's lastActive / latest-session pick) need deterministic mtimes.
35
+ */
36
+ mtimes?: Record<string, number | string>;
37
+ /**
38
+ * AgentRegistry rows (pid→sessionFilePath etc.) visible at capture time,
39
+ * restricted to captured process pids — adapters' registry caches read
40
+ * this state, so replay seeds an isolated registry with it.
41
+ */
42
+ registry?: Record<string, unknown>[];
43
+ /**
44
+ * SQLite stores adapters consult (OpenCode's opencode.db), keyed by
45
+ * relpath under $FIXTURE_HOME: SQL statements (DDL + INSERTs) executed
46
+ * in order to materialize each db. Statements may embed HOME_PLACEHOLDER.
47
+ */
48
+ sqlite?: Record<string, string[]>;
49
+ expected: Record<string, unknown>[];
50
+ }
51
+
52
+ /**
53
+ * Rewrite harness dot-dir paths (`<home>/.claude`, `<home>/.codex`, …) to the
54
+ * placeholder — nothing else. Project cwds share the home prefix
55
+ * (`<home>/Code/proj`) and MUST stay literal: harnesses encode them into
56
+ * session-dir names (`-Users-foo-proj`), so rewriting them breaks
57
+ * cwd↔session matching on replay.
58
+ */
59
+ export function sanitize<T>(value: T, realHome: string): T {
60
+ const homeDot = `${realHome}/.`;
61
+ if (typeof value === "string") {
62
+ return value.split(homeDot).join(`${HOME_PLACEHOLDER}/.`) as T;
63
+ }
64
+ if (Array.isArray(value)) return value.map((v) => sanitize(v, realHome)) as T;
65
+ if (value && typeof value === "object") {
66
+ if (value instanceof Date) return value.toISOString() as T;
67
+ const out: Record<string, unknown> = {};
68
+ for (const [k, v] of Object.entries(value)) out[k] = sanitize(v, realHome);
69
+ return out as T;
70
+ }
71
+ return value;
72
+ }
73
+
74
+ /** Inverse of sanitize: expand the placeholder to a concrete dir. */
75
+ export function expand<T>(value: T, fixtureHome: string): T {
76
+ if (typeof value === "string") {
77
+ return value.split(HOME_PLACEHOLDER).join(fixtureHome) as T;
78
+ }
79
+ if (Array.isArray(value)) return value.map((v) => expand(v, fixtureHome)) as T;
80
+ if (value && typeof value === "object" && !(value instanceof Date)) {
81
+ const out: Record<string, unknown> = {};
82
+ for (const [k, v] of Object.entries(value)) out[k] = expand(v, fixtureHome);
83
+ return out as T;
84
+ }
85
+ return value;
86
+ }
87
+
88
+ /** Replace NOW_PLACEHOLDER strings with a resolved ISO instant. */
89
+ export function expandNow<T>(value: T, isoInstant: string): T {
90
+ if (typeof value === "string") {
91
+ return value.split(NOW_PLACEHOLDER).join(isoInstant) as T;
92
+ }
93
+ if (Array.isArray(value)) return value.map((v) => expandNow(v, isoInstant)) as T;
94
+ if (value && typeof value === "object" && !(value instanceof Date)) {
95
+ const out: Record<string, unknown> = {};
96
+ for (const [k, v] of Object.entries(value)) out[k] = expandNow(v, isoInstant);
97
+ return out as T;
98
+ }
99
+ return value;
100
+ }
101
+
102
+ /** Agents normalized the way the wire carries them (Date → ISO string). */
103
+ export function normalizeAgents(agents: AgentInfo[], realHome: string) {
104
+ return sanitize(JSON.parse(JSON.stringify(agents)), realHome);
105
+ }
106
+
107
+ /**
108
+ * Freeze `Date` at `epochMs` for the duration of `fn`. Adapters stamp
109
+ * `new Date()` in several places; parity requires a fixed clock.
110
+ */
111
+ export async function withFrozenClock<T>(epochMs: number, fn: () => Promise<T>): Promise<T> {
112
+ const RealDate = Date;
113
+ class FrozenDate extends RealDate {
114
+ constructor(...args: unknown[]) {
115
+ if (args.length === 0) super(epochMs);
116
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
117
+ else super(...(args as [any]));
118
+ }
119
+ static override now() {
120
+ return epochMs;
121
+ }
122
+ }
123
+ const g = globalThis as { Date: DateConstructor };
124
+ g.Date = FrozenDate as DateConstructor;
125
+ try {
126
+ return await fn();
127
+ } finally {
128
+ g.Date = RealDate;
129
+ }
130
+ }