@app-vitals/agent-admin 1.43.0 → 1.44.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,787 @@
1
+ /**
2
+ * admin/src/agent-template-reconcile.integration.test.ts
3
+ * ATP-2.1: the per-agent template reconcile against real Postgres.
4
+ *
5
+ * Requires DATABASE_URL_ADMIN_TEST to be set; skips otherwise.
6
+ */
7
+
8
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
9
+ import { AGENT_PLATFORM_PLUGIN } from "@app-vitals/agent-lib/default-plugins";
10
+ import type { PrismaClient } from "../prisma/client/client.ts";
11
+ import {
12
+ type AgentTemplateItemKind,
13
+ sealTemplateItemPayload,
14
+ type TemplateItemPayload,
15
+ } from "./agent-template-items.ts";
16
+ import { AgentTemplateReconcileService } from "./agent-template-reconcile.ts";
17
+ import { NotFoundError } from "./errors.ts";
18
+ import { createAdminPrismaClient } from "./prisma-client.ts";
19
+ import type { SpecialtyDefaultsResolver } from "./specialty-defaults.ts";
20
+ import { SPECIALIST_TYPE } from "./specialty-types.ts";
21
+ import { makeStrictTokenCrypto, type TokenCrypto } from "./token-crypto.ts";
22
+
23
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
24
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
25
+
26
+ const KEY = "ab".repeat(32);
27
+
28
+ /** A fixture extension specialty with one tool, one plugin, one system cron. */
29
+ const FIXTURE = "fixture";
30
+ /** An extension specialty that declares no tools at all. */
31
+ const TOOLLESS = "toolless";
32
+
33
+ const fixtureDefaults: SpecialtyDefaultsResolver = (specialty) => {
34
+ if (specialty === FIXTURE) {
35
+ return {
36
+ tools: ["Read"],
37
+ plugins: ["fx@m"],
38
+ crons: [{ name: "fx-loop", schedule: "*/5 * * * *", prompt: "/fx" }],
39
+ };
40
+ }
41
+ if (specialty === TOOLLESS) return { tools: [], plugins: [], crons: [] };
42
+ return undefined;
43
+ };
44
+
45
+ const registry = {
46
+ tryGetType: (s: string) =>
47
+ s === SPECIALIST_TYPE.name ? SPECIALIST_TYPE : undefined,
48
+ };
49
+
50
+ type Item = {
51
+ kind: AgentTemplateItemKind;
52
+ key: string;
53
+ payload?: TemplateItemPayload;
54
+ };
55
+
56
+ describeOrSkip("AgentTemplateReconcileService (integration)", () => {
57
+ let prisma: PrismaClient;
58
+ let service: AgentTemplateReconcileService;
59
+ const realCrypto = makeStrictTokenCrypto(KEY);
60
+ if (!realCrypto) throw new Error("test crypto");
61
+ const crypto: TokenCrypto = realCrypto;
62
+
63
+ beforeEach(async () => {
64
+ prisma = createAdminPrismaClient(TEST_DB as string);
65
+ await prisma.agentTemplateItem.deleteMany();
66
+ await prisma.agentTemplate.deleteMany();
67
+ await prisma.agentCronJob.deleteMany();
68
+ await prisma.agentTool.deleteMany();
69
+ await prisma.agentPlugin.deleteMany();
70
+ await prisma.agentEnv.deleteMany();
71
+ await prisma.agentToken.deleteMany();
72
+ await prisma.agent.deleteMany();
73
+ await prisma.accountInvite.deleteMany();
74
+ await prisma.accountMember.deleteMany();
75
+ await prisma.account.deleteMany();
76
+ service = new AgentTemplateReconcileService(
77
+ prisma,
78
+ crypto,
79
+ registry,
80
+ fixtureDefaults,
81
+ );
82
+ });
83
+
84
+ afterEach(async () => {
85
+ await prisma.$disconnect();
86
+ });
87
+
88
+ // ─── helpers ──────────────────────────────────────────────────────────────
89
+
90
+ async function template(
91
+ accountId: string | null,
92
+ specialty: string | null,
93
+ items: Item[],
94
+ ): Promise<string> {
95
+ const t = await prisma.agentTemplate.create({
96
+ data: { accountId, specialty },
97
+ });
98
+ await setItems(t.id, items);
99
+ return t.id;
100
+ }
101
+
102
+ async function setItems(templateId: string, items: Item[]): Promise<void> {
103
+ await prisma.agentTemplateItem.deleteMany({ where: { templateId } });
104
+ for (const it of items) {
105
+ await prisma.agentTemplateItem.create({
106
+ data: {
107
+ templateId,
108
+ kind: it.kind,
109
+ key: it.key,
110
+ payload: sealTemplateItemPayload(it.kind, it.payload ?? {}, crypto),
111
+ },
112
+ });
113
+ }
114
+ }
115
+
116
+ async function agent(
117
+ opts: {
118
+ specialty?: string;
119
+ accountId?: string | null;
120
+ templateDetached?: boolean;
121
+ } = {},
122
+ ): Promise<string> {
123
+ const a = await prisma.agent.create({
124
+ data: {
125
+ name: `agent-${Math.random().toString(36).slice(2)}`,
126
+ specialty: opts.specialty ?? FIXTURE,
127
+ accountId: opts.accountId ?? null,
128
+ templateDetached: opts.templateDetached ?? false,
129
+ },
130
+ });
131
+ return a.id;
132
+ }
133
+
134
+ async function account(name = "Acme"): Promise<string> {
135
+ return (await prisma.account.create({ data: { name } })).id;
136
+ }
137
+
138
+ async function env(agentId: string): Promise<Record<string, string>> {
139
+ const rows = await prisma.agentEnv.findMany({ where: { agentId } });
140
+ return Object.fromEntries(
141
+ rows.map((r) => [r.key, `${crypto.decrypt(r.value)}|${r.source}`]),
142
+ );
143
+ }
144
+
145
+ async function plugin(agentId: string, name: string) {
146
+ return prisma.agentPlugin.findUnique({
147
+ where: { agentId_name: { agentId, name } },
148
+ });
149
+ }
150
+
151
+ async function snapshot(agentId: string) {
152
+ const [envs, tools, plugins, crons] = await Promise.all([
153
+ prisma.agentEnv.findMany({ where: { agentId }, orderBy: { key: "asc" } }),
154
+ prisma.agentTool.findMany({
155
+ where: { agentId },
156
+ orderBy: { pattern: "asc" },
157
+ }),
158
+ prisma.agentPlugin.findMany({
159
+ where: { agentId },
160
+ orderBy: { name: "asc" },
161
+ }),
162
+ prisma.agentCronJob.findMany({
163
+ where: { agentId },
164
+ orderBy: { id: "asc" },
165
+ }),
166
+ ]);
167
+ return { envs, tools, plugins, crons };
168
+ }
169
+
170
+ // ─── precedence ───────────────────────────────────────────────────────────
171
+
172
+ it("the most specific of all five layers wins for a key defined in several", async () => {
173
+ const acct = await account();
174
+ const other = await account("Other");
175
+ const agentId = await agent({ accountId: acct });
176
+ // "fx@m" is a built-in default of FIXTURE (layer 0, version null).
177
+ const layerIds = {
178
+ deployment: await template(null, null, [
179
+ { kind: "plugin", key: "fx@m", payload: { version: "1" } },
180
+ { kind: "env", key: "LEVEL", payload: { value: "deployment" } },
181
+ ]),
182
+ deploymentType: await template(null, FIXTURE, [
183
+ { kind: "plugin", key: "fx@m", payload: { version: "2" } },
184
+ { kind: "env", key: "LEVEL", payload: { value: "deployment-type" } },
185
+ ]),
186
+ account: await template(acct, null, [
187
+ { kind: "plugin", key: "fx@m", payload: { version: "3" } },
188
+ { kind: "env", key: "LEVEL", payload: { value: "account" } },
189
+ ]),
190
+ accountType: await template(acct, FIXTURE, [
191
+ { kind: "plugin", key: "fx@m", payload: { version: "4" } },
192
+ { kind: "env", key: "LEVEL", payload: { value: "account-type" } },
193
+ ]),
194
+ };
195
+ // Templates outside the agent's scope never apply.
196
+ await template(other, FIXTURE, [
197
+ { kind: "plugin", key: "fx@m", payload: { version: "other-account" } },
198
+ ]);
199
+ await template(null, "specialist", [
200
+ { kind: "plugin", key: "fx@m", payload: { version: "other-type" } },
201
+ ]);
202
+
203
+ await service.reconcile(agentId);
204
+ expect((await plugin(agentId, "fx@m"))?.version).toBe("4");
205
+ expect((await env(agentId)).LEVEL).toBe("account-type|template");
206
+
207
+ const expected = [
208
+ [layerIds.accountType, "3", "account"],
209
+ [layerIds.account, "2", "deployment-type"],
210
+ [layerIds.deploymentType, "1", "deployment"],
211
+ ] as const;
212
+ for (const [drop, version, level] of expected) {
213
+ await prisma.agentTemplate.delete({ where: { id: drop } });
214
+ await service.reconcile(agentId);
215
+ const row = await plugin(agentId, "fx@m");
216
+ expect(row?.version).toBe(version);
217
+ expect(row?.source).toBe("template");
218
+ expect((await env(agentId)).LEVEL).toBe(`${level}|template`);
219
+ }
220
+
221
+ // Only the specialty default is left: the plugin stays (version null),
222
+ // the env key, defined by no layer any more, is removed.
223
+ await prisma.agentTemplate.delete({ where: { id: layerIds.deployment } });
224
+ await service.reconcile(agentId);
225
+ expect((await plugin(agentId, "fx@m"))?.version).toBeNull();
226
+ expect((await env(agentId)).LEVEL).toBeUndefined();
227
+ });
228
+
229
+ // ─── add / track / remove ─────────────────────────────────────────────────
230
+
231
+ it("adds every missing item, including the specialty defaults, as template rows", async () => {
232
+ const agentId = await agent();
233
+ await template(null, null, [
234
+ { kind: "env", key: "SENTRY_DSN", payload: { value: "dsn" } },
235
+ { kind: "env", key: "API_SECRET", payload: { value: "s", secret: true } },
236
+ { kind: "tool", key: "Write" },
237
+ { kind: "plugin", key: "x@y", payload: { version: "1.2.3" } },
238
+ {
239
+ kind: "cron",
240
+ key: "digest",
241
+ payload: {
242
+ schedule: "0 9 * * *",
243
+ prompt: "/digest",
244
+ channel: "C1",
245
+ },
246
+ },
247
+ ]);
248
+
249
+ const result = await service.reconcile(agentId);
250
+ expect(result.status).toBe("reconciled");
251
+ expect(result.counts.env.created).toBe(2);
252
+ expect(result.counts.tool.created).toBe(2); // Read (default) + Write
253
+ expect(result.counts.plugin.created).toBe(3); // platform + fx@m + x@y
254
+ expect(result.counts.cron.created).toBe(1);
255
+ expect(result.systemCrons.created).toBe(1);
256
+
257
+ expect(await env(agentId)).toEqual({
258
+ SENTRY_DSN: "dsn|template",
259
+ API_SECRET: "s|template",
260
+ });
261
+ const secretRow = await prisma.agentEnv.findUniqueOrThrow({
262
+ where: { agentId_key: { agentId, key: "API_SECRET" } },
263
+ });
264
+ expect(secretRow.secret).toBe(true);
265
+ expect(secretRow.value).not.toBe("s"); // encrypted at rest
266
+
267
+ const { tools, plugins, crons } = await snapshot(agentId);
268
+ expect(tools.map((t) => [t.pattern, t.enabled, t.source])).toEqual([
269
+ ["Read", true, "template"],
270
+ ["Write", true, "template"],
271
+ ]);
272
+ expect(plugins.map((p) => [p.name, p.version, p.source])).toEqual([
273
+ [AGENT_PLATFORM_PLUGIN, null, "template"],
274
+ ["fx@m", null, "template"],
275
+ ["x@y", "1.2.3", "template"],
276
+ ]);
277
+ const digest = crons.find((c) => c.name === "digest");
278
+ expect(digest).toMatchObject({
279
+ schedule: "0 9 * * *",
280
+ prompt: "/digest",
281
+ channel: "C1",
282
+ user: null,
283
+ silent: false,
284
+ enabled: true,
285
+ system: false,
286
+ source: "template",
287
+ });
288
+ const loop = crons.find((c) => c.name === "fx-loop");
289
+ expect(loop?.system).toBe(true);
290
+ });
291
+
292
+ it("template rows track edits in place and are removed when the template drops them", async () => {
293
+ const agentId = await agent();
294
+ const t = await template(null, null, [
295
+ { kind: "env", key: "A", payload: { value: "1" } },
296
+ { kind: "tool", key: "Write" },
297
+ { kind: "plugin", key: "x@y", payload: { version: "1" } },
298
+ {
299
+ kind: "cron",
300
+ key: "digest",
301
+ payload: { schedule: "0 9 * * *", prompt: "/d", silent: true },
302
+ },
303
+ ]);
304
+ await service.reconcile(agentId);
305
+ const before = await snapshot(agentId);
306
+
307
+ await setItems(t, [
308
+ { kind: "env", key: "A", payload: { value: "2", secret: true } },
309
+ { kind: "tool", key: "Write", payload: { enabled: false } },
310
+ { kind: "plugin", key: "x@y", payload: { version: "2" } },
311
+ {
312
+ kind: "cron",
313
+ key: "digest",
314
+ payload: { schedule: "0 10 * * *", prompt: "/d2", silent: true },
315
+ },
316
+ ]);
317
+ const edited = await service.reconcile(agentId);
318
+ expect(edited.counts.env.updated).toBe(1);
319
+ expect(edited.counts.tool.updated).toBe(1);
320
+ expect(edited.counts.plugin.updated).toBe(1);
321
+ expect(edited.counts.cron.updated).toBe(1);
322
+
323
+ const after = await snapshot(agentId);
324
+ const envRow = after.envs.find((e) => e.key === "A");
325
+ expect(envRow?.id).toBe(before.envs.find((e) => e.key === "A")?.id);
326
+ expect(crypto.decrypt(envRow?.value ?? "")).toBe("2");
327
+ expect(envRow?.secret).toBe(true);
328
+ expect(after.tools.find((x) => x.pattern === "Write")?.enabled).toBe(false);
329
+ expect(after.plugins.find((p) => p.name === "x@y")?.version).toBe("2");
330
+ const digest = after.crons.find((c) => c.name === "digest");
331
+ expect(digest?.id).toBe(before.crons.find((c) => c.name === "digest")?.id);
332
+ expect(digest).toMatchObject({ schedule: "0 10 * * *", prompt: "/d2" });
333
+
334
+ await setItems(t, []);
335
+ const removed = await service.reconcile(agentId);
336
+ expect(removed.counts.env.deleted).toBe(1);
337
+ expect(removed.counts.tool.deleted).toBe(1);
338
+ expect(removed.counts.plugin.deleted).toBe(1);
339
+ expect(removed.counts.cron.deleted).toBe(1);
340
+ const final = await snapshot(agentId);
341
+ expect(final.envs).toEqual([]);
342
+ expect(final.tools.map((x) => x.pattern)).toEqual(["Read"]);
343
+ expect(final.plugins.map((p) => p.name).sort()).toEqual(
344
+ [AGENT_PLATFORM_PLUGIN, "fx@m"].sort(),
345
+ );
346
+ expect(final.crons.map((c) => c.name)).toEqual(["fx-loop"]);
347
+ });
348
+
349
+ // ─── custom rows, tombstones, detached ────────────────────────────────────
350
+
351
+ it("never modifies or removes custom rows", async () => {
352
+ const agentId = await agent();
353
+ await prisma.agentEnv.create({
354
+ data: { agentId, key: "A", value: crypto.encrypt("mine") },
355
+ });
356
+ await prisma.agentEnv.create({
357
+ data: { agentId, key: "ONLY_MINE", value: crypto.encrypt("x") },
358
+ });
359
+ await prisma.agentTool.create({ data: { agentId, pattern: "Custom" } });
360
+ await prisma.agentPlugin.create({
361
+ data: { agentId, name: "x@y", version: "mine" },
362
+ });
363
+ await prisma.agentCronJob.create({
364
+ data: { agentId, schedule: "0 1 * * *", prompt: "mine", silent: true },
365
+ });
366
+ await template(null, null, [
367
+ { kind: "env", key: "A", payload: { value: "template" } },
368
+ { kind: "plugin", key: "x@y", payload: { version: "template" } },
369
+ ]);
370
+ const before = await snapshot(agentId);
371
+
372
+ await service.reconcile(agentId);
373
+ const after = await snapshot(agentId);
374
+ for (const row of before.envs) {
375
+ expect(after.envs.find((e) => e.id === row.id)).toEqual(row);
376
+ }
377
+ expect(after.tools.find((t) => t.pattern === "Custom")).toEqual(
378
+ before.tools[0],
379
+ );
380
+ expect(after.plugins.find((p) => p.name === "x@y")).toEqual(
381
+ before.plugins[0],
382
+ );
383
+ expect(after.crons.find((c) => c.prompt === "mine")).toEqual(
384
+ before.crons[0],
385
+ );
386
+ });
387
+
388
+ it("honors tombstones: a disabled custom row is neither re-added, re-enabled nor adopted", async () => {
389
+ const agentId = await agent();
390
+ // Tombstones as ATP-1.2 writes them (enabled=false, source=custom); the
391
+ // env tombstone even holds the template's exact value.
392
+ await prisma.agentEnv.create({
393
+ data: {
394
+ agentId,
395
+ key: "A",
396
+ value: crypto.encrypt("v"),
397
+ enabled: false,
398
+ },
399
+ });
400
+ await prisma.agentTool.create({
401
+ data: { agentId, pattern: "Write", enabled: false },
402
+ });
403
+ await prisma.agentPlugin.create({
404
+ data: { agentId, name: "x@y", enabled: false },
405
+ });
406
+ await prisma.agentCronJob.create({
407
+ data: {
408
+ agentId,
409
+ name: "digest",
410
+ schedule: "0 9 * * *",
411
+ prompt: "/d",
412
+ enabled: false,
413
+ },
414
+ });
415
+ await template(null, null, [
416
+ { kind: "env", key: "A", payload: { value: "v" } },
417
+ { kind: "tool", key: "Write" },
418
+ { kind: "plugin", key: "x@y" },
419
+ {
420
+ kind: "cron",
421
+ key: "digest",
422
+ payload: { schedule: "0 9 * * *", prompt: "/d" },
423
+ },
424
+ ]);
425
+ const before = await snapshot(agentId);
426
+
427
+ const result = await service.reconcile(agentId);
428
+ const after = await snapshot(agentId);
429
+ expect(after.envs).toEqual(before.envs);
430
+ expect(after.tools.find((t) => t.pattern === "Write")).toEqual(
431
+ before.tools[0],
432
+ );
433
+ expect(after.plugins.find((p) => p.name === "x@y")).toEqual(
434
+ before.plugins[0],
435
+ );
436
+ expect(after.crons.filter((c) => c.name === "digest")).toEqual(
437
+ before.crons,
438
+ );
439
+ for (const kind of ["env", "tool", "plugin", "cron"] as const) {
440
+ expect(result.counts[kind].adopted).toBe(0);
441
+ }
442
+ });
443
+
444
+ it("never touches a detached agent", async () => {
445
+ const agentId = await agent({ templateDetached: true });
446
+ await prisma.agentEnv.create({
447
+ data: {
448
+ agentId,
449
+ key: "OLD",
450
+ value: crypto.encrypt("x"),
451
+ source: "template",
452
+ },
453
+ });
454
+ await template(null, null, [
455
+ { kind: "env", key: "A", payload: { value: "v" } },
456
+ { kind: "tool", key: "Write" },
457
+ ]);
458
+ const before = await snapshot(agentId);
459
+
460
+ const result = await service.reconcile(agentId);
461
+ expect(result.status).toBe("detached");
462
+ expect(await snapshot(agentId)).toEqual(before);
463
+ });
464
+
465
+ // ─── adoption ─────────────────────────────────────────────────────────────
466
+
467
+ it("adopts custom rows whose value already equals the template value", async () => {
468
+ const agentId = await agent();
469
+ const envRow = await prisma.agentEnv.create({
470
+ data: { agentId, key: "A", value: crypto.encrypt("v") },
471
+ });
472
+ await prisma.agentEnv.create({
473
+ data: { agentId, key: "B", value: crypto.encrypt("different") },
474
+ });
475
+ // Seeded at create time as custom (pre-ATP rows): the specialty default.
476
+ const toolRow = await prisma.agentTool.create({
477
+ data: { agentId, pattern: "Read" },
478
+ });
479
+ const pluginRow = await prisma.agentPlugin.create({
480
+ data: { agentId, name: "x@y", version: "1" },
481
+ });
482
+ await template(null, null, [
483
+ { kind: "env", key: "A", payload: { value: "v" } },
484
+ { kind: "env", key: "B", payload: { value: "template" } },
485
+ { kind: "plugin", key: "x@y", payload: { version: "1" } },
486
+ ]);
487
+
488
+ const result = await service.reconcile(agentId);
489
+ expect(result.counts.env.adopted).toBe(1);
490
+ expect(result.counts.tool.adopted).toBe(1);
491
+ expect(result.counts.plugin.adopted).toBe(1);
492
+ const after = await snapshot(agentId);
493
+ expect(after.envs.find((e) => e.key === "A")).toMatchObject({
494
+ id: envRow.id,
495
+ source: "template",
496
+ });
497
+ expect(after.envs.find((e) => e.key === "B")?.source).toBe("custom");
498
+ expect(after.tools.find((t) => t.pattern === "Read")).toMatchObject({
499
+ id: toolRow.id,
500
+ source: "template",
501
+ });
502
+ expect(after.plugins.find((p) => p.name === "x@y")).toMatchObject({
503
+ id: pluginRow.id,
504
+ source: "template",
505
+ });
506
+ });
507
+
508
+ it("adopts a same-named user cron only when schedule and prompt match; otherwise leaves it and reports it", async () => {
509
+ const agentId = await agent();
510
+ const match = await prisma.agentCronJob.create({
511
+ data: {
512
+ agentId,
513
+ name: "same",
514
+ schedule: "0 9 * * *",
515
+ prompt: "/same",
516
+ channel: "C-mine",
517
+ },
518
+ });
519
+ const differs = await prisma.agentCronJob.create({
520
+ data: {
521
+ agentId,
522
+ name: "differs",
523
+ schedule: "0 9 * * *",
524
+ prompt: "/mine",
525
+ channel: "C-mine",
526
+ },
527
+ });
528
+ await template(null, null, [
529
+ {
530
+ kind: "cron",
531
+ key: "same",
532
+ payload: { schedule: "0 9 * * *", prompt: "/same", silent: true },
533
+ },
534
+ {
535
+ kind: "cron",
536
+ key: "differs",
537
+ payload: { schedule: "0 9 * * *", prompt: "/template", silent: true },
538
+ },
539
+ ]);
540
+
541
+ const result = await service.reconcile(agentId);
542
+ expect(result.counts.cron.adopted).toBe(1);
543
+ expect(result.counts.cron.created).toBe(0);
544
+ expect(result.conflicts).toEqual([
545
+ { kind: "cron", key: "differs", reason: "cron_name_conflict" },
546
+ ]);
547
+
548
+ const crons = await prisma.agentCronJob.findMany({
549
+ where: { agentId, system: false },
550
+ });
551
+ expect(crons).toHaveLength(2);
552
+ // Adopted: same row, now template-owned, template fields applied, fields
553
+ // the template does not set (the delivery target) kept.
554
+ expect(crons.find((c) => c.id === match.id)).toMatchObject({
555
+ source: "template",
556
+ silent: true,
557
+ channel: "C-mine",
558
+ });
559
+ expect(crons.find((c) => c.id === differs.id)).toEqual(differs);
560
+ });
561
+
562
+ // ─── tools floor ──────────────────────────────────────────────────────────
563
+
564
+ it("never reduces allowedTools to empty", async () => {
565
+ const agentId = await agent({ specialty: TOOLLESS });
566
+ const t = await template(null, null, [{ kind: "tool", key: "Write" }]);
567
+ await service.reconcile(agentId);
568
+ expect(
569
+ (await prisma.agentTool.findMany({ where: { agentId } })).map(
570
+ (x) => x.pattern,
571
+ ),
572
+ ).toEqual(["Write"]);
573
+
574
+ // Removing the only tool would leave the agent with none: kept.
575
+ await setItems(t, []);
576
+ const removed = await service.reconcile(agentId);
577
+ expect(removed.toolsEmptyGuarded).toBe(true);
578
+ expect(removed.counts.tool.deleted).toBe(0);
579
+ const kept = await prisma.agentTool.findMany({ where: { agentId } });
580
+ expect(kept.map((x) => [x.pattern, x.enabled])).toEqual([["Write", true]]);
581
+
582
+ // Disabling the only tool is refused the same way.
583
+ await setItems(t, [
584
+ { kind: "tool", key: "Write", payload: { enabled: false } },
585
+ ]);
586
+ const disabled = await service.reconcile(agentId);
587
+ expect(disabled.toolsEmptyGuarded).toBe(true);
588
+ expect(
589
+ (await prisma.agentTool.findFirstOrThrow({ where: { agentId } })).enabled,
590
+ ).toBe(true);
591
+
592
+ // With another enabled tool present the removal goes through.
593
+ await prisma.agentTool.create({ data: { agentId, pattern: "Custom" } });
594
+ await setItems(t, []);
595
+ const ok = await service.reconcile(agentId);
596
+ expect(ok.toolsEmptyGuarded).toBe(false);
597
+ expect(ok.counts.tool.deleted).toBe(1);
598
+ });
599
+
600
+ // ─── specialty change ─────────────────────────────────────────────────────
601
+
602
+ it("re-resolves when the agent's specialty changed", async () => {
603
+ const agentId = await agent({ specialty: FIXTURE });
604
+ await template(null, FIXTURE, [
605
+ { kind: "env", key: "FIXTURE_ONLY", payload: { value: "f" } },
606
+ ]);
607
+ await template(null, "specialist", [
608
+ { kind: "env", key: "SPECIALIST_ONLY", payload: { value: "s" } },
609
+ ]);
610
+ await service.reconcile(agentId);
611
+ expect(await env(agentId)).toEqual({ FIXTURE_ONLY: "f|template" });
612
+
613
+ await prisma.agent.update({
614
+ where: { id: agentId },
615
+ data: { specialty: "specialist" },
616
+ });
617
+ await service.reconcile(agentId);
618
+ expect(await env(agentId)).toEqual({ SPECIALIST_ONLY: "s|template" });
619
+ const { tools, plugins, crons } = await snapshot(agentId);
620
+ expect(tools.map((t) => t.pattern).sort()).toEqual(
621
+ [...SPECIALIST_TYPE.tools].sort(),
622
+ );
623
+ expect(plugins.map((p) => p.name)).toEqual([AGENT_PLATFORM_PLUGIN]);
624
+ expect(crons).toEqual([]); // fx-loop was FIXTURE's system cron
625
+ });
626
+
627
+ it("a template cron named like a specialty system cron overrides it in place", async () => {
628
+ const agentId = await agent();
629
+ await service.reconcile(agentId);
630
+ const loop = await prisma.agentCronJob.findFirstOrThrow({
631
+ where: { agentId, name: "fx-loop" },
632
+ });
633
+
634
+ await template(null, null, [
635
+ {
636
+ kind: "cron",
637
+ key: "fx-loop",
638
+ payload: { schedule: "0 * * * *", prompt: "/fx-template" },
639
+ },
640
+ ]);
641
+ await service.reconcile(agentId);
642
+ const rows = await prisma.agentCronJob.findMany({ where: { agentId } });
643
+ expect(rows).toHaveLength(1);
644
+ expect(rows[0]).toMatchObject({
645
+ id: loop.id,
646
+ system: true,
647
+ schedule: "0 * * * *",
648
+ prompt: "/fx-template",
649
+ });
650
+ });
651
+
652
+ it("a system cron override with an invalid schedule keeps the default and reports a conflict", async () => {
653
+ const agentId = await agent();
654
+ await service.reconcile(agentId);
655
+ const loop = await prisma.agentCronJob.findFirstOrThrow({
656
+ where: { agentId, name: "fx-loop" },
657
+ });
658
+
659
+ await template(null, null, [
660
+ {
661
+ kind: "cron",
662
+ key: "fx-loop",
663
+ payload: { schedule: "every 5 min", prompt: "/fx-template" },
664
+ },
665
+ ]);
666
+ const result = await service.reconcile(agentId);
667
+ expect(result.conflicts).toEqual([
668
+ { kind: "cron", key: "fx-loop", reason: "invalid_cron_schedule" },
669
+ ]);
670
+ const rows = await prisma.agentCronJob.findMany({ where: { agentId } });
671
+ expect(rows).toHaveLength(1);
672
+ expect(rows[0]).toMatchObject({
673
+ id: loop.id,
674
+ system: true,
675
+ schedule: "*/5 * * * *",
676
+ prompt: "/fx",
677
+ });
678
+ });
679
+
680
+ // ─── idempotency and atomicity ────────────────────────────────────────────
681
+
682
+ it("is idempotent: a second reconcile writes nothing", async () => {
683
+ const acct = await account();
684
+ const agentId = await agent({ accountId: acct });
685
+ await template(null, null, [
686
+ { kind: "env", key: "A", payload: { value: "1", secret: true } },
687
+ { kind: "tool", key: "Write" },
688
+ { kind: "plugin", key: "x@y", payload: { version: "1" } },
689
+ {
690
+ kind: "cron",
691
+ key: "digest",
692
+ payload: { schedule: "0 9 * * *", prompt: "/d", channel: "C1" },
693
+ },
694
+ ]);
695
+ await template(acct, FIXTURE, [
696
+ { kind: "env", key: "B", payload: { value: "2" } },
697
+ ]);
698
+ await service.reconcile(agentId);
699
+ const before = await snapshot(agentId);
700
+
701
+ const second = await service.reconcile(agentId);
702
+ for (const kind of ["env", "tool", "plugin", "cron"] as const) {
703
+ expect(second.counts[kind]).toEqual({
704
+ created: 0,
705
+ updated: 0,
706
+ adopted: 0,
707
+ deleted: 0,
708
+ });
709
+ }
710
+ const after = await snapshot(agentId);
711
+ expect(after.envs).toEqual(before.envs);
712
+ expect(after.tools).toEqual(before.tools);
713
+ expect(after.plugins).toEqual(before.plugins);
714
+ expect(after.crons.filter((c) => !c.system)).toEqual(
715
+ before.crons.filter((c) => !c.system),
716
+ );
717
+ });
718
+
719
+ it("writes nothing when the reconcile fails part-way (one transaction)", async () => {
720
+ const agentId = await agent();
721
+ await prisma.agentTool.create({
722
+ data: { agentId, pattern: "Stale", source: "template" },
723
+ });
724
+ await prisma.agentTool.create({ data: { agentId, pattern: "Custom" } });
725
+ await template(null, null, [
726
+ { kind: "tool", key: "Write" },
727
+ { kind: "plugin", key: "x@y" },
728
+ {
729
+ kind: "cron",
730
+ key: "digest",
731
+ payload: { schedule: "0 9 * * *", prompt: "/d" },
732
+ },
733
+ { kind: "env", key: "A", payload: { value: "v" } },
734
+ ]);
735
+ const before = await snapshot(agentId);
736
+
737
+ // Env rows are written last; an encrypt failure there must roll back the
738
+ // tool, plugin and cron writes made before it.
739
+ const failing = new AgentTemplateReconcileService(
740
+ prisma,
741
+ {
742
+ encrypt: () => {
743
+ throw new Error("boom");
744
+ },
745
+ decrypt: (s) => crypto.decrypt(s),
746
+ },
747
+ registry,
748
+ fixtureDefaults,
749
+ );
750
+ await expect(failing.reconcile(agentId)).rejects.toThrow("boom");
751
+ expect(await snapshot(agentId)).toEqual(before);
752
+ });
753
+
754
+ // ─── guards ───────────────────────────────────────────────────────────────
755
+
756
+ it("an unknown specialty changes nothing", async () => {
757
+ const agentId = await agent({ specialty: "renamed-type" });
758
+ await prisma.agentTool.create({
759
+ data: { agentId, pattern: "Read", source: "template" },
760
+ });
761
+ await template(null, null, [{ kind: "tool", key: "Write" }]);
762
+ const before = await snapshot(agentId);
763
+
764
+ const result = await service.reconcile(agentId);
765
+ expect(result.status).toBe("unknown_specialty");
766
+ expect(await snapshot(agentId)).toEqual(before);
767
+ });
768
+
769
+ it("skips and reports a per-agent credential key that reached a template", async () => {
770
+ const agentId = await agent();
771
+ // Bypasses the service-layer denylist (ATP-1.3) on purpose.
772
+ await template(null, null, [
773
+ { kind: "env", key: "GH_TOKEN", payload: { value: "leak" } },
774
+ ]);
775
+ const result = await service.reconcile(agentId);
776
+ expect(await env(agentId)).toEqual({});
777
+ expect(result.conflicts).toEqual([
778
+ { kind: "env", key: "GH_TOKEN", reason: "denylisted_env_key" },
779
+ ]);
780
+ });
781
+
782
+ it("throws NotFoundError for an unknown agent", async () => {
783
+ await expect(service.reconcile("missing")).rejects.toBeInstanceOf(
784
+ NotFoundError,
785
+ );
786
+ });
787
+ });