@app-vitals/agent-runtime 1.91.0 → 1.92.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,563 @@
1
+ /**
2
+ * runtime/boot.integration.test.ts
3
+ *
4
+ * Integration tests for the startup sequence in boot.ts (startAgent).
5
+ * startAgent has no dependency-injection seam: it reads process.env, patches
6
+ * console, binds a health server, registers signal handlers and starts
7
+ * intervals. So each test boots it in a real child `bun` process (isolated
8
+ * HOME/AGENT_HOME in a temp dir) against a local fake admin API, then asserts
9
+ * on the requests the fake saw, the boot log order and the exit behaviour.
10
+ * Isolation contract: no mock.module(), no global overrides in this process.
11
+ */
12
+
13
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
14
+ import {
15
+ existsSync,
16
+ mkdirSync,
17
+ readFileSync,
18
+ rmSync,
19
+ writeFileSync,
20
+ } from "node:fs";
21
+ import { join } from "node:path";
22
+
23
+ // ─── Fixtures ──────────────────────────────────────────────────────────────────
24
+
25
+ const AGENT_ID = "boot-test-agent";
26
+ const API_KEY = "boot-test-key";
27
+ const BOOT_TIMEOUT_MS = 30_000;
28
+
29
+ const BUNDLE = {
30
+ specialty: "coding",
31
+ env: { BOOT_TEST_SYNCED_VAR: "synced" },
32
+ allowedTools: ["Read", "Bash"],
33
+ plugins: [],
34
+ repos: [],
35
+ reviewAuthorAllowlist: [],
36
+ patchAuthorAllowlist: [],
37
+ restrictSlackToMembers: false,
38
+ memberEmails: [],
39
+ autoPostReviews: true,
40
+ allowSelfReview: false,
41
+ minConfidence: 75,
42
+ maxFindings: 5,
43
+ cleanupMergedWorktrees: true,
44
+ cleanupAfterDays: 14,
45
+ };
46
+
47
+ type Route = (req: Request) => Response | Promise<Response>;
48
+
49
+ interface FakeAdmin {
50
+ url: string;
51
+ /** "METHOD /path" in arrival order. */
52
+ requests: string[];
53
+ authHeaders: string[];
54
+ stop(): void;
55
+ }
56
+
57
+ function startFakeAdmin(overrides: Record<string, Route> = {}): FakeAdmin {
58
+ const requests: string[] = [];
59
+ const authHeaders: string[] = [];
60
+ const json = (body: unknown, status = 200) =>
61
+ new Response(JSON.stringify(body), {
62
+ status,
63
+ headers: { "Content-Type": "application/json" },
64
+ });
65
+ const routes: Record<string, Route> = {
66
+ [`GET /agents/${AGENT_ID}/config`]: () => json(BUNDLE),
67
+ [`GET /agents/${AGENT_ID}/crons`]: () => json([]),
68
+ [`POST /agents/${AGENT_ID}/template/reconcile`]: () => json({}),
69
+ [`POST /agents/${AGENT_ID}/crons/reconcile`]: () => json({}),
70
+ ...overrides,
71
+ };
72
+ const server = Bun.serve({
73
+ port: 0,
74
+ fetch(req) {
75
+ const key = `${req.method} ${new URL(req.url).pathname}`;
76
+ requests.push(key);
77
+ authHeaders.push(req.headers.get("authorization") ?? "");
78
+ const route = routes[key];
79
+ return route ? route(req) : json({ error: "not found" }, 404);
80
+ },
81
+ });
82
+ return {
83
+ url: `http://127.0.0.1:${server.port}`,
84
+ requests,
85
+ authHeaders,
86
+ stop: () => void server.stop(true),
87
+ };
88
+ }
89
+
90
+ function freePort(): number {
91
+ const s = Bun.serve({ port: 0, fetch: () => new Response("") });
92
+ const port = s.port as number;
93
+ s.stop(true);
94
+ return port;
95
+ }
96
+
97
+ // ─── Child process harness ─────────────────────────────────────────────────────
98
+
99
+ let tmpRoot: string;
100
+
101
+ beforeEach(() => {
102
+ tmpRoot = `/tmp/test-boot-${Date.now()}-${Math.random().toString(36).slice(2)}`;
103
+ mkdirSync(join(tmpRoot, "home"), { recursive: true });
104
+ });
105
+
106
+ afterEach(() => {
107
+ if (existsSync(tmpRoot)) rmSync(tmpRoot, { recursive: true, force: true });
108
+ });
109
+
110
+ interface Booted {
111
+ proc: ReturnType<typeof Bun.spawn>;
112
+ healthPort: number;
113
+ /** Combined stdout+stderr captured so far. */
114
+ output(): string;
115
+ /** Resolves once `needle` appears in the output; rejects on early exit/timeout. */
116
+ waitFor(needle: string): Promise<void>;
117
+ exited: Promise<number>;
118
+ }
119
+
120
+ function bootAgent(env: Record<string, string>): Booted {
121
+ // The driver is the equivalent of the repo's index.ts, plus one extension
122
+ // that records onConfigSync calls so we can see the extension seam fire.
123
+ const driver = join(tmpRoot, "driver.ts");
124
+ const bootPath = join(import.meta.dir, "boot.ts");
125
+ writeFileSync(
126
+ driver,
127
+ `import { appendFileSync } from "node:fs";
128
+ import { startAgent } from ${JSON.stringify(bootPath)};
129
+ await startAgent([
130
+ () => ({
131
+ onConfigSync: (bundle: { specialty: string }) =>
132
+ appendFileSync(${JSON.stringify(join(tmpRoot, "ext.log"))}, "onConfigSync:" + bundle.specialty + "\\n"),
133
+ }),
134
+ ]);
135
+ `,
136
+ );
137
+
138
+ const healthPort = freePort();
139
+ const cleanEnv: Record<string, string> = {};
140
+ for (const k of ["PATH", "TMPDIR", "LANG"]) {
141
+ const v = process.env[k];
142
+ if (v) cleanEnv[k] = v;
143
+ }
144
+ const proc = Bun.spawn(["bun", driver], {
145
+ cwd: join(import.meta.dir, ".."),
146
+ env: {
147
+ ...cleanEnv,
148
+ HOME: join(tmpRoot, "home"),
149
+ AGENT_HOME: join(tmpRoot, "agent-home"),
150
+ SHIPWRIGHT_HEALTH_PORT: String(healthPort),
151
+ SHIPWRIGHT_PR_STATE_RECONCILER_INTERVAL_MS: "3600000",
152
+ ...env,
153
+ },
154
+ stdout: "pipe",
155
+ stderr: "pipe",
156
+ });
157
+
158
+ let buf = "";
159
+ const waiters: Array<{ needle: string; resolve: () => void }> = [];
160
+ const pump = async (stream: ReadableStream<Uint8Array>) => {
161
+ const decoder = new TextDecoder();
162
+ for await (const chunk of stream) {
163
+ buf += decoder.decode(chunk);
164
+ for (const w of [...waiters]) {
165
+ if (buf.includes(w.needle)) {
166
+ waiters.splice(waiters.indexOf(w), 1);
167
+ w.resolve();
168
+ }
169
+ }
170
+ }
171
+ };
172
+ void pump(proc.stdout as ReadableStream<Uint8Array>);
173
+ void pump(proc.stderr as ReadableStream<Uint8Array>);
174
+
175
+ const exited = proc.exited as Promise<number>;
176
+ return {
177
+ proc,
178
+ healthPort,
179
+ output: () => buf,
180
+ exited,
181
+ waitFor: (needle) =>
182
+ new Promise<void>((resolve, reject) => {
183
+ if (buf.includes(needle)) return resolve();
184
+ const timer = setTimeout(
185
+ () => reject(new Error(`timed out waiting for "${needle}"\n${buf}`)),
186
+ BOOT_TIMEOUT_MS - 2_000,
187
+ );
188
+ waiters.push({
189
+ needle,
190
+ resolve: () => {
191
+ clearTimeout(timer);
192
+ resolve();
193
+ },
194
+ });
195
+ void exited.then((code) =>
196
+ reject(new Error(`exited ${code} before "${needle}"\n${buf}`)),
197
+ );
198
+ }),
199
+ };
200
+ }
201
+
202
+ /** Index of `needle` in the boot output; fails the test if absent. */
203
+ function at(output: string, needle: string): number {
204
+ const i = output.indexOf(needle);
205
+ expect(i, `missing "${needle}" in:\n${output}`).toBeGreaterThanOrEqual(0);
206
+ return i;
207
+ }
208
+
209
+ async function shutdownAndWait(
210
+ b: Booted,
211
+ signal: "SIGTERM" | "SIGINT" = "SIGTERM",
212
+ ) {
213
+ b.proc.kill(signal);
214
+ return await b.exited;
215
+ }
216
+
217
+ async function waitForRequest(admin: FakeAdmin, request: string) {
218
+ const deadline = Date.now() + 10_000;
219
+ while (!admin.requests.includes(request) && Date.now() < deadline) {
220
+ await Bun.sleep(50);
221
+ }
222
+ }
223
+
224
+ const adminEnv = (admin: FakeAdmin): Record<string, string> => ({
225
+ SHIPWRIGHT_API_URL: admin.url,
226
+ SHIPWRIGHT_AGENT_API_KEY: API_KEY,
227
+ SHIPWRIGHT_AGENT_ID: AGENT_ID,
228
+ });
229
+
230
+ // ─── Tests ─────────────────────────────────────────────────────────────────────
231
+
232
+ describe("startAgent — startup sequencing (admin wired)", () => {
233
+ it(
234
+ "runs the boot steps in documented order and serves /health",
235
+ async () => {
236
+ const admin = startFakeAdmin();
237
+ const b = bootAgent(adminEnv(admin));
238
+ try {
239
+ await b.waitFor("[agent] cron sync started");
240
+ const out = b.output();
241
+
242
+ // Step 1 -> 2 -> 3 -> 4 -> 5 -> 5b -> 6
243
+ const order = [
244
+ "[agent] agent home initialized",
245
+ "[agent] health server on port",
246
+ "[agent] mise startup complete",
247
+ "[agent] default plugin install complete",
248
+ "[agent] config sync started (60s interval)",
249
+ "[agent] agent template reconciled",
250
+ "[agent] system crons reconciled",
251
+ "[agent] PR state reconciler started",
252
+ "[agent] cron sync started (60s interval)",
253
+ ].map((n) => at(out, n));
254
+ expect(order).toEqual([...order].sort((x, y) => x - y));
255
+
256
+ // Health server is already bound while the agent runs.
257
+ const res = await fetch(`http://127.0.0.1:${b.healthPort}/health`);
258
+ expect(res.status).toBe(200);
259
+ } finally {
260
+ b.proc.kill("SIGKILL");
261
+ await b.exited;
262
+ admin.stop();
263
+ }
264
+ },
265
+ BOOT_TIMEOUT_MS,
266
+ );
267
+
268
+ it(
269
+ "calls the admin API in order, authenticated, and fires the extension hook after the config fetch",
270
+ async () => {
271
+ const admin = startFakeAdmin();
272
+ const b = bootAgent(adminEnv(admin));
273
+ try {
274
+ await b.waitFor("[agent] cron sync started");
275
+ const [cfg, tmpl, sys] = [
276
+ `GET /agents/${AGENT_ID}/config`,
277
+ `POST /agents/${AGENT_ID}/template/reconcile`,
278
+ `POST /agents/${AGENT_ID}/crons/reconcile`,
279
+ ].map((r) => admin.requests.indexOf(r));
280
+ expect(cfg).toBeGreaterThanOrEqual(0);
281
+ expect(tmpl).toBeGreaterThan(cfg);
282
+ expect(sys).toBeGreaterThan(tmpl);
283
+ // Cron sync is last (Step 6) and fire-and-forget.
284
+ await waitForRequest(admin, `GET /agents/${AGENT_ID}/crons`);
285
+ expect(admin.requests).toContain(`GET /agents/${AGENT_ID}/crons`);
286
+ expect(
287
+ admin.requests.indexOf(`GET /agents/${AGENT_ID}/crons`),
288
+ ).toBeGreaterThan(sys);
289
+ expect(admin.authHeaders.every((h) => h === `Bearer ${API_KEY}`)).toBe(
290
+ true,
291
+ );
292
+
293
+ const ext = readFileSync(join(tmpRoot, "ext.log"), "utf8");
294
+ expect(ext).toBe("onConfigSync:coding\n");
295
+ // The bundle env was applied before boot finished.
296
+ expect(b.output()).toContain(
297
+ "[config-sync] updated: BOOT_TEST_SYNCED_VAR",
298
+ );
299
+ } finally {
300
+ b.proc.kill("SIGKILL");
301
+ await b.exited;
302
+ admin.stop();
303
+ }
304
+ },
305
+ BOOT_TIMEOUT_MS,
306
+ );
307
+
308
+ it(
309
+ "starts the chat poll loop only when both chat service vars are set",
310
+ async () => {
311
+ const admin = startFakeAdmin();
312
+ const b = bootAgent({
313
+ ...adminEnv(admin),
314
+ SHIPWRIGHT_CHAT_SERVICE_URL: "http://127.0.0.1:1",
315
+ SHIPWRIGHT_CHAT_SERVICE_TOKEN: "chat-token",
316
+ SHIPWRIGHT_CHAT_POLL_INTERVAL_MS: "3600000",
317
+ });
318
+ try {
319
+ await b.waitFor("[agent] chat poll loop started (3600000ms interval)");
320
+ const out = b.output();
321
+ expect(at(out, "[agent] cron sync started")).toBeLessThan(
322
+ at(out, "[agent] chat poll loop started"),
323
+ );
324
+ } finally {
325
+ b.proc.kill("SIGKILL");
326
+ await b.exited;
327
+ admin.stop();
328
+ }
329
+ },
330
+ BOOT_TIMEOUT_MS,
331
+ );
332
+ });
333
+
334
+ describe("startAgent — failure paths are non-fatal", () => {
335
+ it(
336
+ "keeps booting when the config bundle fetch returns 404, and still reconciles",
337
+ async () => {
338
+ const admin = startFakeAdmin({
339
+ [`GET /agents/${AGENT_ID}/config`]: () =>
340
+ new Response(JSON.stringify({ error: "nope" }), {
341
+ status: 404,
342
+ headers: { "Content-Type": "application/json" },
343
+ }),
344
+ });
345
+ const b = bootAgent(adminEnv(admin));
346
+ try {
347
+ await b.waitFor("[agent] cron sync started");
348
+ const out = b.output();
349
+ expect(out).toContain("[config-sync] no config bundle found");
350
+ expect(out).toContain("[agent] config sync started (60s interval)");
351
+ expect(out).toContain("[agent] agent template reconciled");
352
+ // The extension hook is never reached when the fetch fails.
353
+ expect(existsSync(join(tmpRoot, "ext.log"))).toBe(false);
354
+ } finally {
355
+ b.proc.kill("SIGKILL");
356
+ await b.exited;
357
+ admin.stop();
358
+ }
359
+ },
360
+ BOOT_TIMEOUT_MS,
361
+ );
362
+
363
+ it(
364
+ "keeps booting when the config bundle fetch returns 500",
365
+ async () => {
366
+ const admin = startFakeAdmin({
367
+ [`GET /agents/${AGENT_ID}/config`]: () =>
368
+ new Response(JSON.stringify({ error: "boom" }), {
369
+ status: 500,
370
+ headers: { "Content-Type": "application/json" },
371
+ }),
372
+ });
373
+ const b = bootAgent(adminEnv(admin));
374
+ try {
375
+ await b.waitFor("[agent] cron sync started");
376
+ const out = b.output();
377
+ expect(out).toContain("[config-sync] failed to fetch config bundle:");
378
+ expect(out).toContain("failed: 500");
379
+ expect(out).toContain("[agent] config sync started (60s interval)");
380
+ } finally {
381
+ b.proc.kill("SIGKILL");
382
+ await b.exited;
383
+ admin.stop();
384
+ }
385
+ },
386
+ BOOT_TIMEOUT_MS,
387
+ );
388
+
389
+ it(
390
+ "a reconcileTemplate failure is logged non-fatally and reconcileSystemCrons still runs",
391
+ async () => {
392
+ const admin = startFakeAdmin({
393
+ [`POST /agents/${AGENT_ID}/template/reconcile`]: () =>
394
+ new Response("{}", { status: 500 }),
395
+ });
396
+ const b = bootAgent(adminEnv(admin));
397
+ try {
398
+ await b.waitFor("[agent] cron sync started");
399
+ const out = b.output();
400
+ expect(out).toContain("[agent] reconcileTemplate failed (non-fatal):");
401
+ expect(out).not.toContain("[agent] agent template reconciled");
402
+ expect(out).toContain("[agent] system crons reconciled");
403
+ } finally {
404
+ b.proc.kill("SIGKILL");
405
+ await b.exited;
406
+ admin.stop();
407
+ }
408
+ },
409
+ BOOT_TIMEOUT_MS,
410
+ );
411
+
412
+ it(
413
+ "a reconcileSystemCrons failure is logged non-fatally and the cron sync loop still starts",
414
+ async () => {
415
+ const admin = startFakeAdmin({
416
+ [`POST /agents/${AGENT_ID}/crons/reconcile`]: () =>
417
+ new Response("{}", { status: 500 }),
418
+ });
419
+ const b = bootAgent(adminEnv(admin));
420
+ try {
421
+ await b.waitFor("[agent] cron sync started");
422
+ const out = b.output();
423
+ expect(out).toContain(
424
+ "[agent] reconcileSystemCrons failed (non-fatal):",
425
+ );
426
+ expect(out).toContain("[agent] agent template reconciled");
427
+ expect(out).not.toContain("[agent] system crons reconciled");
428
+ } finally {
429
+ b.proc.kill("SIGKILL");
430
+ await b.exited;
431
+ admin.stop();
432
+ }
433
+ },
434
+ BOOT_TIMEOUT_MS,
435
+ );
436
+
437
+ it(
438
+ "logs a cron-list failure without crashing the process",
439
+ async () => {
440
+ const admin = startFakeAdmin({
441
+ [`GET /agents/${AGENT_ID}/crons`]: () =>
442
+ new Response("{}", { status: 500 }),
443
+ });
444
+ const b = bootAgent(adminEnv(admin));
445
+ try {
446
+ await b.waitFor("[cron-sync] failed to fetch cron jobs:");
447
+ const health = await fetch(`http://127.0.0.1:${b.healthPort}/health`);
448
+ expect(health.status).toBe(200);
449
+ } finally {
450
+ b.proc.kill("SIGKILL");
451
+ await b.exited;
452
+ admin.stop();
453
+ }
454
+ },
455
+ BOOT_TIMEOUT_MS,
456
+ );
457
+ });
458
+
459
+ describe("startAgent — offline / unwired boot", () => {
460
+ it(
461
+ "without admin credentials skips config sync, reconcile and cron sync, and runs Slack-less",
462
+ async () => {
463
+ const b = bootAgent({});
464
+ try {
465
+ await b.waitFor("[agent] Slack credentials absent");
466
+ const out = b.output();
467
+ expect(out).toContain("[agent] default plugin install complete");
468
+ expect(out).not.toContain("config sync started");
469
+ expect(out).not.toContain("reconciled");
470
+ expect(out).not.toContain("cron sync started");
471
+ expect(out).not.toContain("PR state reconciler started");
472
+ expect(out).toContain("Offline mode");
473
+ expect(at(out, "[agent] default plugin install complete")).toBeLessThan(
474
+ at(out, "[agent] Slack credentials absent"),
475
+ );
476
+ const res = await fetch(`http://127.0.0.1:${b.healthPort}/health`);
477
+ expect(res.status).toBe(200);
478
+ } finally {
479
+ b.proc.kill("SIGKILL");
480
+ await b.exited;
481
+ }
482
+ },
483
+ BOOT_TIMEOUT_MS,
484
+ );
485
+
486
+ it(
487
+ "initialises the agent home directory before anything else",
488
+ async () => {
489
+ const b = bootAgent({});
490
+ try {
491
+ await b.waitFor("[agent] health server on port");
492
+ expect(existsSync(join(tmpRoot, "agent-home"))).toBe(true);
493
+ expect(existsSync(join(tmpRoot, "agent-home", "workspace"))).toBe(true);
494
+ } finally {
495
+ b.proc.kill("SIGKILL");
496
+ await b.exited;
497
+ }
498
+ },
499
+ BOOT_TIMEOUT_MS,
500
+ );
501
+ });
502
+
503
+ describe("startAgent — graceful shutdown (Step 8)", () => {
504
+ for (const signal of ["SIGTERM", "SIGINT"] as const) {
505
+ it(
506
+ `exits 0 after logging the ordered shutdown sequence on ${signal}`,
507
+ async () => {
508
+ const b = bootAgent({});
509
+ await b.waitFor("[agent] Slack credentials absent");
510
+ const code = await shutdownAndWait(b, signal);
511
+ expect(code).toBe(0);
512
+ const out = b.output();
513
+ expect(
514
+ at(out, `received ${signal}, beginning graceful shutdown`),
515
+ ).toBeLessThan(at(out, "[agent] shutdown complete"));
516
+ // Offline mode: no Slack app to stop.
517
+ expect(out).not.toContain("[agent] Slack app stopped");
518
+ },
519
+ BOOT_TIMEOUT_MS,
520
+ );
521
+ }
522
+
523
+ it(
524
+ "unschedules cron tasks on shutdown when jobs were scheduled",
525
+ async () => {
526
+ const admin = startFakeAdmin({
527
+ [`GET /agents/${AGENT_ID}/crons`]: () =>
528
+ new Response(
529
+ JSON.stringify([
530
+ {
531
+ id: "job-1",
532
+ name: "nightly",
533
+ enabled: true,
534
+ parentCronId: null,
535
+ schedule: "0 3 * * *",
536
+ prompt: "hello",
537
+ channel: null,
538
+ user: null,
539
+ silent: false,
540
+ preCheck: null,
541
+ },
542
+ ]),
543
+ { headers: { "Content-Type": "application/json" } },
544
+ ),
545
+ });
546
+ const b = bootAgent(adminEnv(admin));
547
+ try {
548
+ await b.waitFor("[agent] cron sync started");
549
+ // syncCrons is fire-and-forget; wait until it has hit the API.
550
+ await waitForRequest(admin, `GET /agents/${AGENT_ID}/crons`);
551
+ await Bun.sleep(300);
552
+ const code = await shutdownAndWait(b);
553
+ expect(code).toBe(0);
554
+ expect(b.output()).toContain(
555
+ "[agent] cron unscheduled on shutdown: job-1",
556
+ );
557
+ } finally {
558
+ admin.stop();
559
+ }
560
+ },
561
+ BOOT_TIMEOUT_MS,
562
+ );
563
+ });
@@ -0,0 +1,153 @@
1
+ /**
2
+ * agent/src/runtime/crypto.unit.test.ts
3
+ * Unit tests for runtime/crypto.ts (AES-256-GCM encrypt / decrypt).
4
+ * Pure logic — no I/O, no DB, no network.
5
+ */
6
+
7
+ import { describe, expect, it } from "bun:test";
8
+ import { decrypt, encrypt } from "./crypto.ts";
9
+
10
+ // ─── Test key ─────────────────────────────────────────────────────────────────
11
+ // A known 64-char hex key (32 bytes) for deterministic tests.
12
+ const TEST_KEY =
13
+ "0000000000000000000000000000000000000000000000000000000000000001";
14
+ const OTHER_KEY =
15
+ "0000000000000000000000000000000000000000000000000000000000000002";
16
+
17
+ /** Flips the final byte of a hex string so it always differs from the input. */
18
+ function flipLastByte(hex: string): string {
19
+ const last = hex.slice(-2);
20
+ return hex.slice(0, -2) + (last === "ff" ? "00" : "ff");
21
+ }
22
+
23
+ /** Returns an encrypted value with the part at `index` replaced via `mutate`. */
24
+ function tamperPart(
25
+ encrypted: string,
26
+ index: 0 | 1 | 2,
27
+ mutate: (part: string) => string,
28
+ ): string {
29
+ const parts = encrypted.split(":");
30
+ parts[index] = mutate(parts[index] ?? "");
31
+ return parts.join(":");
32
+ }
33
+
34
+ describe("encrypt / decrypt (AES-256-GCM)", () => {
35
+ describe("round trip", () => {
36
+ it("round-trips a plain ASCII string", () => {
37
+ const plaintext = "hello world";
38
+ expect(decrypt(encrypt(plaintext, TEST_KEY), TEST_KEY)).toBe(plaintext);
39
+ });
40
+
41
+ it("round-trips an empty string", () => {
42
+ expect(decrypt(encrypt("", TEST_KEY), TEST_KEY)).toBe("");
43
+ });
44
+
45
+ it("round-trips a unicode string", () => {
46
+ const plaintext = "こんにちは世界 🌍 — café résumé naïve";
47
+ expect(decrypt(encrypt(plaintext, TEST_KEY), TEST_KEY)).toBe(plaintext);
48
+ });
49
+
50
+ it("round-trips a large (64 KiB) value", () => {
51
+ const plaintext = "x".repeat(64 * 1024);
52
+ expect(decrypt(encrypt(plaintext, TEST_KEY), TEST_KEY)).toBe(plaintext);
53
+ });
54
+ });
55
+
56
+ describe("random IV", () => {
57
+ it("produces a different ciphertext on each call", () => {
58
+ const enc1 = encrypt("same input", TEST_KEY);
59
+ const enc2 = encrypt("same input", TEST_KEY);
60
+ expect(enc1).not.toBe(enc2);
61
+ });
62
+
63
+ it("uses a different IV on each call", () => {
64
+ const iv1 = encrypt("same input", TEST_KEY).split(":")[0];
65
+ const iv2 = encrypt("same input", TEST_KEY).split(":")[0];
66
+ expect(iv1).not.toBe(iv2);
67
+ });
68
+ });
69
+
70
+ describe("format", () => {
71
+ it("is iv:ciphertext:authTag (3 colon-separated hex parts)", () => {
72
+ const parts = encrypt("test", TEST_KEY).split(":");
73
+ expect(parts.length).toBe(3);
74
+ for (const part of parts) {
75
+ expect(part).toMatch(/^[0-9a-f]+$/);
76
+ }
77
+ });
78
+
79
+ it("has a 12-byte IV (24 hex chars)", () => {
80
+ expect(encrypt("test", TEST_KEY).split(":")[0]).toHaveLength(24);
81
+ });
82
+
83
+ it("has a 16-byte auth tag (32 hex chars)", () => {
84
+ expect(encrypt("test", TEST_KEY).split(":")[2]).toHaveLength(32);
85
+ });
86
+ });
87
+
88
+ describe("authentication failures", () => {
89
+ it("throws when decrypting with the wrong key", () => {
90
+ const encrypted = encrypt("secret", TEST_KEY);
91
+ expect(() => decrypt(encrypted, OTHER_KEY)).toThrow();
92
+ });
93
+
94
+ it("throws when the ciphertext is tampered", () => {
95
+ const tampered = tamperPart(encrypt("secret", TEST_KEY), 1, flipLastByte);
96
+ expect(() => decrypt(tampered, TEST_KEY)).toThrow();
97
+ });
98
+
99
+ it("throws when the auth tag is tampered", () => {
100
+ const tampered = tamperPart(encrypt("secret", TEST_KEY), 2, flipLastByte);
101
+ expect(() => decrypt(tampered, TEST_KEY)).toThrow();
102
+ });
103
+
104
+ it("throws when the IV is tampered", () => {
105
+ const tampered = tamperPart(encrypt("secret", TEST_KEY), 0, flipLastByte);
106
+ expect(() => decrypt(tampered, TEST_KEY)).toThrow();
107
+ });
108
+ });
109
+
110
+ describe("malformed input", () => {
111
+ it("throws on 1 part", () => {
112
+ expect(() => decrypt("notvalid", TEST_KEY)).toThrow(
113
+ "Invalid encrypted format",
114
+ );
115
+ });
116
+
117
+ it("throws on 2 parts", () => {
118
+ expect(() => decrypt("aa:bb", TEST_KEY)).toThrow(
119
+ "Invalid encrypted format",
120
+ );
121
+ });
122
+
123
+ it("throws on 4 parts", () => {
124
+ expect(() => decrypt("aa:bb:cc:dd", TEST_KEY)).toThrow(
125
+ "Invalid encrypted format",
126
+ );
127
+ });
128
+
129
+ it("throws on an empty string", () => {
130
+ expect(() => decrypt("", TEST_KEY)).toThrow("Invalid encrypted format");
131
+ });
132
+ });
133
+
134
+ describe("invalid key length", () => {
135
+ const validEncrypted = encrypt("secret", TEST_KEY);
136
+
137
+ it("encrypt throws on a short key", () => {
138
+ expect(() => encrypt("secret", "abcd")).toThrow();
139
+ });
140
+
141
+ it("encrypt throws on an empty key", () => {
142
+ expect(() => encrypt("secret", "")).toThrow();
143
+ });
144
+
145
+ it("decrypt throws on a short key", () => {
146
+ expect(() => decrypt(validEncrypted, "abcd")).toThrow();
147
+ });
148
+
149
+ it("decrypt throws on an empty key", () => {
150
+ expect(() => decrypt(validEncrypted, "")).toThrow();
151
+ });
152
+ });
153
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@app-vitals/agent-runtime",
3
- "version": "1.91.0",
3
+ "version": "1.92.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/app-vitals/agent.git",
@@ -41,8 +41,8 @@
41
41
  "./workspace-paths": "./workspace-paths.ts"
42
42
  },
43
43
  "dependencies": {
44
- "@app-vitals/agent-admin": "1.91.0",
45
- "@app-vitals/agent-lib": "1.91.0",
44
+ "@app-vitals/agent-admin": "1.92.0",
45
+ "@app-vitals/agent-lib": "1.92.0",
46
46
  "@octokit/auth-app": "^8.2.0",
47
47
  "@sentry/bun": "^10.63.0",
48
48
  "@slack/bolt": "^5.0.0",
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Unit tests for agent/src/runtime/workspace-paths.ts — env-driven, no module mocks.
3
+ */
4
+
5
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
6
+ import { resolveWorkspacePath, splitOrgRepo } from "./workspace-paths.ts";
7
+
8
+ describe("resolveWorkspacePath", () => {
9
+ let savedWorkspacePath: string | undefined;
10
+ let savedAgentHome: string | undefined;
11
+
12
+ beforeEach(() => {
13
+ savedWorkspacePath = process.env.WORKSPACE_PATH;
14
+ savedAgentHome = process.env.AGENT_HOME;
15
+ delete process.env.WORKSPACE_PATH;
16
+ delete process.env.AGENT_HOME;
17
+ });
18
+
19
+ afterEach(() => {
20
+ if (savedWorkspacePath === undefined) delete process.env.WORKSPACE_PATH;
21
+ else process.env.WORKSPACE_PATH = savedWorkspacePath;
22
+ if (savedAgentHome === undefined) delete process.env.AGENT_HOME;
23
+ else process.env.AGENT_HOME = savedAgentHome;
24
+ });
25
+
26
+ it("prefers WORKSPACE_PATH over AGENT_HOME", () => {
27
+ process.env.WORKSPACE_PATH = "/explicit/ws";
28
+ process.env.AGENT_HOME = "/home/agent";
29
+ expect(resolveWorkspacePath()).toBe("/explicit/ws");
30
+ });
31
+
32
+ it("trims whitespace from WORKSPACE_PATH", () => {
33
+ process.env.WORKSPACE_PATH = " /explicit/ws \n";
34
+ expect(resolveWorkspacePath()).toBe("/explicit/ws");
35
+ });
36
+
37
+ it("falls through to AGENT_HOME/workspace when WORKSPACE_PATH is whitespace-only", () => {
38
+ process.env.WORKSPACE_PATH = " ";
39
+ process.env.AGENT_HOME = "/home/agent";
40
+ expect(resolveWorkspacePath()).toBe("/home/agent/workspace");
41
+ });
42
+
43
+ it("falls through to AGENT_HOME/workspace when WORKSPACE_PATH is empty", () => {
44
+ process.env.WORKSPACE_PATH = "";
45
+ process.env.AGENT_HOME = "/home/agent";
46
+ expect(resolveWorkspacePath()).toBe("/home/agent/workspace");
47
+ });
48
+
49
+ it("uses AGENT_HOME/workspace when WORKSPACE_PATH is unset", () => {
50
+ process.env.AGENT_HOME = "/home/agent";
51
+ expect(resolveWorkspacePath()).toBe("/home/agent/workspace");
52
+ });
53
+
54
+ it("trims whitespace from AGENT_HOME", () => {
55
+ process.env.AGENT_HOME = " /home/agent\t";
56
+ expect(resolveWorkspacePath()).toBe("/home/agent/workspace");
57
+ });
58
+
59
+ it("throws when neither variable is set", () => {
60
+ expect(() => resolveWorkspacePath()).toThrow(/AGENT_HOME is not set/);
61
+ });
62
+
63
+ it("throws when both variables are blank", () => {
64
+ process.env.WORKSPACE_PATH = " ";
65
+ process.env.AGENT_HOME = " ";
66
+ expect(() => resolveWorkspacePath()).toThrow(/AGENT_HOME is not set/);
67
+ });
68
+ });
69
+
70
+ describe("splitOrgRepo", () => {
71
+ it("splits org/repo into [org, repo]", () => {
72
+ expect(splitOrgRepo("acme/widgets")).toEqual(["acme", "widgets"]);
73
+ });
74
+
75
+ it("defaults org to app-vitals for a bare repo name", () => {
76
+ expect(splitOrgRepo("shipwright")).toEqual(["app-vitals", "shipwright"]);
77
+ });
78
+
79
+ it("drops segments beyond the second when given extra slashes", () => {
80
+ expect(splitOrgRepo("a/b/c")).toEqual(["a", "b"]);
81
+ });
82
+ });