@app-vitals/agent-admin 1.45.0 → 1.47.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.
@@ -153,8 +153,34 @@ export class AgentTemplateService {
153
153
  private prisma: PrismaClient,
154
154
  private crypto: TokenCrypto,
155
155
  private specialtyRegistry: Pick<SpecialtyTypeResolver, "tryGetType">,
156
+ /**
157
+ * ATP-2.2: applies a template write to the agents that follow it. Optional
158
+ * (additive); absent means template writes are not propagated.
159
+ */
160
+ private fanOut?: {
161
+ reconcileScope(scope: {
162
+ accountId: string | null;
163
+ specialty: string | null;
164
+ }): Promise<unknown>;
165
+ },
156
166
  ) {}
157
167
 
168
+ /** Best-effort fan-out: the template write already committed. */
169
+ private async propagate(scope: {
170
+ accountId: string | null;
171
+ specialty: string | null;
172
+ }): Promise<void> {
173
+ if (!this.fanOut) return;
174
+ try {
175
+ await this.fanOut.reconcileScope(scope);
176
+ } catch (err) {
177
+ console.error(
178
+ "template fan-out failed:",
179
+ err instanceof Error ? err.message : String(err),
180
+ );
181
+ }
182
+ }
183
+
158
184
  private toView(row: TemplateRow): TemplateView {
159
185
  const items = [...row.items]
160
186
  .sort((a, b) =>
@@ -322,8 +348,9 @@ export class AgentTemplateService {
322
348
  }
323
349
  }
324
350
 
351
+ let outcome: { template: TemplateView; created: boolean };
325
352
  try {
326
- return await this.prisma.$transaction(async (tx) => {
353
+ outcome = await this.prisma.$transaction(async (tx) => {
327
354
  const existing = await tx.agentTemplate.findFirst({
328
355
  where: { accountId, specialty },
329
356
  include: { items: true },
@@ -370,6 +397,8 @@ export class AgentTemplateService {
370
397
  }
371
398
  throw err;
372
399
  }
400
+ await this.propagate({ accountId, specialty });
401
+ return outcome;
373
402
  }
374
403
 
375
404
  /** Add or replace one item of a template. */
@@ -401,6 +430,7 @@ export class AgentTemplateService {
401
430
  data: { updatedAt: new Date() },
402
431
  }),
403
432
  ]);
433
+ await this.propagate(existing);
404
434
  return this.get(actor, templateId);
405
435
  }
406
436
 
@@ -411,7 +441,7 @@ export class AgentTemplateService {
411
441
  kind: AgentTemplateItemKind,
412
442
  key: string,
413
443
  ): Promise<void> {
414
- await this.load(actor, templateId);
444
+ const existing = await this.load(actor, templateId);
415
445
  const { count } = await this.prisma.agentTemplateItem.deleteMany({
416
446
  where: { templateId, kind, key },
417
447
  });
@@ -422,11 +452,13 @@ export class AgentTemplateService {
422
452
  where: { id: templateId },
423
453
  data: { updatedAt: new Date() },
424
454
  });
455
+ await this.propagate(existing);
425
456
  }
426
457
 
427
458
  /** Delete a template and (by cascade) its items. */
428
459
  async delete(actor: TemplateActor, id: string): Promise<void> {
429
- await this.load(actor, id);
460
+ const existing = await this.load(actor, id);
430
461
  await this.prisma.agentTemplate.delete({ where: { id } });
462
+ await this.propagate(existing);
431
463
  }
432
464
  }
package/src/agents-api.ts CHANGED
@@ -67,6 +67,7 @@ import {
67
67
  type AgentProvisioner,
68
68
  hasPerAgentIdentity,
69
69
  } from "./agent-provisioner.ts";
70
+ import type { AgentTemplateReconcileService } from "./agent-template-reconcile.ts";
70
71
  import type { AgentTokenService } from "./agent-tokens.ts";
71
72
  import type { AgentToolService } from "./agent-tools.ts";
72
73
  import type { AgentService } from "./agents.ts";
@@ -256,6 +257,15 @@ export interface AdminDeps {
256
257
  specialtyRegistry: SpecialtyTypeResolver;
257
258
  /** Extension-supplied specialty defaults, consulted before the built-in type. */
258
259
  specialtyDefaults?: SpecialtyDefaultsResolver;
260
+ /**
261
+ * ATP-2.2: per-agent template reconcile engine. Optional (additive): backs
262
+ * the /agents/{id}/template/* routes (503 when absent) and seeds the
263
+ * resolved template inside POST /agents.
264
+ */
265
+ agentTemplateReconcileService?: Pick<
266
+ AgentTemplateReconcileService,
267
+ "reconcile" | "reset" | "setDetached"
268
+ >;
259
269
  agentChatTokenService: Pick<
260
270
  AgentChatTokenService,
261
271
  "upsertDailyByModel" | "queryStats"
@@ -1057,6 +1067,115 @@ const createCronRoute = createRoute({
1057
1067
  },
1058
1068
  });
1059
1069
 
1070
+ const TemplateReconcileCountsSchema = z.object({
1071
+ created: z.number().int(),
1072
+ updated: z.number().int(),
1073
+ adopted: z.number().int(),
1074
+ deleted: z.number().int(),
1075
+ });
1076
+
1077
+ const TemplateReconcileResultSchema = z
1078
+ .object({
1079
+ agentId: z.string(),
1080
+ status: z.enum(["reconciled", "detached", "unknown_specialty"]),
1081
+ counts: z.object({
1082
+ env: TemplateReconcileCountsSchema,
1083
+ tool: TemplateReconcileCountsSchema,
1084
+ plugin: TemplateReconcileCountsSchema,
1085
+ cron: TemplateReconcileCountsSchema,
1086
+ }),
1087
+ systemCrons: z.object({
1088
+ created: z.number().int(),
1089
+ updated: z.number().int(),
1090
+ deleted: z.number().int(),
1091
+ }),
1092
+ conflicts: z.array(
1093
+ z.object({
1094
+ kind: z.enum(["env", "tool", "plugin", "cron"]),
1095
+ key: z.string(),
1096
+ reason: z.enum([
1097
+ "cron_name_conflict",
1098
+ "invalid_cron_schedule",
1099
+ "denylisted_env_key",
1100
+ ]),
1101
+ }),
1102
+ ),
1103
+ toolsEmptyGuarded: z.boolean(),
1104
+ })
1105
+ .openapi("TemplateReconcileResult");
1106
+
1107
+ const TemplateDetachResultSchema = z
1108
+ .object({ templateDetached: z.boolean() })
1109
+ .openapi("TemplateDetachResult");
1110
+
1111
+ const ResetTemplateBodySchema = z
1112
+ .object({
1113
+ kind: z.enum(["env", "tool", "plugin", "cron"]).optional(),
1114
+ key: z.string().min(1).optional(),
1115
+ })
1116
+ .refine((b) => (b.kind === undefined) === (b.key === undefined), {
1117
+ message: "kind and key must be given together",
1118
+ })
1119
+ .openapi("ResetTemplateBody");
1120
+
1121
+ const templateRouteResponses = {
1122
+ 200: {
1123
+ description: "Template reconcile summary",
1124
+ content: { "application/json": { schema: TemplateReconcileResultSchema } },
1125
+ },
1126
+ };
1127
+
1128
+ const reconcileTemplateRoute = createRoute({
1129
+ method: "post",
1130
+ path: "/agents/{id}/template/reconcile",
1131
+ summary: "Reconcile the agent against its template",
1132
+ description:
1133
+ "Applies the agent's merged template (specialty defaults, deployment/account layers) to its env, tools, plugins and crons in one transaction: adds missing items, updates template-sourced rows, removes orphans, and leaves custom rows and tombstones alone. A detached agent is left untouched (status `detached`). Called automatically on agent startup and when a template changes.",
1134
+ request: { params: AgentIdParamSchema },
1135
+ responses: templateRouteResponses,
1136
+ });
1137
+
1138
+ const detachTemplateRoute = createRoute({
1139
+ method: "post",
1140
+ path: "/agents/{id}/template/detach",
1141
+ summary: "Detach the agent from its template",
1142
+ description:
1143
+ "Stops applying template writes to the agent. Existing rows stay as they are. Admin or session member only.",
1144
+ request: { params: AgentIdParamSchema },
1145
+ responses: {
1146
+ 200: {
1147
+ description: "Agent detached",
1148
+ content: { "application/json": { schema: TemplateDetachResultSchema } },
1149
+ },
1150
+ },
1151
+ });
1152
+
1153
+ const reattachTemplateRoute = createRoute({
1154
+ method: "post",
1155
+ path: "/agents/{id}/template/reattach",
1156
+ summary: "Reattach the agent to its template",
1157
+ description:
1158
+ "Clears the detach flag and reconciles the agent against its template. Custom rows are kept. Admin or session member only.",
1159
+ request: { params: AgentIdParamSchema },
1160
+ responses: templateRouteResponses,
1161
+ });
1162
+
1163
+ const resetTemplateRoute = createRoute({
1164
+ method: "post",
1165
+ path: "/agents/{id}/template/reset",
1166
+ summary: "Reset the agent to its template",
1167
+ description:
1168
+ "Drops the agent's custom rows (overrides and tombstones) for every key its template defines, or only the one `kind`/`key` given, then reconciles so the template values return as template-sourced rows. 409 when the agent is detached. Admin or session member only.",
1169
+ request: {
1170
+ params: AgentIdParamSchema,
1171
+ body: {
1172
+ required: false,
1173
+ content: { "application/json": { schema: ResetTemplateBodySchema } },
1174
+ },
1175
+ },
1176
+ responses: templateRouteResponses,
1177
+ });
1178
+
1060
1179
  const reconcileCronsRoute = createRoute({
1061
1180
  method: "post",
1062
1181
  path: "/agents/{id}/crons/reconcile",
@@ -2518,6 +2637,15 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2518
2637
  specialtyRegistry,
2519
2638
  specialtyDefaults,
2520
2639
  anthropicFederationEnabled: deps.anthropicFederationEnabled,
2640
+ ...(deps.agentTemplateReconcileService
2641
+ ? {
2642
+ templateReconcile: {
2643
+ reconcile: deps.agentTemplateReconcileService.reconcile.bind(
2644
+ deps.agentTemplateReconcileService,
2645
+ ),
2646
+ },
2647
+ }
2648
+ : {}),
2521
2649
  },
2522
2650
  {
2523
2651
  name: body.name,
@@ -2535,6 +2663,8 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2535
2663
  restrictSlackToMembersRaw: body.restrictSlackToMembersRaw,
2536
2664
  claudeCodeOauthToken: body.claudeCodeOauthToken,
2537
2665
  anthropicApiKey: body.anthropicApiKey,
2666
+ ...(body.templateDetached ? { templateDetached: true } : {}),
2667
+ ...(body.env ? { env: body.env } : {}),
2538
2668
  },
2539
2669
  );
2540
2670
 
@@ -2610,6 +2740,59 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
2610
2740
  return c.json({ cron: serializeCron(cron) }, 201);
2611
2741
  });
2612
2742
 
2743
+ // ─── Agent template (ATP-2.2) ──────────────────────────────────────────────
2744
+
2745
+ const templateEngine = () => {
2746
+ if (!deps.agentTemplateReconcileService) {
2747
+ throw new ApiError(503, "agent templates are not configured");
2748
+ }
2749
+ return deps.agentTemplateReconcileService;
2750
+ };
2751
+
2752
+ // POST /agents/:id/template/reconcile — also what agent boot calls
2753
+ app.openapi(reconcileTemplateRoute, async (c) => {
2754
+ const { id: agentId } = c.req.valid("param");
2755
+ return c.json(await templateEngine().reconcile(agentId), 200);
2756
+ });
2757
+
2758
+ app.openapi(detachTemplateRoute, async (c) => {
2759
+ if (!isAdminOrSessionMember(c)) {
2760
+ throw new ForbiddenError(
2761
+ "Only admin bearers and session users can detach an agent from its template",
2762
+ );
2763
+ }
2764
+ const { id: agentId } = c.req.valid("param");
2765
+ await templateEngine().setDetached(agentId, true);
2766
+ return c.json({ templateDetached: true }, 200);
2767
+ });
2768
+
2769
+ app.openapi(reattachTemplateRoute, async (c) => {
2770
+ if (!isAdminOrSessionMember(c)) {
2771
+ throw new ForbiddenError(
2772
+ "Only admin bearers and session users can reattach an agent to its template",
2773
+ );
2774
+ }
2775
+ const { id: agentId } = c.req.valid("param");
2776
+ const engine = templateEngine();
2777
+ await engine.setDetached(agentId, false);
2778
+ return c.json(await engine.reconcile(agentId), 200);
2779
+ });
2780
+
2781
+ app.openapi(resetTemplateRoute, async (c) => {
2782
+ if (!isAdminOrSessionMember(c)) {
2783
+ throw new ForbiddenError(
2784
+ "Only admin bearers and session users can reset an agent to its template",
2785
+ );
2786
+ }
2787
+ const { id: agentId } = c.req.valid("param");
2788
+ const body = c.req.valid("json");
2789
+ const only =
2790
+ body?.kind !== undefined && body.key !== undefined
2791
+ ? { kind: body.kind, key: body.key }
2792
+ : undefined;
2793
+ return c.json(await templateEngine().reset(agentId, only), 200);
2794
+ });
2795
+
2613
2796
  // POST /agents/:id/crons/reconcile — static path must precede /:cronId routes
2614
2797
  app.openapi(reconcileCronsRoute, async (c) => {
2615
2798
  const { id: agentId } = c.req.valid("param");
@@ -25,6 +25,7 @@ import { AgentEnvService } from "./agent-envs.ts";
25
25
  import { AgentMemberService } from "./agent-members.ts";
26
26
  import { AgentPluginService } from "./agent-plugins.ts";
27
27
  import type { AgentProvisioner, ProvisionResult } from "./agent-provisioner.ts";
28
+ import { AgentTemplateReconcileService } from "./agent-template-reconcile.ts";
28
29
  import { AgentToolService } from "./agent-tools.ts";
29
30
  import type { CreateAgentDeps } from "./agents.ts";
30
31
  import { AgentService, createAgent } from "./agents.ts";
@@ -35,6 +36,8 @@ import type {
35
36
  } from "./specialty-types.ts";
36
37
  import { makeTokenCrypto } from "./token-crypto.ts";
37
38
 
39
+ const FIXTURE_DEFAULTS = () => ({ plugins: ["shipwright"] });
40
+
38
41
  const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
39
42
  const describeOrSkip = TEST_DB ? describe : describe.skip;
40
43
 
@@ -116,6 +119,7 @@ describeOrSkip("createAgent() — integration (real Postgres)", () => {
116
119
  let agentMemberService: AgentMemberService;
117
120
  let agentEnvService: AgentEnvService;
118
121
  let agentCronJobService: AgentCronJobService;
122
+ let templateReconcile: AgentTemplateReconcileService;
119
123
 
120
124
  beforeEach(async () => {
121
125
  prisma = makePrisma();
@@ -133,11 +137,20 @@ describeOrSkip("createAgent() — integration (real Postgres)", () => {
133
137
  fakeSpecialtyTypes(),
134
138
  );
135
139
 
140
+ templateReconcile = new AgentTemplateReconcileService(
141
+ prisma,
142
+ makeTokenCrypto(),
143
+ fakeSpecialtyTypes(),
144
+ FIXTURE_DEFAULTS,
145
+ );
146
+
136
147
  // Truncate between tests — this suite shares a DB with every other
137
148
  // admin/src/*.integration.test.ts file (see docs/test-readiness/
138
149
  // test-system.md's "real per-run DB with truncate-between-tests"
139
150
  // convention, needed because several services already open their own
140
151
  // interactive $transaction internally).
152
+ await prisma.agentTemplateItem.deleteMany();
153
+ await prisma.agentTemplate.deleteMany();
141
154
  await prisma.agentTool.deleteMany();
142
155
  await prisma.agentPlugin.deleteMany();
143
156
  await prisma.agentMember.deleteMany();
@@ -161,7 +174,8 @@ describeOrSkip("createAgent() — integration (real Postgres)", () => {
161
174
  agentCronJobService,
162
175
  provisioner: makeProvisioner(),
163
176
  specialtyRegistry: fakeSpecialtyTypes(),
164
- specialtyDefaults: () => ({ plugins: ["shipwright"] }),
177
+ specialtyDefaults: FIXTURE_DEFAULTS,
178
+ templateReconcile,
165
179
  ...overrides,
166
180
  };
167
181
  }
@@ -219,9 +233,10 @@ describeOrSkip("createAgent() — integration (real Postgres)", () => {
219
233
  },
220
234
  };
221
235
 
236
+ // A detached agent takes the direct built-in-defaults copy.
222
237
  const result = await createAgent(
223
238
  deps({ agentToolService: failingAgentToolService }),
224
- baseInput(),
239
+ baseInput({ templateDetached: true }),
225
240
  );
226
241
 
227
242
  expect(result).toEqual({ ok: false, errorCode: "seed_failed" });
@@ -239,7 +254,7 @@ describeOrSkip("createAgent() — integration (real Postgres)", () => {
239
254
 
240
255
  const result = await createAgent(
241
256
  deps({ agentPluginService: failingAgentPluginService }),
242
- baseInput(),
257
+ baseInput({ templateDetached: true }),
243
258
  );
244
259
 
245
260
  expect(result).toEqual({ ok: false, errorCode: "seed_failed" });
@@ -249,6 +264,28 @@ describeOrSkip("createAgent() — integration (real Postgres)", () => {
249
264
  expect(await prisma.agentTool.findMany()).toEqual([]);
250
265
  });
251
266
 
267
+ it("a failure of the template seeding step rolls back the agent and every row the template wrote", async () => {
268
+ const reconcileThenFail = {
269
+ reconcile: async (
270
+ agentId: string,
271
+ tx?: Parameters<AgentTemplateReconcileService["reconcile"]>[1],
272
+ ): Promise<never> => {
273
+ await templateReconcile.reconcile(agentId, tx);
274
+ throw new Error("boom: template seeding failed");
275
+ },
276
+ };
277
+
278
+ const result = await createAgent(
279
+ deps({ templateReconcile: reconcileThenFail }),
280
+ baseInput(),
281
+ );
282
+
283
+ expect(result).toEqual({ ok: false, errorCode: "seed_failed" });
284
+ expect(await prisma.agent.findMany()).toEqual([]);
285
+ expect(await prisma.agentTool.findMany()).toEqual([]);
286
+ expect(await prisma.agentPlugin.findMany()).toEqual([]);
287
+ });
288
+
252
289
  it("invalid repo format leaves ZERO Agent row behind, including manifest-seeded tools/plugins", async () => {
253
290
  const result = await createAgent(
254
291
  deps(),
@@ -323,6 +360,192 @@ describeOrSkip("createAgent() — integration (real Postgres)", () => {
323
360
  await prisma.agent.findUnique({ where: { id: result.agent.id } }),
324
361
  ).not.toBeNull();
325
362
  });
363
+ describe("agent template at provisioning (ATP-2.2)", () => {
364
+ async function seedTemplate(
365
+ accountId: string | null,
366
+ specialty: string | null,
367
+ items: {
368
+ kind: "env" | "tool" | "plugin" | "cron";
369
+ key: string;
370
+ payload: Record<string, unknown>;
371
+ }[],
372
+ ) {
373
+ const t = await prisma.agentTemplate.create({
374
+ data: { accountId, specialty },
375
+ });
376
+ await prisma.agentTemplateItem.createMany({
377
+ data: items.map((i) => ({
378
+ templateId: t.id,
379
+ kind: i.kind,
380
+ key: i.key,
381
+ payload: (i.kind === "env"
382
+ ? {
383
+ ...i.payload,
384
+ value: makeTokenCrypto().encrypt(String(i.payload.value)),
385
+ }
386
+ : i.payload) as never,
387
+ })),
388
+ });
389
+ }
390
+
391
+ const TEMPLATE_ITEMS = [
392
+ { kind: "env", key: "TEAM_FLAG", payload: { value: "on" } },
393
+ { kind: "env", key: "ANTHROPIC_MODEL", payload: { value: "tpl-model" } },
394
+ { kind: "tool", key: "Grep", payload: {} },
395
+ { kind: "plugin", key: "extra-plugin", payload: { version: null } },
396
+ {
397
+ kind: "cron",
398
+ key: "nightly",
399
+ payload: { schedule: "0 3 * * *", prompt: "/nightly" },
400
+ },
401
+ ] as const;
402
+
403
+ it("a new agent receives the merged template (env, tools, plugins, crons) as template-sourced rows, plus the built-in specialty defaults", async () => {
404
+ await seedTemplate(null, null, [...TEMPLATE_ITEMS]);
405
+
406
+ const result = await createAgent(deps(), baseInput());
407
+ if (!result.ok) throw new Error("expected success");
408
+ const agentId = result.agent.id;
409
+
410
+ const tools = await prisma.agentTool.findMany({ where: { agentId } });
411
+ expect(tools.map((t) => t.pattern).sort()).toEqual(
412
+ [...CODING_TYPE.tools, "Grep"].sort(),
413
+ );
414
+ expect(tools.every((t) => t.source === "template")).toBe(true);
415
+
416
+ const plugins = await prisma.agentPlugin.findMany({ where: { agentId } });
417
+ expect(plugins.map((p) => p.name).sort()).toEqual([
418
+ "agent-platform@app-vitals-agent",
419
+ "extra-plugin",
420
+ "shipwright",
421
+ ]);
422
+ expect(plugins.every((p) => p.source === "template")).toBe(true);
423
+
424
+ const crons = await prisma.agentCronJob.findMany({ where: { agentId } });
425
+ expect(crons.map((c) => [c.name, c.source])).toEqual([
426
+ ["nightly", "template"],
427
+ ]);
428
+
429
+ const envs = await prisma.agentEnv.findMany({ where: { agentId } });
430
+ const sourceOf = (key: string) => envs.find((e) => e.key === key)?.source;
431
+ expect(sourceOf("TEAM_FLAG")).toBe("template");
432
+ // The template value replaces the built-in ANTHROPIC_MODEL default.
433
+ expect(sourceOf("ANTHROPIC_MODEL")).toBe("template");
434
+ expect(
435
+ makeTokenCrypto().decrypt(
436
+ envs.find((e) => e.key === "ANTHROPIC_MODEL")?.value ?? "",
437
+ ),
438
+ ).toBe("tpl-model");
439
+ });
440
+
441
+ it("an explicit env value in the request wins per key, is written custom, and survives later reconciles", async () => {
442
+ await seedTemplate(null, null, [...TEMPLATE_ITEMS]);
443
+
444
+ const result = await createAgent(
445
+ deps(),
446
+ baseInput({ env: { TEAM_FLAG: "mine", EXTRA: "x" } }),
447
+ );
448
+ if (!result.ok) throw new Error("expected success");
449
+ const agentId = result.agent.id;
450
+
451
+ const read = async (key: string) => {
452
+ const row = await prisma.agentEnv.findUnique({
453
+ where: { agentId_key: { agentId, key } },
454
+ });
455
+ return (
456
+ row && {
457
+ value: makeTokenCrypto().decrypt(row.value),
458
+ source: row.source,
459
+ }
460
+ );
461
+ };
462
+ expect(await read("TEAM_FLAG")).toEqual({
463
+ value: "mine",
464
+ source: "custom",
465
+ });
466
+ expect(await read("EXTRA")).toEqual({ value: "x", source: "custom" });
467
+ // Keys the request did not set still come from the template.
468
+ expect(await read("ANTHROPIC_MODEL")).toEqual({
469
+ value: "tpl-model",
470
+ source: "template",
471
+ });
472
+
473
+ await templateReconcile.reconcile(agentId);
474
+ expect(await read("TEAM_FLAG")).toEqual({
475
+ value: "mine",
476
+ source: "custom",
477
+ });
478
+ });
479
+
480
+ it("an account-scoped template applies only to agents of that account", async () => {
481
+ const a = await prisma.account.create({
482
+ data: { name: "A", status: "active", maxAgents: 5 },
483
+ });
484
+ const b = await prisma.account.create({
485
+ data: { name: "B", status: "active", maxAgents: 5 },
486
+ });
487
+ await seedTemplate(a.id, null, [
488
+ { kind: "env", key: "ACCOUNT_FLAG", payload: { value: "a" } },
489
+ ]);
490
+
491
+ const inA = await createAgent(
492
+ deps(),
493
+ baseInput({ name: "in-a", accountId: a.id }),
494
+ );
495
+ const inB = await createAgent(
496
+ deps(),
497
+ baseInput({ name: "in-b", accountId: b.id }),
498
+ );
499
+ if (!inA.ok || !inB.ok) throw new Error("expected success");
500
+ const has = async (agentId: string) =>
501
+ (await prisma.agentEnv.count({
502
+ where: { agentId, key: "ACCOUNT_FLAG" },
503
+ })) === 1;
504
+ expect(await has(inA.agent.id)).toBe(true);
505
+ expect(await has(inB.agent.id)).toBe(false);
506
+ });
507
+
508
+ it("templateDetached:true yields only the built-in specialty defaults and ignores later template writes", async () => {
509
+ await seedTemplate(null, null, [...TEMPLATE_ITEMS]);
510
+
511
+ const result = await createAgent(
512
+ deps(),
513
+ baseInput({ templateDetached: true }),
514
+ );
515
+ if (!result.ok) throw new Error("expected success");
516
+ const agentId = result.agent.id;
517
+
518
+ expect(
519
+ (await prisma.agent.findUnique({ where: { id: agentId } }))
520
+ ?.templateDetached,
521
+ ).toBe(true);
522
+ const tools = await prisma.agentTool.findMany({ where: { agentId } });
523
+ expect(tools.map((t) => t.pattern).sort()).toEqual(
524
+ [...CODING_TYPE.tools].sort(),
525
+ );
526
+ const plugins = await prisma.agentPlugin.findMany({ where: { agentId } });
527
+ expect(plugins.map((p) => p.name).sort()).toEqual([
528
+ "agent-platform@app-vitals-agent",
529
+ "shipwright",
530
+ ]);
531
+ expect(await prisma.agentCronJob.count({ where: { agentId } })).toBe(0);
532
+ const envKeys = (
533
+ await prisma.agentEnv.findMany({ where: { agentId } })
534
+ ).map((e) => e.key);
535
+ expect(envKeys).toEqual(["ANTHROPIC_MODEL"]);
536
+ expect(
537
+ (await prisma.agentEnv.findMany({ where: { agentId } }))[0]?.source,
538
+ ).toBe("custom");
539
+
540
+ // A later reconcile does not touch it.
541
+ const again = await templateReconcile.reconcile(agentId);
542
+ expect(again.status).toBe("detached");
543
+ expect(await prisma.agentTool.count({ where: { agentId } })).toBe(
544
+ CODING_TYPE.tools.length,
545
+ );
546
+ });
547
+ });
548
+
326
549
  describe("account quota (SSP-4.1)", () => {
327
550
  async function makeAccount(
328
551
  overrides: { status?: string; maxAgents?: number } = {},