@app-vitals/agent-admin 1.51.0 → 1.52.1

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.
@@ -145,3 +145,17 @@ test("a malformed spec redirects with an error and adds nothing", async ({
145
145
  await page.waitForURL(/\?error=/);
146
146
  await expect(table(page).locator("tbody tr")).toHaveCount(before);
147
147
  });
148
+
149
+ test("settings content grows with the viewport width", async ({
150
+ page,
151
+ context,
152
+ }) => {
153
+ const contentWidth = async () =>
154
+ (await page.locator(".settings-content").boundingBox())?.width ?? 0;
155
+ await page.setViewportSize({ width: 1200, height: 900 });
156
+ await loadAgentPage(page, context);
157
+ const narrow = await contentWidth();
158
+ await page.setViewportSize({ width: 1800, height: 900 });
159
+ const wide = await contentWidth();
160
+ expect(wide).toBeGreaterThan(narrow);
161
+ });
@@ -0,0 +1,277 @@
1
+ /**
2
+ * admin/e2e/settings-nav.e2e.ts
3
+ * Admin UI — settings shell navigation E2E (SGL-2.4)
4
+ *
5
+ * Real browser journeys through the settings layout (sidebar + active pill):
6
+ * 1. Agent detail: click through General, Automation, Configuration, Access
7
+ * and Extensions; the URL and the aria-current pill follow each click.
8
+ * 2. One write action per section; each POST redirects back to the section
9
+ * that owns the form.
10
+ * 3. /admin/settings redirects to the first nav item; the Account and
11
+ * Platform items are reachable from the sidebar.
12
+ * 4. Mobile (375px): the sidebar collapses into a <details> disclosure.
13
+ *
14
+ * Spawns admin/e2e/test-server.ts with ADMIN_E2E_SETTINGS=1 (own port) and
15
+ * mints session cookies directly; no DB or OAuth.
16
+ */
17
+
18
+ import { type ChildProcess, spawn } from "node:child_process";
19
+ import { dirname, resolve } from "node:path";
20
+ import { fileURLToPath } from "node:url";
21
+ import { type BrowserContext, expect, type Page, test } from "@playwright/test";
22
+ import { sign } from "hono/jwt";
23
+
24
+ const PORT = 3498;
25
+ const BASE_URL = `http://localhost:${PORT}`;
26
+ const SESSION_SECRET = "e2e-admin-test-secret-32chars!!!";
27
+ const SESSION_COOKIE = "admin_session";
28
+ const AGENT_ID = "agent-e2e-1";
29
+ const AGENT_BASE = `/admin/agents/${AGENT_ID}`;
30
+
31
+ const __dirname = dirname(fileURLToPath(import.meta.url));
32
+
33
+ let serverProcess: ChildProcess | null = null;
34
+
35
+ async function waitForServer(url: string, maxWaitMs: number): Promise<void> {
36
+ const start = Date.now();
37
+ while (Date.now() - start < maxWaitMs) {
38
+ try {
39
+ const res = await fetch(url);
40
+ if (res.status < 500) return;
41
+ } catch {
42
+ // Not ready yet
43
+ }
44
+ await new Promise((r) => setTimeout(r, 300));
45
+ }
46
+ throw new Error(`Server at ${url} did not start within ${maxWaitMs}ms`);
47
+ }
48
+
49
+ test.beforeAll(async () => {
50
+ serverProcess = spawn("bun", ["run", resolve(__dirname, "test-server.ts")], {
51
+ env: {
52
+ ...process.env,
53
+ ADMIN_E2E_PORT: String(PORT),
54
+ ADMIN_E2E_SESSION_SECRET: SESSION_SECRET,
55
+ ADMIN_E2E_SETTINGS: "1",
56
+ },
57
+ stdio: "pipe",
58
+ cwd: resolve(__dirname, "../.."),
59
+ });
60
+ serverProcess.stderr?.on("data", (d: Buffer) => {
61
+ if (d.toString().trim())
62
+ console.error("[admin-e2e-settings-server]", d.toString().trim());
63
+ });
64
+ await waitForServer(`${BASE_URL}/health`, 15_000);
65
+ });
66
+
67
+ test.afterAll(() => {
68
+ serverProcess?.kill("SIGTERM");
69
+ serverProcess = null;
70
+ });
71
+
72
+ async function signIn(context: BrowserContext): Promise<void> {
73
+ const nowSec = Math.floor(Date.now() / 1000);
74
+ const token = await sign(
75
+ {
76
+ userId: "google-sub-e2e",
77
+ email: "admin@example.com",
78
+ isAdmin: true,
79
+ iat: nowSec,
80
+ exp: nowSec + 3600,
81
+ },
82
+ SESSION_SECRET,
83
+ "HS256",
84
+ );
85
+ await context.addCookies([
86
+ {
87
+ name: SESSION_COOKIE,
88
+ value: token,
89
+ domain: "localhost",
90
+ path: "/",
91
+ httpOnly: true,
92
+ sameSite: "Lax",
93
+ },
94
+ ]);
95
+ }
96
+
97
+ /** The desktop sidebar's links (the mobile <details> duplicates them). */
98
+ const sidebar = (page: Page) => page.locator("nav.settings-sidebar");
99
+ const activePill = (page: Page) =>
100
+ sidebar(page).locator('a[aria-current="page"]');
101
+
102
+ const SECTIONS = [
103
+ { label: "General", path: AGENT_BASE },
104
+ { label: "Automation", path: `${AGENT_BASE}/automation` },
105
+ { label: "Configuration", path: `${AGENT_BASE}/configuration` },
106
+ { label: "Access", path: `${AGENT_BASE}/access` },
107
+ { label: "Extensions", path: `${AGENT_BASE}/extensions` },
108
+ ];
109
+
110
+ test.describe("agent detail sections", () => {
111
+ test("sidebar navigation moves the URL and the active pill through all five sections", async ({
112
+ page,
113
+ context,
114
+ }) => {
115
+ await signIn(context);
116
+ await page.goto(`${BASE_URL}${AGENT_BASE}`);
117
+ await expect(sidebar(page).locator("a.settings-nav-link")).toHaveText(
118
+ SECTIONS.map((s) => s.label),
119
+ );
120
+ await expect(activePill(page)).toHaveText("General");
121
+
122
+ for (const s of SECTIONS.slice(1)) {
123
+ await sidebar(page).getByRole("link", { name: s.label }).click();
124
+ await expect(page).toHaveURL(`${BASE_URL}${s.path}`);
125
+ await expect(activePill(page)).toHaveCount(1);
126
+ await expect(activePill(page)).toHaveText(s.label);
127
+ await expect(page.locator("h1")).toContainText("Test Agent");
128
+ }
129
+
130
+ // And back to General via the bare agent path.
131
+ await sidebar(page).getByRole("link", { name: "General" }).click();
132
+ await expect(page).toHaveURL(`${BASE_URL}${AGENT_BASE}`);
133
+ await expect(activePill(page)).toHaveText("General");
134
+ });
135
+
136
+ test("a write action in each section lands back on that section", async ({
137
+ page,
138
+ context,
139
+ }) => {
140
+ await signIn(context);
141
+
142
+ // General: Sync Manifest with a malformed token redirects back with an error.
143
+ await page.goto(`${BASE_URL}${AGENT_BASE}`);
144
+ await page.locator("summary", { hasText: "Sync Manifest" }).click();
145
+ await page.locator('input[name="xoxpToken"]').fill("not-a-slack-token");
146
+ await page.getByRole("button", { name: "Confirm Sync" }).click();
147
+ await page.waitForURL(new RegExp(`${AGENT_BASE}\\?error=`));
148
+ await expect(activePill(page)).toHaveText("General");
149
+
150
+ // Automation: add a cron.
151
+ await sidebar(page).getByRole("link", { name: "Automation" }).click();
152
+ await page.locator('input[name="schedule"]').first().fill("5 4 * * *");
153
+ await page
154
+ .locator('form[action$="/crons"] input[name="prompt"]')
155
+ .fill("nightly check");
156
+ await page.getByRole("button", { name: "Add Cron" }).click();
157
+ await page.waitForURL(`${BASE_URL}${AGENT_BASE}/automation`);
158
+ await expect(activePill(page)).toHaveText("Automation");
159
+
160
+ // Configuration: set an env var.
161
+ await sidebar(page).getByRole("link", { name: "Configuration" }).click();
162
+ await page
163
+ .locator('form[action$="/envs"] input[name="key"]')
164
+ .fill("E2E_KEY");
165
+ await page
166
+ .locator('form[action$="/envs"] input[name="value"]')
167
+ .fill("e2e-value");
168
+ await page.locator('form[action$="/envs"] button[type="submit"]').click();
169
+ await page.waitForURL(`${BASE_URL}${AGENT_BASE}/configuration`);
170
+ await expect(activePill(page)).toHaveText("Configuration");
171
+
172
+ // Access: add a review-author allowlist entry.
173
+ await sidebar(page).getByRole("link", { name: "Access" }).click();
174
+ await page
175
+ .locator(
176
+ 'form[action$="/review-author-allowlist/add"] input[name="login"]',
177
+ )
178
+ .fill("octocat");
179
+ await page
180
+ .locator('form[action$="/review-author-allowlist/add"] button')
181
+ .click();
182
+ await page.waitForURL(`${BASE_URL}${AGENT_BASE}/access`);
183
+ await expect(activePill(page)).toHaveText("Access");
184
+
185
+ // Extensions: add a plugin.
186
+ await sidebar(page).getByRole("link", { name: "Extensions" }).click();
187
+ await page
188
+ .locator("#add-plugin-form input[name='spec']")
189
+ .fill("nav-e2e@seeded-remote");
190
+ await page.locator("#add-plugin-form").getByRole("button").click();
191
+ await page.waitForURL(`${BASE_URL}${AGENT_BASE}/extensions`);
192
+ await expect(activePill(page)).toHaveText("Extensions");
193
+ await expect(page.locator("body")).toContainText("nav-e2e@seeded-remote");
194
+ });
195
+ });
196
+
197
+ test.describe("/admin/settings", () => {
198
+ test("redirects to the first item and moves between Account and Platform items", async ({
199
+ page,
200
+ context,
201
+ }) => {
202
+ await signIn(context);
203
+ await page.goto(`${BASE_URL}/admin/settings`);
204
+ await expect(page).toHaveURL(`${BASE_URL}/admin/account`);
205
+ await expect(activePill(page)).toHaveText("Account");
206
+ await expect(page.locator("h1")).toHaveText("E2E Account");
207
+
208
+ const groups = sidebar(page).locator(".settings-nav-label");
209
+ await expect(groups).toHaveText(["Account", "Platform"]);
210
+
211
+ const items = [
212
+ { label: "GitHub Enterprise", path: "/admin/settings/github-enterprise" },
213
+ { label: "Templates", path: "/admin/settings/templates" },
214
+ { label: "Accounts", path: "/admin/accounts" },
215
+ { label: "Account", path: "/admin/account" },
216
+ ];
217
+ for (const item of items) {
218
+ await sidebar(page)
219
+ .getByRole("link", { name: item.label, exact: true })
220
+ .click();
221
+ await expect(page).toHaveURL(`${BASE_URL}${item.path}`);
222
+ await expect(activePill(page)).toHaveCount(1);
223
+ await expect(activePill(page)).toHaveText(item.label);
224
+ }
225
+ });
226
+
227
+ test("mobile (375px): sidebar collapses into a disclosure that navigates", async ({
228
+ page,
229
+ context,
230
+ }) => {
231
+ await signIn(context);
232
+ await page.setViewportSize({ width: 375, height: 812 });
233
+ await page.goto(`${BASE_URL}/admin/account`);
234
+
235
+ const disclosure = page.locator("details.settings-nav-mobile");
236
+ await expect(sidebar(page)).toBeHidden();
237
+ await expect(disclosure).toBeVisible();
238
+ await expect(disclosure.locator("summary")).toHaveText("Account");
239
+ await expect(disclosure).not.toHaveAttribute("open", "");
240
+ await expect(
241
+ disclosure.getByRole("link", { name: "Templates" }),
242
+ ).toBeHidden();
243
+
244
+ await disclosure.locator("summary").click();
245
+ await expect(disclosure).toHaveAttribute("open", "");
246
+ await expect(disclosure.locator('a[aria-current="page"]')).toHaveText(
247
+ "Account",
248
+ );
249
+
250
+ await disclosure.getByRole("link", { name: "Templates" }).click();
251
+ await expect(page).toHaveURL(`${BASE_URL}/admin/settings/templates`);
252
+ // The new page renders collapsed again, labelled with the active item.
253
+ await expect(
254
+ page.locator("details.settings-nav-mobile summary"),
255
+ ).toHaveText("Templates");
256
+ await expect(
257
+ page.locator("details.settings-nav-mobile"),
258
+ ).not.toHaveAttribute("open", "");
259
+ });
260
+
261
+ test("mobile (375px): agent sections are reachable from the disclosure", async ({
262
+ page,
263
+ context,
264
+ }) => {
265
+ await signIn(context);
266
+ await page.setViewportSize({ width: 375, height: 812 });
267
+ await page.goto(`${BASE_URL}${AGENT_BASE}`);
268
+ const disclosure = page.locator("details.settings-nav-mobile");
269
+ await expect(disclosure.locator("summary")).toHaveText("General");
270
+ await disclosure.locator("summary").click();
271
+ await disclosure.getByRole("link", { name: "Access" }).click();
272
+ await expect(page).toHaveURL(`${BASE_URL}${AGENT_BASE}/access`);
273
+ await expect(
274
+ page.locator("details.settings-nav-mobile summary"),
275
+ ).toHaveText("Access");
276
+ });
277
+ });
@@ -9,6 +9,7 @@
9
9
  * Usage:
10
10
  * ADMIN_E2E_PORT=3490 bun run admin/e2e/test-server.ts
11
11
  * ADMIN_E2E_AGENTS_MODE=1 ADMIN_E2E_PORT=3490 bun run admin/e2e/test-server.ts
12
+ * ADMIN_E2E_SETTINGS=1 ADMIN_E2E_PORT=3498 bun run admin/e2e/test-server.ts
12
13
  *
13
14
  * The server exposes:
14
15
  * GET /health → 200 OK
@@ -241,6 +242,87 @@ function buildMockChatClient(): ChatClient {
241
242
  // are exercising the real UI, not a silently-degraded fallback.
242
243
  const CHAT_CLIENT_ABSENT = process.env.ADMIN_E2E_CHAT_CLIENT_ABSENT === "1";
243
244
 
245
+ // ─── Settings-shell fixtures (SGL-2.4) ───────────────────────────────────────
246
+ // When ADMIN_E2E_SETTINGS=1 the server wires the optional services that turn on
247
+ // the /admin/settings sidebar: GitHub Enterprise, Templates (Platform) and
248
+ // Account/Accounts (self-serve). Off by default so other suites are unchanged.
249
+ const SETTINGS_MODE = process.env.ADMIN_E2E_SETTINGS === "1";
250
+
251
+ const MOCK_ACCOUNT = {
252
+ id: "acct-e2e-1",
253
+ name: "E2E Account",
254
+ status: "active",
255
+ maxAgents: 5,
256
+ plan: null,
257
+ trialExpiresAt: null,
258
+ trialExpiryWarnedAt: null,
259
+ createdAt: new Date("2024-01-01"),
260
+ updatedAt: new Date("2024-01-01"),
261
+ };
262
+
263
+ function buildSettingsDeps(): Partial<AdminUIDeps> {
264
+ const members = [
265
+ {
266
+ id: "am-e2e-1",
267
+ accountId: MOCK_ACCOUNT.id,
268
+ email: "admin@example.com",
269
+ role: "owner",
270
+ createdAt: new Date("2024-01-01"),
271
+ },
272
+ ];
273
+ const counts = { ...MOCK_ACCOUNT, agentCount: 1, memberCount: 1 };
274
+ return {
275
+ selfServe: {
276
+ enabled: true,
277
+ defaultMaxAgents: 5,
278
+ contactEmail: "contact@example.com",
279
+ },
280
+ templateService: {
281
+ list: async () => [],
282
+ replace: async () => {
283
+ throw new Error("not used in e2e tests");
284
+ },
285
+ putItem: async () => {
286
+ throw new Error("not used in e2e tests");
287
+ },
288
+ deleteItem: async () => {
289
+ throw new Error("not used in e2e tests");
290
+ },
291
+ delete: async () => {
292
+ throw new Error("not used in e2e tests");
293
+ },
294
+ } as unknown as AdminUIDeps["templateService"],
295
+ githubEnterpriseApi: async (path: string) =>
296
+ path === "/github-enterprise/apps"
297
+ ? Response.json({ configured: false, installer: null, lookup: null })
298
+ : Response.json({}, { status: 404 }),
299
+ accountServices: {
300
+ accounts: {
301
+ getByMemberEmail: async () => MOCK_ACCOUNT,
302
+ update: async () => MOCK_ACCOUNT,
303
+ countAgents: async () => 1,
304
+ listWithCounts: async () => [counts],
305
+ getWithCounts: async () => counts,
306
+ listAgents: async () => [],
307
+ },
308
+ members: {
309
+ listByAccount: async () => members,
310
+ getByEmail: async () => members[0],
311
+ add: async () => members[0],
312
+ remove: async () => {},
313
+ promote: async () => {},
314
+ demote: async () => {},
315
+ },
316
+ invites: {
317
+ create: async () => ({}),
318
+ listPending: async () => [],
319
+ revoke: async () => {},
320
+ },
321
+ lifecycle: { update: async () => MOCK_ACCOUNT },
322
+ } as unknown as AdminUIDeps["accountServices"],
323
+ };
324
+ }
325
+
244
326
  // ─── Mock deps factory ────────────────────────────────────────────────────────
245
327
 
246
328
  function buildMockDeps(chatClient: ChatClient | undefined): AdminUIDeps {
@@ -485,6 +567,7 @@ function buildMockDeps(chatClient: ChatClient | undefined): AdminUIDeps {
485
567
  },
486
568
  appBaseUrl: `http://localhost:${ADMIN_E2E_PORT}`,
487
569
  chatClient,
570
+ ...(SETTINGS_MODE ? buildSettingsDeps() : {}),
488
571
  };
489
572
  }
490
573
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@app-vitals/agent-admin",
3
- "version": "1.51.0",
3
+ "version": "1.52.1",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/app-vitals/agent.git",
@@ -42,7 +42,7 @@
42
42
  },
43
43
  "dependencies": {
44
44
  "@anthropic-ai/sdk": "0.135.0",
45
- "@app-vitals/agent-lib": "1.51.0",
45
+ "@app-vitals/agent-lib": "1.52.1",
46
46
  "@hono/zod-openapi": "^1.0.0",
47
47
  "@prisma/adapter-pg": "^7.10.0",
48
48
  "@prisma/client": "^7.10.0",
@@ -65,7 +65,7 @@ export function renderSettingsLayout(
65
65
  ?.label ?? opts.title;
66
66
 
67
67
  return `${renderAdminToolbar(opts.userName, opts.toolbarPath ?? opts.active)}
68
- <div class="vos-page">
68
+ <div class="vos-page vos-page-wide vos-page-settings">
69
69
  <div class="settings-layout">
70
70
  <nav class="settings-sidebar" aria-label="Settings">${sectionsHtml}</nav>
71
71
  <details class="settings-nav-mobile"><summary>${escapeHtml(activeLabel)}</summary>${sectionsHtml}</details>
@@ -60,6 +60,7 @@ describe("renderSettingsLayout", () => {
60
60
  expect(html).toContain("Profile</h1>");
61
61
  expect(html).toContain("<p>BODY</p>");
62
62
  expect(html).toContain('class="vos-page');
63
+ expect(html).toContain('class="vos-page vos-page-wide vos-page-settings"');
63
64
  expect(html).toContain("vos-toolbar");
64
65
  });
65
66
 
@@ -615,6 +615,12 @@ export function baseStyles(): string {
615
615
  font-weight: 600;
616
616
  }
617
617
  .settings-content { flex: 1 1 auto; min-width: 0; }
618
+ .settings-content .form-input,
619
+ .settings-content input[type="text"],
620
+ .settings-content input[type="email"],
621
+ .settings-content input[type="password"],
622
+ .settings-content input[type="number"],
623
+ .settings-content input[type="search"] { max-width: 640px; }
618
624
  .settings-content h1 {
619
625
  font-size: 24px;
620
626
  font-weight: 600;
@@ -122,6 +122,14 @@ describe("baseStyles — SGL-1.1 settings layout", () => {
122
122
  }
123
123
  });
124
124
 
125
+ test("full-width modifier and input cap", () => {
126
+ expect(css).toMatch(
127
+ /\.vos-page-wide\s*{\s*max-width:\s*none;\s*width:\s*100%;/,
128
+ );
129
+ expect(block).toMatch(/\.settings-content \.form-input[^}]*max-width: 640px/);
130
+ expect(block).toContain('.settings-content input[type="search"]');
131
+ });
132
+
125
133
  test("mobile media block references the settings classes", () => {
126
134
  const media = block.slice(
127
135
  block.indexOf(`@media (max-width: ${BREAKPOINT_MOBILE_MAX}px)`),
@@ -577,6 +577,95 @@ describeOrSkip("AgentCronJobService (integration)", () => {
577
577
  expect(systemJobs.length).toBe(FIXTURE_CRONS.length);
578
578
  });
579
579
 
580
+ // Coding -> specialist shape: an orphan parent whose children are also
581
+ // orphans. parentCron is onDelete: Cascade, so a per-row delete of a child
582
+ // after its parent was deleted used to throw.
583
+ async function seedOrphanLoop(agentId: string): Promise<string[]> {
584
+ const parent = await prisma.agentCronJob.create({
585
+ data: {
586
+ agentId,
587
+ name: "shipwright-loop",
588
+ system: true,
589
+ schedule: "*/30 * * * *",
590
+ prompt: "/shipwright:loop",
591
+ },
592
+ });
593
+ const ids = [parent.id];
594
+ for (const name of ["shipwright-dev-task", "shipwright-review"]) {
595
+ const child = await prisma.agentCronJob.create({
596
+ data: {
597
+ agentId,
598
+ name,
599
+ system: true,
600
+ schedule: "0 * * * *",
601
+ prompt: `/${name}`,
602
+ parentCronId: parent.id,
603
+ },
604
+ });
605
+ ids.push(child.id);
606
+ }
607
+ return ids;
608
+ }
609
+
610
+ it("reconcileSystemCrons() deletes an orphan parent together with its orphan children without throwing", async () => {
611
+ const agentId = await createAgent(prisma);
612
+ const orphanIds = await seedOrphanLoop(agentId);
613
+
614
+ const result = await service.reconcileSystemCrons(agentId);
615
+
616
+ expect(result.deleted).toBe(orphanIds.length);
617
+ expect(result.created).toBe(FIXTURE_CRONS.length);
618
+ expect(
619
+ await prisma.agentCronJob.count({ where: { id: { in: orphanIds } } }),
620
+ ).toBe(0);
621
+ const names = (await service.list(agentId)).map((j) => j.name).sort();
622
+ expect(names).toEqual(FIXTURE_CRONS.map((c) => c.name).sort());
623
+ });
624
+
625
+ it("reconcileSystemCrons() detaches a surviving cron whose parentCronId points at an orphan", async () => {
626
+ const agentId = await createAgent(prisma);
627
+ const orphanIds = await seedOrphanLoop(agentId);
628
+ const orphanParentId = orphanIds[0] as string;
629
+ const userCron = await prisma.agentCronJob.create({
630
+ data: {
631
+ agentId,
632
+ name: "my-cron",
633
+ system: false,
634
+ schedule: "0 3 * * *",
635
+ prompt: "/mine",
636
+ parentCronId: orphanParentId,
637
+ },
638
+ });
639
+ // A system cron that is still a default, also linked to the orphan.
640
+ const defaultCron = await prisma.agentCronJob.create({
641
+ data: {
642
+ agentId,
643
+ name: "fixture-standalone",
644
+ system: true,
645
+ schedule: "0 7 * * 1",
646
+ prompt: "/fixture:standalone\n/fixture:follow-up",
647
+ parentCronId: orphanParentId,
648
+ },
649
+ });
650
+
651
+ const result = await service.reconcileSystemCrons(agentId);
652
+
653
+ expect(result.deleted).toBe(orphanIds.length);
654
+ expect(
655
+ await prisma.agentCronJob.count({ where: { id: { in: orphanIds } } }),
656
+ ).toBe(0);
657
+ const userAfter = await prisma.agentCronJob.findUnique({
658
+ where: { id: userCron.id },
659
+ });
660
+ expect(userAfter).not.toBeNull();
661
+ expect(userAfter?.parentCronId).toBeNull();
662
+ const defaultAfter = await prisma.agentCronJob.findUnique({
663
+ where: { id: defaultCron.id },
664
+ });
665
+ expect(defaultAfter).not.toBeNull();
666
+ expect(defaultAfter?.parentCronId).toBeNull();
667
+ });
668
+
580
669
  it("reconcileSystemCrons() for an unknown specialty changes nothing (no fallback)", async () => {
581
670
  const agentId = await createAgent(prisma, "Renamed Agent", "renamed-type");
582
671
 
@@ -666,11 +666,27 @@ export async function applySystemCronDefaults(
666
666
  }
667
667
 
668
668
  // Orphan pass: delete any system cron whose name is not in the defaults.
669
- for (const cron of existingSystemCrons) {
670
- if (!cron.name || !systemCronNames.has(cron.name)) {
671
- await tx.agentCronJob.delete({ where: { id: cron.id } });
672
- deleted++;
673
- }
669
+ // parentCron is onDelete: Cascade, so deleting an orphan parent would
670
+ // cascade to its children — and a per-row delete of an already-cascaded
671
+ // child throws. Detach survivors first, then delete the orphan set in one
672
+ // statement.
673
+ const orphanIds = existingSystemCrons
674
+ .filter((cron) => !cron.name || !systemCronNames.has(cron.name))
675
+ .map((cron) => cron.id);
676
+
677
+ if (orphanIds.length > 0) {
678
+ await tx.agentCronJob.updateMany({
679
+ where: {
680
+ agentId,
681
+ parentCronId: { in: orphanIds },
682
+ id: { notIn: orphanIds },
683
+ },
684
+ data: { parentCronId: null },
685
+ });
686
+ const result = await tx.agentCronJob.deleteMany({
687
+ where: { agentId, id: { in: orphanIds } },
688
+ });
689
+ deleted = result.count;
674
690
  }
675
691
 
676
692
  return { created, updated, deleted };
@@ -97,7 +97,7 @@ type FakeCronRow = AgentCronJob;
97
97
  * In-memory prisma double covering only what reconcileSystemCrons() touches:
98
98
  * agent.findUnique (specialty resolution),
99
99
  * agentCronJob.findMany, and a $transaction exposing
100
- * agentCronJob.{create,update,delete}.
100
+ * agentCronJob.{create,update,delete,updateMany,deleteMany}.
101
101
  */
102
102
  function makeFakePrisma(opts: {
103
103
  specialty: string;
@@ -191,6 +191,48 @@ function makeFakePrisma(opts: {
191
191
  rows.delete(where.id);
192
192
  return row;
193
193
  },
194
+ async updateMany({
195
+ where,
196
+ data,
197
+ }: {
198
+ where: {
199
+ agentId?: string;
200
+ parentCronId?: { in: string[] };
201
+ id?: { notIn: string[] };
202
+ };
203
+ data: Partial<FakeCronRow>;
204
+ }): Promise<{ count: number }> {
205
+ let count = 0;
206
+ for (const [id, row] of rows) {
207
+ if (where.agentId !== undefined && row.agentId !== where.agentId)
208
+ continue;
209
+ if (
210
+ where.parentCronId &&
211
+ !where.parentCronId.in.includes(row.parentCronId ?? "")
212
+ )
213
+ continue;
214
+ if (where.id && where.id.notIn.includes(id)) continue;
215
+ rows.set(id, { ...row, ...data } as FakeCronRow);
216
+ count++;
217
+ }
218
+ return { count };
219
+ },
220
+ async deleteMany({
221
+ where,
222
+ }: {
223
+ where: { agentId?: string; id: { in: string[] } };
224
+ }): Promise<{ count: number }> {
225
+ let count = 0;
226
+ for (const id of where.id.in) {
227
+ const row = rows.get(id);
228
+ if (!row) continue;
229
+ if (where.agentId !== undefined && row.agentId !== where.agentId)
230
+ continue;
231
+ rows.delete(id);
232
+ count++;
233
+ }
234
+ return { count };
235
+ },
194
236
  };
195
237
 
196
238
  const agent = {
@@ -624,6 +624,47 @@ describeOrSkip("AgentTemplateReconcileService (integration)", () => {
624
624
  expect(crons).toEqual([]); // fx-loop was FIXTURE's system cron
625
625
  });
626
626
 
627
+ it("deletes an orphan system-cron parent with its children and detaches survivors", async () => {
628
+ const agentId = await agent();
629
+ const parent = await prisma.agentCronJob.create({
630
+ data: {
631
+ agentId,
632
+ name: "shipwright-loop",
633
+ system: true,
634
+ schedule: "*/30 * * * *",
635
+ prompt: "/shipwright:loop",
636
+ },
637
+ });
638
+ for (const name of ["shipwright-dev-task", "shipwright-review"]) {
639
+ await prisma.agentCronJob.create({
640
+ data: {
641
+ agentId,
642
+ name,
643
+ system: true,
644
+ schedule: "0 * * * *",
645
+ prompt: `/${name}`,
646
+ parentCronId: parent.id,
647
+ },
648
+ });
649
+ }
650
+ const userCron = await prisma.agentCronJob.create({
651
+ data: {
652
+ agentId,
653
+ name: "my-cron",
654
+ system: false,
655
+ schedule: "0 3 * * *",
656
+ prompt: "/mine",
657
+ parentCronId: parent.id,
658
+ },
659
+ });
660
+
661
+ await service.reconcile(agentId);
662
+
663
+ const rows = await prisma.agentCronJob.findMany({ where: { agentId } });
664
+ expect(rows.map((r) => r.name).sort()).toEqual(["fx-loop", "my-cron"]);
665
+ expect(rows.find((r) => r.id === userCron.id)?.parentCronId).toBeNull();
666
+ });
667
+
627
668
  it("a template cron named like a specialty system cron overrides it in place", async () => {
628
669
  const agentId = await agent();
629
670
  await service.reconcile(agentId);
@@ -158,6 +158,31 @@ describeOrSkip("PATCH /agents/:id specialty (integration)", () => {
158
158
  },
159
159
  });
160
160
  }
161
+ // Loop crons: a parent and children linked via parentCronId. Deleting the
162
+ // parent cascades to the children, which the orphan pass must tolerate.
163
+ const loop = await prisma.agentCronJob.create({
164
+ data: {
165
+ agentId: agent.id,
166
+ name: "shipwright-loop",
167
+ system: true,
168
+ schedule: "*/30 * * * *",
169
+ prompt: "/shipwright:loop",
170
+ enabled: false,
171
+ },
172
+ });
173
+ for (const name of ["shipwright-loop-dev", "shipwright-loop-review"]) {
174
+ await prisma.agentCronJob.create({
175
+ data: {
176
+ agentId: agent.id,
177
+ name,
178
+ system: true,
179
+ schedule: "0 * * * *",
180
+ prompt: `/${name}`,
181
+ enabled: false,
182
+ parentCronId: loop.id,
183
+ },
184
+ });
185
+ }
161
186
  const userCron = await prisma.agentCronJob.create({
162
187
  data: {
163
188
  agentId: agent.id,
@@ -191,7 +216,9 @@ describeOrSkip("PATCH /agents/:id specialty (integration)", () => {
191
216
  });
192
217
 
193
218
  expect(res.status).toBe(200);
194
- expect((await res.json()).specialty).toBe("specialist");
219
+ const body = await res.json();
220
+ expect(body.specialty).toBe("specialist");
221
+ expect(body.warning).toBeUndefined();
195
222
  const row = await prisma.agent.findUniqueOrThrow({
196
223
  where: { id: agent.id },
197
224
  });