-
Notifications
You must be signed in to change notification settings - Fork 14.4k
Expand file tree
/
Copy pathbuilt-in-agents.test.ts
More file actions
1637 lines (1481 loc) · 61 KB
/
Copy pathbuilt-in-agents.test.ts
File metadata and controls
1637 lines (1481 loc) · 61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { randomUUID } from "node:crypto";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { and, eq, sql } from "drizzle-orm";
import {
activityLog,
agentConfigRevisions,
agents,
approvals,
budgetPolicies,
builtInManagedResources,
companies,
companyMemberships,
companySkillVersions,
companySkills,
createDb,
issueThreadInteractions,
issues,
principalPermissionGrants,
routines,
routineTriggers,
} from "@paperclipai/db";
import { readPaperclipSkillSyncPreference } from "@paperclipai/adapter-utils/server-utils";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
import { agentInstructionsService } from "../services/agent-instructions.ts";
import { agentService } from "../services/agents.ts";
import { approvalService } from "../services/approvals.ts";
import {
builtInAgentService,
deriveBuiltInAgentStatus,
listBuiltInAgentDefinitions,
readBuiltInTextWithFallback,
reconcileBuiltInAgentsOnStartup,
validateBuiltInAgentDefinitions,
} from "../services/built-in-agents.ts";
import { readBuiltInAgentMarker, withBuiltInAgentMarker } from "../services/built-in-agent-metadata.ts";
import { issueThreadInteractionService } from "../services/issue-thread-interactions.ts";
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
const BUILT_IN_MARKER_UNIQUE_INDEX = "agents_company_built_in_agent_key_unique_idx";
// Mirrors migration 0192. Used to drop/restore the partial unique index when a
// test needs to simulate legacy duplicates that predate the constraint.
const BUILT_IN_MARKER_UNIQUE_INDEX_DDL = `
CREATE UNIQUE INDEX IF NOT EXISTS "${BUILT_IN_MARKER_UNIQUE_INDEX}"
ON "agents" ("company_id", ((metadata -> 'paperclipBuiltInAgent' ->> 'key')))
WHERE (metadata -> 'paperclipBuiltInAgent' ->> 'key') IS NOT NULL
AND status <> 'terminated'
`;
function issuePrefix(id: string) {
return `T${id.replace(/-/g, "").slice(0, 6).toUpperCase()}`;
}
if (!embeddedPostgresSupport.supported) {
console.warn(
`Skipping embedded Postgres built-in agent tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`,
);
}
describe("built-in agent asset loading", () => {
it("uses the first readable candidate path", () => {
const dir = mkdtempSync(path.join(tmpdir(), "paperclip-built-in-agent-"));
try {
const first = path.join(dir, "missing.md");
const second = path.join(dir, "asset.md");
writeFileSync(second, "asset text", "utf8");
expect(readBuiltInTextWithFallback(`asset:${randomUUID()}`, [first, second], "fallback text")).toBe("asset text");
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("falls back instead of throwing when built-in agent files are missing", () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const label = `missing:${randomUUID()}`;
try {
expect(readBuiltInTextWithFallback(label, [path.join(tmpdir(), label, "AGENTS.md")], "fallback text")).toBe(
"fallback text",
);
expect(warn).toHaveBeenCalledWith(expect.stringContaining(`Built-in agent asset ${label} was not readable`));
} finally {
warn.mockRestore();
}
});
it("warns about non-missing read errors before falling back", () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const dir = mkdtempSync(path.join(tmpdir(), "paperclip-built-in-agent-"));
const label = "unreadable:" + randomUUID();
try {
const directoryPath = path.join(dir, "asset.md");
mkdirSync(directoryPath);
expect(readBuiltInTextWithFallback(label, [directoryPath], "fallback text")).toBe("fallback text");
expect(warn).toHaveBeenCalledWith(expect.stringContaining("read error on " + directoryPath + ":"));
expect(warn).toHaveBeenCalledWith(
expect.stringContaining("Built-in agent asset " + label + " was not readable"),
);
} finally {
warn.mockRestore();
rmSync(dir, { recursive: true, force: true });
}
});
});
describeEmbeddedPostgres("built-in agents", () => {
let db!: ReturnType<typeof createDb>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
beforeAll(async () => {
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-built-in-agents-");
db = createDb(tempDb.connectionString);
}, 20_000);
afterEach(async () => {
await db.delete(routineTriggers);
await db.delete(routines);
await db.delete(issueThreadInteractions);
await db.delete(issues);
await db.delete(builtInManagedResources);
await db.delete(companySkillVersions);
await db.delete(companySkills);
await db.delete(principalPermissionGrants);
await db.delete(companyMemberships);
await db.delete(agentConfigRevisions);
await db.delete(activityLog);
await db.delete(approvals);
await db.delete(agents);
await db.delete(budgetPolicies);
await db.delete(companies);
// Some tests drop the built-in marker unique index to simulate legacy
// (pre-migration 0192) duplicates; restore it now that all rows are gone.
await db.execute(sql.raw(BUILT_IN_MARKER_UNIQUE_INDEX_DDL));
});
afterAll(async () => {
await tempDb?.cleanup();
});
async function permissionKeysForAgent(agentId: string) {
const grants = await db
.select()
.from(principalPermissionGrants)
.where(eq(principalPermissionGrants.principalId, agentId));
return grants.map((grant) => grant.permissionKey).sort();
}
async function seedCompany(options: { requireApproval?: boolean } = {}) {
const companyId = randomUUID();
await db.insert(companies).values({
id: companyId,
name: "Paperclip",
issuePrefix: issuePrefix(companyId),
defaultResponsibleUserId: "responsible-user",
requireBoardApprovalForNewAgents: options.requireApproval ?? true,
});
return companyId;
}
it("validates the static registry and rejects invalid definitions", () => {
const definitions = listBuiltInAgentDefinitions();
expect(definitions.map((definition) => definition.key).sort()).toEqual(["briefs", "learning", "reflection-coach", "summarizer"]);
const summarizer = definitions.find((definition) => definition.key === "summarizer");
expect(summarizer).toMatchObject({
defaultAdapterType: "claude_local",
defaultAdapterConfig: { model: "claude-haiku-4-5" },
});
expect(summarizer?.defaultRuntimeConfig).toBeUndefined();
expect(() => validateBuiltInAgentDefinitions([
{
key: "briefs",
displayName: "Briefs Agent",
featureKeys: ["briefs"],
shortPurpose: "One",
defaultInstructions: "Do work",
defaultRole: "general",
},
{
key: "briefs",
displayName: "Duplicate",
featureKeys: ["duplicate"],
shortPurpose: "Two",
defaultInstructions: "Do work",
defaultRole: "general",
},
])).toThrow("Duplicate built-in agent key");
expect(() => validateBuiltInAgentDefinitions([
{
key: "Bad Key",
displayName: "Bad",
featureKeys: ["bad"],
shortPurpose: "Bad",
defaultInstructions: "Bad",
defaultRole: "general",
},
])).toThrow("Invalid built-in agent key");
expect(() => validateBuiltInAgentDefinitions([
{
key: "bad-default",
displayName: "Bad default",
featureKeys: ["bad-default"],
shortPurpose: "Bad default adapter",
defaultInstructions: "Do work",
defaultRole: "general",
allowedAdapterTypes: ["codex_local"],
defaultAdapterType: "claude_local",
},
])).toThrow("defaultAdapterType must be allowed");
});
it("lazily provisions one agent per company/key and updates the same row on setup", async () => {
const companyId = await seedCompany();
const svc = builtInAgentService(db);
const created = await svc.ensure(companyId, "briefs");
expect(created.status).toBe("needs_setup");
expect(created.agentId).toBeTruthy();
expect(created.agent).toMatchObject({
companyId,
name: "Briefs Agent",
adapterConfig: {},
status: "idle",
});
expect(readBuiltInAgentMarker(created.agent?.metadata)).toEqual({
key: "briefs",
featureKeys: ["briefs"],
});
const configured = await svc.ensure(companyId, "briefs", {
adapterType: "codex_local",
adapterConfig: { model: "gpt-5.4" },
});
expect(configured.status).toBe("ready");
expect(configured.agentId).toBe(created.agentId);
expect(configured.agent).toMatchObject({
adapterType: "codex_local",
adapterConfig: { model: "gpt-5.4" },
});
const reconciled = await svc.ensure(companyId, "briefs");
expect(reconciled.status).toBe("ready");
expect(reconciled.agent).toMatchObject({
adapterType: "codex_local",
adapterConfig: { model: "gpt-5.4" },
});
const rows = await db.select().from(agents).where(eq(agents.companyId, companyId));
expect(rows).toHaveLength(1);
});
it("routes policy-gated built-in provisioning through a pending hire approval", async () => {
const companyId = await seedCompany();
const builtIns = builtInAgentService(db);
const result = await builtIns.provision(companyId, "briefs", {
adapterType: "process",
adapterConfig: { command: "echo safe" },
budgetMonthlyCents: 5000,
}, { requestedByUserId: "board-user" });
expect(result.state).toMatchObject({
status: "pending_approval",
agent: {
companyId,
name: "Briefs Agent",
status: "pending_approval",
adapterType: "process",
adapterConfig: { command: "echo safe" },
budgetMonthlyCents: 5000,
},
});
expect(result.approval).toMatchObject({
companyId,
type: "hire_agent",
status: "pending",
requestedByUserId: "board-user",
requestedByAgentId: null,
payload: {
name: "Briefs Agent",
role: "general",
adapterType: "process",
adapterConfig: { command: "echo safe" },
budgetMonthlyCents: 5000,
agentId: result.state.agentId,
sourceBuiltInAgentKey: "briefs",
featureKeys: ["briefs"],
},
});
const rowsBeforeApproval = await db.select().from(agents).where(eq(agents.companyId, companyId));
expect(rowsBeforeApproval).toHaveLength(1);
expect(rowsBeforeApproval[0]).toMatchObject({ status: "pending_approval" });
await expect(builtIns.requireBuiltInAgent(companyId, "briefs")).rejects.toMatchObject({
status: 412,
details: { code: "built_in_agent_not_configured", status: "pending_approval" },
});
await expect(agentService(db).update(result.state.agentId!, {
adapterType: "process",
adapterConfig: { command: "echo tampered" },
})).rejects.toMatchObject({
status: 409,
details: {
code: "pending_approval_agent_config_frozen",
agentId: result.state.agentId,
fields: ["adapterConfig"],
},
});
await expect(builtIns.provision(companyId, "briefs", {
budgetMonthlyCents: 7500,
})).rejects.toMatchObject({
status: 409,
details: {
code: "built_in_agent_pending_approval",
key: "briefs",
agentId: result.state.agentId,
},
});
await db
.update(agents)
.set({
adapterType: "process",
adapterConfig: { command: "echo tampered" },
})
.where(eq(agents.id, result.state.agentId!));
await approvalService(db).approve(result.approval!.id, "board-user", "Approved built-in agent");
await expect(builtIns.get(companyId, "briefs")).resolves.toMatchObject({
status: "ready",
agentId: result.state.agentId,
agent: { status: "idle", adapterType: "process", adapterConfig: { command: "echo safe" }, budgetMonthlyCents: 5000 },
});
});
it("blocks policy-gated built-in reconfiguration instead of applying adapter overrides immediately", async () => {
const companyId = await seedCompany();
const builtIns = builtInAgentService(db);
const ready = await builtIns.ensure(companyId, "briefs", {
adapterType: "codex_local",
adapterConfig: { model: "gpt-5.4" },
});
await expect(builtIns.provision(companyId, "briefs", {
adapterType: "process",
adapterConfig: { command: "echo bypass" },
})).rejects.toMatchObject({
status: 409,
details: {
code: "built_in_agent_reconfiguration_requires_approval",
key: "briefs",
agentId: ready.agentId,
},
});
await expect(builtIns.get(companyId, "briefs")).resolves.toMatchObject({
status: "ready",
agentId: ready.agentId,
agent: { adapterType: "codex_local", adapterConfig: { model: "gpt-5.4" } },
});
});
it("completes first-time setup of a needs_setup built-in without a fresh board approval", async () => {
const companyId = await seedCompany({ requireApproval: true });
const builtIns = builtInAgentService(db);
// A hired-but-unconfigured built-in row: exists (its hire was already
// sanctioned) but its adapter config is still empty → `needs_setup`.
const seeded = await builtIns.ensure(companyId, "briefs");
expect(seeded.status).toBe("needs_setup");
// Configuring the adapter for the first time must apply directly instead of
// throwing "adapter changes require board approval".
const result = await builtIns.provision(companyId, "briefs", {
adapterType: "codex_local",
adapterConfig: { model: "gpt-5.4" },
budgetMonthlyCents: 2500,
}, { requestedByUserId: "board-user" });
expect(result.approval).toBeNull();
expect(result.state).toMatchObject({
status: "ready",
agentId: seeded.agentId,
agent: {
status: "idle",
adapterType: "codex_local",
adapterConfig: { model: "gpt-5.4" },
budgetMonthlyCents: 2500,
},
});
const rows = await db.select().from(agents).where(eq(agents.companyId, companyId));
expect(rows).toHaveLength(1);
const noApprovals = await db.select().from(approvals).where(eq(approvals.companyId, companyId));
expect(noApprovals).toHaveLength(0);
});
it("rejects adapter types outside the built-in definition allowlist", async () => {
const companyId = await seedCompany();
await expect(builtInAgentService(db).ensure(companyId, "briefs", {
adapterType: "http",
adapterConfig: { url: "https://example.test/webhook" },
})).rejects.toMatchObject({
status: 422,
details: {
code: "built_in_agent_adapter_not_allowed",
key: "briefs",
allowedAdapterTypes: ["codex_local", "claude_local", "gemini_local", "opencode_local", "process"],
},
});
});
it("rejects unknown built-in adapter models before saving setup", async () => {
const companyId = await seedCompany();
await expect(builtInAgentService(db).ensure(companyId, "summarizer", {
adapterType: "claude_local",
adapterConfig: { model: "claude-haiku-4-6" },
})).rejects.toMatchObject({
status: 422,
details: {
code: "built_in_agent_model_unknown",
key: "summarizer",
adapterType: "claude_local",
model: "claude-haiku-4-6",
},
});
const rows = await db.select().from(agents).where(eq(agents.companyId, companyId));
expect(rows).toHaveLength(0);
});
it("recovers an orphaned marked row instead of creating a duplicate", async () => {
const companyId = await seedCompany();
const orphanId = randomUUID();
await db.insert(agents).values({
id: orphanId,
companyId,
name: "Old Briefs",
role: "general",
status: "idle",
adapterType: "codex_local",
adapterConfig: { model: "gpt-5.4" },
runtimeConfig: {},
permissions: {},
metadata: withBuiltInAgentMarker({ source: "orphan" }, { key: "briefs", featureKeys: ["briefs"] }),
});
const state = await builtInAgentService(db).ensure(companyId, "briefs");
expect(state.status).toBe("ready");
expect(state.agentId).toBe(orphanId);
const rows = await db.select().from(agents).where(eq(agents.companyId, companyId));
expect(rows).toHaveLength(1);
});
it("derives not_provisioned, needs_setup, ready, and paused states", async () => {
const companyId = await seedCompany();
const builtIns = builtInAgentService(db);
await expect(builtIns.get(companyId, "learning")).resolves.toMatchObject({ status: "not_provisioned" });
const needsSetup = await builtIns.ensure(companyId, "learning");
expect(needsSetup.status).toBe("needs_setup");
expect(deriveBuiltInAgentStatus(needsSetup.agent)).toBe("needs_setup");
const ready = await builtIns.ensure(companyId, "learning", {
adapterType: "claude_local",
adapterConfig: { model: "claude-sonnet-4-5" },
});
expect(ready.status).toBe("ready");
await agentService(db).pause(ready.agentId!, "manual");
await expect(builtIns.get(companyId, "learning")).resolves.toMatchObject({
status: "paused",
agentId: ready.agentId,
pauseReason: "manual",
});
});
it("requires configured built-ins with typed precondition failures and paused warnings", async () => {
const companyId = await seedCompany();
const builtIns = builtInAgentService(db);
await expect(builtIns.requireBuiltInAgent(companyId, "briefs")).rejects.toMatchObject({
status: 412,
details: {
code: "built_in_agent_not_configured",
key: "briefs",
status: "not_provisioned",
agentId: null,
},
});
const needsSetup = await builtIns.ensure(companyId, "briefs");
await expect(builtIns.requireBuiltInAgent(companyId, "briefs")).rejects.toMatchObject({
status: 412,
details: {
code: "built_in_agent_not_configured",
key: "briefs",
status: "needs_setup",
agentId: needsSetup.agentId,
},
});
const ready = await builtIns.ensure(companyId, "briefs", {
adapterType: "codex_local",
adapterConfig: { model: "gpt-5.4" },
});
await expect(builtIns.requireBuiltInAgent(companyId, "briefs")).resolves.toMatchObject({
agent: { id: ready.agentId },
warning: null,
});
await agentService(db).pause(ready.agentId!, "maintenance");
await expect(builtIns.requireBuiltInAgent(companyId, "briefs")).resolves.toMatchObject({
agent: { id: ready.agentId },
warning: {
code: "built_in_agent_paused",
key: "briefs",
agentId: ready.agentId,
pauseReason: "maintenance",
},
});
});
it("resets marked agents back to registry display defaults without replacing adapter setup", async () => {
const companyId = await seedCompany();
const builtIns = builtInAgentService(db);
const ready = await builtIns.ensure(companyId, "briefs", {
adapterType: "codex_local",
adapterConfig: { model: "gpt-5.4" },
});
await agentService(db).update(ready.agentId!, {
name: "Custom Briefs",
role: "engineer",
title: "Custom",
capabilities: "Custom purpose",
});
const reset = await builtIns.reset(companyId, "briefs");
expect(reset).toMatchObject({
status: "ready",
agentId: ready.agentId,
agent: {
name: "Briefs Agent",
role: "general",
title: null,
capabilities: "Prepares concise operational briefs for the board and agent company.",
adapterType: "codex_local",
adapterConfig: { model: "gpt-5.4" },
},
});
});
it("reconciles an enabled Reflection Coach bundle with skill sync and a disabled routine", async () => {
const companyId = await seedCompany({ requireApproval: false });
const root = await agentService(db).create(companyId, {
name: "CEO",
role: "ceo",
status: "idle",
adapterType: "codex_local",
adapterConfig: { model: "gpt-5.4", apiKey: "do-not-copy" },
runtimeConfig: {},
permissions: {},
});
// The Reflection Coach is opt-in (not auto-created). Enabling it on demand
// materializes its managed bundle in a single pass.
const enabled = await builtInAgentService(db).ensure(companyId, "reflection-coach");
expect(enabled.agent?.adapterConfig).toMatchObject({
instructionsBundleMode: "managed",
instructionsEntryFile: "AGENTS.md",
});
expect(enabled.agent?.adapterConfig).not.toMatchObject({ model: "gpt-5.4", apiKey: "do-not-copy" });
// Startup reconcile keeps the enabled bundle tracking stock and re-grants
// the root/company default permissions.
const result = await reconcileBuiltInAgentsOnStartup(db);
expect(result.autoEnsured).toBeGreaterThanOrEqual(1);
expect(result.defaultGrantsEnsured).toBeGreaterThanOrEqual(4);
const rootGrantKeys = await permissionKeysForAgent(root.id);
expect(rootGrantKeys).toEqual(expect.arrayContaining(["agents:configure", "skills:create"]));
expect(rootGrantKeys).not.toContain("agents:suggest-changes");
expect(rootGrantKeys).not.toContain("skills:suggest-changes");
const state = await builtInAgentService(db).get(companyId, "reflection-coach");
expect(state).toMatchObject({
status: "paused",
agent: {
companyId,
name: "Reflection Coach",
role: "general",
title: "Reflection Coach",
icon: "eye",
adapterType: "codex_local",
permissions: {
canCreateAgents: false,
canCreateSkills: false,
},
},
});
expect(state.resources.map((resource) => [resource.resourceKind, resource.stockStatus])).toEqual([
["instructions", "stock_current"],
["skill", "stock_current"],
["routine", "stock_current"],
]);
expect(state.resources.find((resource) => resource.resourceKind === "routine")).toMatchObject({
resourceId: expect.any(String),
scheduleEnabled: false,
});
const agentRows = await db.select().from(agents).where(eq(agents.companyId, companyId));
expect(agentRows.filter((row) => readBuiltInAgentMarker(row.metadata)?.key === "reflection-coach")).toHaveLength(1);
const [skill] = await db
.select()
.from(companySkills)
.where(eq(companySkills.key, "paperclipai/bundled/paperclip-operations/reflection-coach"));
expect(skill).toMatchObject({
key: "paperclipai/bundled/paperclip-operations/reflection-coach",
slug: "reflection-coach",
});
expect(readPaperclipSkillSyncPreference(state.agent!.adapterConfig as Record<string, unknown>).desiredSkills).toContain(
"paperclipai/bundled/paperclip-operations/reflection-coach",
);
const [routine] = await db.select().from(routines).where(eq(routines.companyId, companyId));
expect(routine).toMatchObject({
title: "Review recent agent trajectories for coaching proposals",
status: "paused",
assigneeAgentId: state.agentId,
});
const [trigger] = await db.select().from(routineTriggers).where(eq(routineTriggers.routineId, routine!.id));
expect(trigger).toMatchObject({
kind: "schedule",
enabled: false,
cronExpression: "0 9 * * 1",
timezone: "UTC",
});
const coachGrantKeys = await permissionKeysForAgent(state.agentId!);
expect(coachGrantKeys).toEqual(expect.arrayContaining(["agents:suggest-changes", "skills:suggest-changes"]));
expect(coachGrantKeys).not.toContain("agents:configure");
expect(coachGrantKeys).not.toContain("skills:create");
});
it("recreates missing managed resource bindings idempotently during concurrent reconcile", async () => {
const companyId = await seedCompany({ requireApproval: false });
await agentService(db).create(companyId, {
name: "CEO",
role: "ceo",
status: "idle",
adapterType: "codex_local",
adapterConfig: { model: "gpt-5.4" },
runtimeConfig: {},
permissions: {},
});
const builtIns = builtInAgentService(db);
await builtIns.ensure(companyId, "reflection-coach");
await db.delete(builtInManagedResources).where(eq(builtInManagedResources.companyId, companyId));
const states = await Promise.all([
builtIns.ensure(companyId, "reflection-coach"),
builtIns.ensure(companyId, "reflection-coach"),
]);
expect(states).toHaveLength(2);
for (const state of states) {
expect(state.resources.map((resource) => [resource.resourceKind, resource.stockStatus])).toEqual([
["instructions", "stock_current"],
["skill", "stock_current"],
["routine", "stock_current"],
]);
}
const bindings = await db
.select()
.from(builtInManagedResources)
.where(eq(builtInManagedResources.companyId, companyId));
expect(bindings).toHaveLength(3);
expect(new Set(bindings.map((binding) =>
`${binding.bundleKey}:${binding.resourceKind}:${binding.resourceKey}`
)).size).toBe(3);
});
it("preserves new-agent approval gates during on-demand Reflection Coach provisioning", async () => {
const companyId = await seedCompany({ requireApproval: true });
const root = await agentService(db).create(companyId, {
name: "CEO",
role: "ceo",
status: "idle",
adapterType: "codex_local",
adapterConfig: { model: "gpt-5.4" },
runtimeConfig: {},
permissions: {},
});
const mutationPolicy = {
requiresDisplayedDiff: true,
requiresAcceptedTaskInteraction: true,
applyInSeparateFollowUpRun: true,
};
// The Reflection Coach is opt-in, so it's enabled on demand. With board
// approval required, provisioning it must leave a pending agent + a
// hire_agent approval rather than an active agent.
const provisioned = await builtInAgentService(db).provision(companyId, "reflection-coach");
expect(provisioned.approval).not.toBeNull();
const state = await builtInAgentService(db).get(companyId, "reflection-coach");
expect(state).toMatchObject({
status: "pending_approval",
agent: {
companyId,
name: "Reflection Coach",
status: "pending_approval",
reportsTo: root.id,
budgetMonthlyCents: 0,
permissions: {
builtInMutationPolicy: mutationPolicy,
},
},
});
expect(state.resources.map((resource) => resource.stockStatus)).toEqual(["missing", "missing", "missing"]);
const allApprovals = await db.select().from(approvals).where(eq(approvals.companyId, companyId));
const approval = allApprovals.find(
(row) => (row.payload as { agentId?: string } | null)?.agentId === state.agentId,
)!;
expect(approval).toMatchObject({
type: "hire_agent",
status: "pending",
payload: {
agentId: state.agentId,
sourceBuiltInAgentKey: "reflection-coach",
featureKeys: ["reflection-coach"],
reportsTo: root.id,
permissions: expect.objectContaining({
builtInMutationPolicy: mutationPolicy,
}),
},
});
const pendingReconcile = await reconcileBuiltInAgentsOnStartup(db);
expect(pendingReconcile.pendingApprovals).toBe(1);
const stillPending = await builtInAgentService(db).get(companyId, "reflection-coach");
expect(stillPending).toMatchObject({
status: "pending_approval",
agent: {
adapterConfig: {},
reportsTo: root.id,
status: "pending_approval",
},
});
expect(stillPending.resources.map((resource) => resource.stockStatus)).toEqual([
"missing",
"missing",
"missing",
]);
await approvalService(db).approve(approval.id, "board-user", "Approved Reflection Coach");
const approvedState = await builtInAgentService(db).get(companyId, "reflection-coach");
expect(approvedState).toMatchObject({
agent: {
reportsTo: root.id,
permissions: {
builtInMutationPolicy: mutationPolicy,
},
},
});
expect(approvedState.resources.map((resource) => resource.stockStatus)).toEqual([
"stock_current",
"stock_current",
"stock_current",
]);
await reconcileBuiltInAgentsOnStartup(db);
const agentRows = await db.select().from(agents).where(eq(agents.companyId, companyId));
expect(agentRows.filter((row) => readBuiltInAgentMarker(row.metadata)?.key === "reflection-coach")).toHaveLength(1);
const approvalRows = await db.select().from(approvals).where(eq(approvals.companyId, companyId));
expect(approvalRows).toHaveLength(1);
});
it("preserves Reflection Coach instruction drift on reconcile and restores it on reset", async () => {
const companyId = await seedCompany();
const builtIns = builtInAgentService(db);
const created = await builtIns.ensure(companyId, "reflection-coach");
const instructions = agentInstructionsService();
await instructions.writeFile(created.agent!, "AGENTS.md", "# Custom Reflection Coach\n\nOperator edit.\n");
const reconciled = await builtIns.ensure(companyId, "reflection-coach");
const drift = reconciled.resources.find((resource) => resource.resourceKind === "instructions");
expect(drift).toMatchObject({
stockStatus: "operator_modified",
updateAvailable: true,
resetAvailable: true,
changedFiles: ["AGENTS.md"],
});
await expect(instructions.readFile(reconciled.agent!, "AGENTS.md")).resolves.toMatchObject({
content: "# Custom Reflection Coach\n\nOperator edit.\n",
});
const reset = await builtIns.reset(companyId, "reflection-coach");
expect(reset.resources.find((resource) => resource.resourceKind === "instructions")).toMatchObject({
stockStatus: "stock_current",
resetAvailable: false,
});
const resetFile = await instructions.readFile(reset.agent!, "AGENTS.md");
expect(resetFile.content).toContain("Reflection Coach");
expect(resetFile.content).not.toContain("Operator edit.");
});
it("blocks deleting a built-in agent", async () => {
const companyId = await seedCompany();
const state = await builtInAgentService(db).ensure(companyId, "briefs");
await expect(agentService(db).remove(state.agentId!)).rejects.toMatchObject({
status: 409,
details: {
code: "built_in_agent_undeletable",
key: "briefs",
},
});
});
it("prevents direct marker add, remove, or mutation", async () => {
const companyId = await seedCompany();
const builtIn = await builtInAgentService(db).ensure(companyId, "briefs");
const normal = await agentService(db).create(companyId, {
name: "Normal",
role: "engineer",
status: "idle",
adapterType: "codex_local",
adapterConfig: { model: "gpt-5.4" },
runtimeConfig: {},
permissions: {},
});
await expect(agentService(db).create(companyId, {
name: "Spoof",
role: "engineer",
status: "idle",
adapterType: "codex_local",
adapterConfig: { model: "gpt-5.4" },
runtimeConfig: {},
permissions: {},
metadata: withBuiltInAgentMarker({}, { key: "briefs", featureKeys: ["briefs"] }),
})).rejects.toMatchObject({ status: 409, details: { code: "built_in_agent_marker_readonly" } });
await expect(agentService(db).update(normal.id, {
metadata: withBuiltInAgentMarker({}, { key: "briefs", featureKeys: ["briefs"] }),
})).rejects.toMatchObject({ status: 409, details: { code: "built_in_agent_marker_readonly" } });
await expect(agentService(db).update(builtIn.agentId!, {
metadata: { other: "metadata" },
})).rejects.toMatchObject({ status: 409, details: { code: "built_in_agent_marker_readonly" } });
await expect(agentService(db).update(builtIn.agentId!, {
metadata: withBuiltInAgentMarker({}, { key: "learning", featureKeys: ["learning"] }),
})).rejects.toMatchObject({ status: 409, details: { code: "built_in_agent_marker_readonly" } });
await expect(agentService(db).update(builtIn.agentId!, {
metadata: withBuiltInAgentMarker({ note: "allowed" }, { key: "briefs", featureKeys: ["briefs"] }),
})).resolves.toMatchObject({
id: builtIn.agentId,
metadata: {
note: "allowed",
paperclipBuiltInAgent: { key: "briefs", featureKeys: ["briefs"] },
},
});
});
it("repairs display/default drift for marked rows during startup reconciliation", async () => {
const companyId = await seedCompany();
const agentId = randomUUID();
await db.insert(agents).values({
id: agentId,
companyId,
name: "Old Name",
role: "engineer",
title: "Old title",
capabilities: "Old purpose",
status: "idle",
adapterType: "codex_local",
adapterConfig: { model: "gpt-5.4" },
runtimeConfig: {},
permissions: {},
metadata: withBuiltInAgentMarker({}, { key: "briefs", featureKeys: ["old-briefs"] }),
});
const result = await reconcileBuiltInAgentsOnStartup(db);
expect(result).toMatchObject({ unknown: 0, duplicates: 0 });
expect(result.scanned).toBeGreaterThanOrEqual(1);
expect(result.reconciled).toBeGreaterThanOrEqual(1);
const [row] = await db.select().from(agents).where(eq(agents.id, agentId));
expect(row).toMatchObject({
name: "Briefs Agent",
role: "general",
title: null,
capabilities: "Prepares concise operational briefs for the board and agent company.",
});
expect(readBuiltInAgentMarker(row?.metadata)).toEqual({ key: "briefs", featureKeys: ["briefs"] });
});
// Reproduce a company that already carries duplicate marked rows from before
// migration 0192 by dropping the unique index, inserting two active rows, and
// pairing a pending hire_agent approval with the newer one.
async function seedLegacyDuplicateBriefs(companyId: string) {
await db.execute(sql.raw(`DROP INDEX IF EXISTS "${BUILT_IN_MARKER_UNIQUE_INDEX}"`));
const olderId = randomUUID();
const newerId = randomUUID();
await db.insert(agents).values([
{
id: olderId,
companyId,
name: "Briefs One",
role: "general",
status: "idle",
adapterType: "codex_local",
adapterConfig: { model: "gpt-5.4" },
runtimeConfig: {},
permissions: {},
createdAt: new Date("2026-07-18T00:00:00.000Z"),
metadata: withBuiltInAgentMarker({}, { key: "briefs", featureKeys: ["briefs"] }),
},
{
id: newerId,
companyId,
name: "Briefs Two",
role: "general",
status: "pending_approval",
adapterType: "codex_local",
adapterConfig: { model: "gpt-5.4" },
runtimeConfig: {},
permissions: {},
createdAt: new Date("2026-07-18T00:00:00.025Z"),
metadata: withBuiltInAgentMarker({}, { key: "briefs", featureKeys: ["briefs"] }),
},
]);
const approval = await approvalService(db).create(companyId, {
type: "hire_agent",
requestedByAgentId: null,
requestedByUserId: null,
status: "pending",
payload: { agentId: newerId, sourceBuiltInAgentKey: "briefs", featureKeys: ["briefs"] },
decisionNote: null,
decidedByUserId: null,
decidedAt: null,
updatedAt: new Date(),
});
return { olderId, newerId, approvalId: approval!.id };
}
it("self-heals duplicate active instances, keeping the oldest and cancelling the newer's approval", async () => {
const companyId = await seedCompany();
const { olderId, newerId, approvalId } = await seedLegacyDuplicateBriefs(companyId);
// A plain read resolves the duplicate rather than throwing.
const state = await builtInAgentService(db).get(companyId, "briefs");
expect(state.agentId).toBe(olderId);
const rows = await db.select().from(agents).where(eq(agents.companyId, companyId));
const byId = new Map(rows.map((row) => [row.id, row]));
expect(byId.get(olderId)?.status).toBe("idle");
expect(byId.get(newerId)?.status).toBe("terminated");
expect(
rows.filter((row) => row.status !== "terminated" && readBuiltInAgentMarker(row.metadata)?.key === "briefs"),
).toHaveLength(1);
const [approval] = await db.select().from(approvals).where(eq(approvals.id, approvalId));
expect(approval?.status).toBe("cancelled");
});
it("makes concurrent provisioning lose cleanly instead of creating duplicates", async () => {
const companyId = await seedCompany({ requireApproval: false });
const svc = builtInAgentService(db);
const [first, second] = await Promise.all([
svc.ensure(companyId, "briefs"),
svc.ensure(companyId, "briefs"),
]);
expect(first.agentId).toBeTruthy();
expect(second.agentId).toBe(first.agentId);