-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathloop.test.ts
More file actions
875 lines (754 loc) · 26.1 KB
/
Copy pathloop.test.ts
File metadata and controls
875 lines (754 loc) · 26.1 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
/**
* Agent Loop Tests
*
* Deterministic tests for the agent loop using mock clients.
*/
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { runAgentLoop } from "../agent/loop.js";
import { Orchestrator } from "../orchestration/orchestrator.js";
import {
MockInferenceClient,
MockConwayClient,
MockSocialClient,
createTestDb,
createTestIdentity,
createTestConfig,
toolCallResponse,
noToolResponse,
} from "./mocks.js";
import type { AutomatonDatabase, AgentTurn, AgentState } from "../types.js";
describe("Agent Loop", () => {
let db: AutomatonDatabase;
let conway: MockConwayClient;
let identity: ReturnType<typeof createTestIdentity>;
let config: ReturnType<typeof createTestConfig>;
beforeEach(() => {
db = createTestDb();
conway = new MockConwayClient();
identity = createTestIdentity();
config = createTestConfig();
});
afterEach(() => {
vi.restoreAllMocks();
db.close();
});
it("exec tool fails closed when policy context is absent", async () => {
const inference = new MockInferenceClient([
toolCallResponse([
{ name: "exec", arguments: { command: "echo hello" } },
]),
noToolResponse("Done."),
]);
const turns: AgentTurn[] = [];
await runAgentLoop({
identity,
config,
db,
conway,
inference,
onTurnComplete: (turn) => turns.push(turn),
});
// First turn should have the exec tool call
expect(turns.length).toBeGreaterThanOrEqual(1);
const execTurn = turns.find((t) =>
t.toolCalls.some((tc) => tc.name === "exec"),
);
expect(execTurn).toBeDefined();
expect(execTurn!.toolCalls[0].name).toBe("exec");
expect(execTurn!.toolCalls[0].error).toContain("POLICY_CONTEXT_REQUIRED");
// Verify conway.exec was called
expect(conway.execCalls.length).toBe(0);
});
it("forbidden patterns fail closed before execution when policy context is absent", async () => {
const inference = new MockInferenceClient([
toolCallResponse([
{ name: "exec", arguments: { command: "rm -rf ~/.automaton" } },
]),
noToolResponse("OK."),
]);
const turns: AgentTurn[] = [];
await runAgentLoop({
identity,
config,
db,
conway,
inference,
onTurnComplete: (turn) => turns.push(turn),
});
// Missing policy context takes precedence over inline command filtering.
const execTurn = turns.find((t) =>
t.toolCalls.some((tc) => tc.name === "exec"),
);
expect(execTurn).toBeDefined();
const execCall = execTurn!.toolCalls.find((tc) => tc.name === "exec");
expect(execCall!.error).toContain("POLICY_CONTEXT_REQUIRED");
expect(execCall!.result).toBe("");
// conway.exec should NOT have been called
expect(conway.execCalls.length).toBe(0);
});
it("low credits forces low-compute mode", async () => {
conway.creditsCents = 50; // Below $1 threshold -> critical
const inference = new MockInferenceClient([
noToolResponse("Low on credits."),
]);
await runAgentLoop({
identity,
config,
db,
conway,
inference,
});
expect(inference.lowComputeMode).toBe(true);
});
it("sleep tool transitions state", async () => {
const inference = new MockInferenceClient([
toolCallResponse([
{ name: "sleep", arguments: { duration_seconds: 60, reason: "test" } },
]),
]);
await runAgentLoop({
identity,
config,
db,
conway,
inference,
});
expect(db.getAgentState()).toBe("sleeping");
expect(db.getKV("sleep_until")).toBeDefined();
});
it("idle auto-sleep on no tool calls", async () => {
const inference = new MockInferenceClient([
noToolResponse("Nothing to do."),
]);
await runAgentLoop({
identity,
config,
db,
conway,
inference,
});
expect(db.getAgentState()).toBe("sleeping");
});
it("inbox messages cause pendingInput injection", async () => {
// Insert an inbox message before running the loop
db.insertInboxMessage({
id: "test-msg-1",
from: "0xsender",
to: "0xrecipient",
content: "Hello from another agent!",
signedAt: new Date().toISOString(),
createdAt: new Date().toISOString(),
});
const inference = new MockInferenceClient([
// First response: wakeup prompt
toolCallResponse([
{ name: "exec", arguments: { command: "echo awake" } },
]),
// Second response: inbox message (after wakeup turn, pendingInput is cleared,
// then inbox messages are picked up on the next iteration)
noToolResponse("Received the message."),
]);
const turns: AgentTurn[] = [];
await runAgentLoop({
identity,
config,
db,
conway,
inference,
onTurnComplete: (turn) => turns.push(turn),
});
// One of the turns should have input from the inbox message
const inboxTurn = turns.find(
(t) => t.input?.includes("Hello from another agent!"),
);
expect(inboxTurn).toBeDefined();
expect(inboxTurn!.inputSource).toBe("agent");
});
it("MAX_TOOL_CALLS_PER_TURN limits tool calls", async () => {
// Create a response with 15 tool calls (max is 10)
const manyToolCalls = Array.from({ length: 15 }, (_, i) => ({
name: "exec",
arguments: { command: `echo ${i}` },
}));
const inference = new MockInferenceClient([
toolCallResponse(manyToolCalls),
noToolResponse("Done."),
]);
const turns: AgentTurn[] = [];
await runAgentLoop({
identity,
config,
db,
conway,
inference,
onTurnComplete: (turn) => turns.push(turn),
});
// The first turn should have at most 10 tool calls executed
const execTurn = turns.find((t) => t.toolCalls.length > 0);
expect(execTurn).toBeDefined();
expect(execTurn!.toolCalls.length).toBeLessThanOrEqual(10);
});
it("consecutive errors trigger sleep", async () => {
// Create an inference client that always throws
const failingInference = new MockInferenceClient([]);
failingInference.chat = async () => {
throw new Error("Inference API unavailable");
};
const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
const consoleSpy2 = vi.spyOn(console, "log").mockImplementation(() => {});
const consoleSpy3 = vi.spyOn(console, "warn").mockImplementation(() => {});
await runAgentLoop({
identity,
config: { ...config, logLevel: "debug" },
db,
conway,
inference: failingInference,
});
// After 5 consecutive errors, should be sleeping
expect(db.getAgentState()).toBe("sleeping");
expect(db.getKV("sleep_until")).toBeDefined();
consoleSpy.mockRestore();
consoleSpy2.mockRestore();
consoleSpy3.mockRestore();
});
it("financial state cached fallback on API failure", async () => {
// Pre-cache a known balance
db.setKV("last_known_balance", JSON.stringify({ creditsCents: 5000, usdcBalance: 1.0 }));
// Make credits API fail
conway.getCreditsBalance = async () => {
throw new Error("API down");
};
const inference = new MockInferenceClient([
noToolResponse("Running with cached balance."),
]);
const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
const consoleSpy2 = vi.spyOn(console, "warn").mockImplementation(() => {});
await runAgentLoop({
identity,
config,
db,
conway,
inference,
});
// Should not die, should use cached balance and continue
const state = db.getAgentState();
expect(state).not.toBe("dead");
consoleSpy.mockRestore();
consoleSpy2.mockRestore();
});
it("turn persistence is atomic with inbox ack", async () => {
// Insert an inbox message
db.insertInboxMessage({
id: "atomic-msg-1",
from: "0xsender",
to: "0xrecipient",
content: "Test atomic persistence",
signedAt: new Date().toISOString(),
createdAt: new Date().toISOString(),
});
const inference = new MockInferenceClient([
toolCallResponse([
{ name: "exec", arguments: { command: "echo processing" } },
]),
noToolResponse("Done processing."),
]);
const turns: AgentTurn[] = [];
await runAgentLoop({
identity,
config,
db,
conway,
inference,
onTurnComplete: (turn) => turns.push(turn),
});
// After processing, the inbox message should be marked as processed
const unprocessed = db.getUnprocessedInboxMessages(10);
// The message should have been consumed (either processed or not showing as unprocessed)
// Since we successfully completed the turn, it should be processed
expect(turns.length).toBeGreaterThanOrEqual(1);
});
it("state transitions are reported via onStateChange", async () => {
const stateChanges: AgentState[] = [];
const inference = new MockInferenceClient([
noToolResponse("Nothing to do."),
]);
await runAgentLoop({
identity,
config,
db,
conway,
inference,
onStateChange: (state) => stateChanges.push(state),
});
// Should have transitioned through waking -> running -> sleeping
expect(stateChanges).toContain("waking");
expect(stateChanges).toContain("running");
expect(stateChanges).toContain("sleeping");
});
it("cycle turn limit forces sleep after maxTurnsPerCycle", async () => {
// Set a low cycle limit
const lowLimitConfig = createTestConfig({ maxTurnsPerCycle: 3 });
// Create responses that would keep running indefinitely (all mutating tools)
const responses = Array.from({ length: 10 }, () =>
toolCallResponse([{ name: "exec", arguments: { command: "echo loop" } }]),
);
const inference = new MockInferenceClient(responses);
const turns: AgentTurn[] = [];
await runAgentLoop({
identity,
config: lowLimitConfig,
db,
conway,
inference,
onTurnComplete: (turn) => turns.push(turn),
});
// Should have stopped at or before the cycle limit (3 turns)
expect(turns.length).toBeLessThanOrEqual(3);
expect(db.getAgentState()).toBe("sleeping");
expect(db.getKV("sleep_until")).toBeDefined();
});
it("cycle limit sets 2-minute sleep duration", async () => {
const lowLimitConfig = createTestConfig({ maxTurnsPerCycle: 1 });
const inference = new MockInferenceClient([
toolCallResponse([{ name: "exec", arguments: { command: "echo test" } }]),
]);
await runAgentLoop({
identity,
config: lowLimitConfig,
db,
conway,
inference,
});
const sleepUntil = db.getKV("sleep_until");
expect(sleepUntil).toBeDefined();
// Sleep should be ~2 minutes (120_000ms) from now
const sleepMs = new Date(sleepUntil!).getTime() - Date.now();
expect(sleepMs).toBeGreaterThan(100_000); // at least ~100s
expect(sleepMs).toBeLessThan(150_000); // at most ~150s
});
it("respects custom maxTurnsPerCycle from config", async () => {
// A limit of 5 should allow exactly 5 turns before forcing sleep
const limit5Config = createTestConfig({ maxTurnsPerCycle: 5 });
// Use varied tool names to avoid loop detection (fires after 3 identical patterns)
const toolNames = ["exec", "write_file", "git_status", "exec", "write_file", "exec", "write_file"];
const responses = toolNames.map((name) =>
toolCallResponse([{ name, arguments: name === "exec" ? { command: "echo work" } : { path: "/tmp/test" } }]),
);
const inference = new MockInferenceClient(responses);
const turns: AgentTurn[] = [];
await runAgentLoop({
identity,
config: limit5Config,
db,
conway,
inference,
onTurnComplete: (turn) => turns.push(turn),
});
// Should have stopped at the cycle limit of 5
expect(turns.length).toBeLessThanOrEqual(5);
expect(db.getAgentState()).toBe("sleeping");
});
it("zero credits enters critical tier, not dead", async () => {
conway.creditsCents = 0; // $0 -> critical tier (agent stays alive)
const inference = new MockInferenceClient([
noToolResponse("I have no credits but I'm still alive."),
]);
const stateChanges: AgentState[] = [];
await runAgentLoop({
identity,
config,
db,
conway,
inference,
onStateChange: (state) => stateChanges.push(state),
});
// Zero credits = critical, not dead. Agent should stay alive.
expect(stateChanges).toContain("critical");
expect(stateChanges).not.toContain("dead");
expect(db.getAgentState()).not.toBe("dead");
});
it("maintenance loop detected after 3 consecutive idle-only turns", async () => {
// Simulate: wakeup turn with check_credits, then 2 more idle-only turns,
// triggering maintenance loop detection on the 3rd idle-only turn.
// Construct responses with unique tool_call IDs to avoid DB collisions.
function idleToolResponse(name: string, args: Record<string, unknown>, uid: string): ReturnType<typeof toolCallResponse> {
return {
id: `resp_${uid}`,
model: "mock-model",
message: {
role: "assistant",
content: "",
tool_calls: [{
id: `call_${uid}`,
type: "function" as const,
function: { name, arguments: JSON.stringify(args) },
}],
},
toolCalls: [{
id: `call_${uid}`,
type: "function" as const,
function: { name, arguments: JSON.stringify(args) },
}],
usage: { promptTokens: 100, completionTokens: 50, totalTokens: 150 },
finishReason: "tool_calls",
};
}
const inference = new MockInferenceClient([
idleToolResponse("check_credits", {}, "t1"),
idleToolResponse("system_synopsis", {}, "t2"),
idleToolResponse("review_memory", {}, "t3"),
noToolResponse("I will now work on something productive."),
]);
const turns: AgentTurn[] = [];
await runAgentLoop({
identity,
config,
db,
conway,
inference,
onTurnComplete: (turn) => turns.push(turn),
});
// The intervention message should have been injected after the 3rd idle-only turn.
// Turn 4 should have the maintenance loop intervention as input.
const interventionTurn = turns.find(
(t) => t.input?.includes("MAINTENANCE LOOP DETECTED"),
);
expect(interventionTurn).toBeDefined();
expect(interventionTurn!.input).toContain("status-check tools");
});
it("maintenance loop NOT triggered when turns mix idle and productive tools", async () => {
// Turn 1: idle-only, Turn 2: has productive tool (exec), Turn 3: idle-only
// Should NOT trigger because turn 2 breaks the consecutive count.
const inference = new MockInferenceClient([
// Turn 1 (wakeup): idle-only
toolCallResponse([
{ name: "check_credits", arguments: {} },
]),
// Turn 2: productive tool — resets idle counter
toolCallResponse([
{ name: "exec", arguments: { command: "echo hello" } },
]),
// Turn 3: idle-only — counter starts at 1 again
toolCallResponse([
{ name: "system_synopsis", arguments: {} },
]),
// Turn 4: end
noToolResponse("Done."),
]);
const turns: AgentTurn[] = [];
await runAgentLoop({
identity,
config,
db,
conway,
inference,
onTurnComplete: (turn) => turns.push(turn),
});
// No maintenance loop intervention should have been injected
const interventionTurn = turns.find(
(t) => t.input?.includes("MAINTENANCE LOOP DETECTED"),
);
expect(interventionTurn).toBeUndefined();
});
it("maintenance loop triggers with varying idle tool combinations", async () => {
// Each turn uses a different idle-only tool, but all are idle-only.
// The existing exact-pattern detector would NOT catch this (different patterns).
// The new idle-tool detector SHOULD catch it.
function idleToolResponse(name: string, args: Record<string, unknown>, uid: string): ReturnType<typeof toolCallResponse> {
return {
id: `resp_${uid}`,
model: "mock-model",
message: {
role: "assistant",
content: "",
tool_calls: [{
id: `call_${uid}`,
type: "function" as const,
function: { name, arguments: JSON.stringify(args) },
}],
},
toolCalls: [{
id: `call_${uid}`,
type: "function" as const,
function: { name, arguments: JSON.stringify(args) },
}],
usage: { promptTokens: 100, completionTokens: 50, totalTokens: 150 },
finishReason: "tool_calls",
};
}
const inference = new MockInferenceClient([
idleToolResponse("check_credits", {}, "v1"),
idleToolResponse("check_usdc_balance", {}, "v2"),
idleToolResponse("git_status", {}, "v3"),
noToolResponse("Starting productive work now."),
]);
const turns: AgentTurn[] = [];
await runAgentLoop({
identity,
config,
db,
conway,
inference,
onTurnComplete: (turn) => turns.push(turn),
});
const interventionTurn = turns.find(
(t) => t.input?.includes("MAINTENANCE LOOP DETECTED"),
);
expect(interventionTurn).toBeDefined();
});
it("loop enforcement forces sleep after warning is ignored (6 identical patterns)", async () => {
// 6 identical exec tool calls: warning fires at turn 3, enforcement at turn 6.
// Use unique IDs to avoid DB collisions.
function execResponse(uid: string): ReturnType<typeof toolCallResponse> {
return {
id: `resp_${uid}`,
model: "mock-model",
message: {
role: "assistant",
content: "",
tool_calls: [{
id: `call_${uid}`,
type: "function" as const,
function: { name: "exec", arguments: JSON.stringify({ command: "echo loop" }) },
}],
},
toolCalls: [{
id: `call_${uid}`,
type: "function" as const,
function: { name: "exec", arguments: JSON.stringify({ command: "echo loop" }) },
}],
usage: { promptTokens: 100, completionTokens: 50, totalTokens: 150 },
finishReason: "tool_calls",
};
}
const inference = new MockInferenceClient([
execResponse("e1"),
execResponse("e2"),
execResponse("e3"), // Warning fires here
execResponse("e4"),
execResponse("e5"),
execResponse("e6"), // Enforcement fires here — forced sleep
]);
const turns: AgentTurn[] = [];
const stateChanges: AgentState[] = [];
await runAgentLoop({
identity,
config,
db,
conway,
inference,
onTurnComplete: (turn) => turns.push(turn),
onStateChange: (state) => stateChanges.push(state),
});
// Should have the warning at turn 4 (injected after turn 3)
const warningTurn = turns.find(
(t) => t.input?.includes("LOOP DETECTED"),
);
expect(warningTurn).toBeDefined();
// Agent should be sleeping due to enforcement
expect(db.getAgentState()).toBe("sleeping");
expect(stateChanges[stateChanges.length - 1]).toBe("sleeping");
});
it("loop enforcement resets when agent changes behavior after warning", async () => {
// 3 identical exec calls → warning → different tool → 3 more exec calls → warning (not enforcement)
function execResponse(uid: string): ReturnType<typeof toolCallResponse> {
return {
id: `resp_${uid}`,
model: "mock-model",
message: {
role: "assistant",
content: "",
tool_calls: [{
id: `call_${uid}`,
type: "function" as const,
function: { name: "exec", arguments: JSON.stringify({ command: "echo loop" }) },
}],
},
toolCalls: [{
id: `call_${uid}`,
type: "function" as const,
function: { name: "exec", arguments: JSON.stringify({ command: "echo loop" }) },
}],
usage: { promptTokens: 100, completionTokens: 50, totalTokens: 150 },
finishReason: "tool_calls",
};
}
const inference = new MockInferenceClient([
execResponse("r1"),
execResponse("r2"),
execResponse("r3"), // Warning fires, loopWarningPattern = "exec"
// Turn 4: different tool — resets loopWarningPattern
toolCallResponse([
{ name: "send_message", arguments: { to: "0x123", content: "hello" } },
]),
execResponse("r5"),
execResponse("r6"),
execResponse("r7"), // Warning fires again (NOT enforcement — tracker was reset)
noToolResponse("Done."),
]);
const turns: AgentTurn[] = [];
await runAgentLoop({
identity,
config,
db,
conway,
inference,
onTurnComplete: (turn) => turns.push(turn),
});
// Should have gotten a warning, not enforcement (agent is still running, not force-slept)
// The second set of 3 identical patterns gets a NEW warning, not enforcement
const warningTurns = turns.filter(
(t) => t.input?.includes("LOOP DETECTED"),
);
expect(warningTurns.length).toBeGreaterThanOrEqual(2);
// No enforcement turn should exist
const enforcementTurn = turns.find(
(t) => t.input?.includes("LOOP ENFORCEMENT"),
);
expect(enforcementTurn).toBeUndefined();
});
it("discover_agents turns are retained in context (not classified as idle)", { timeout: 180_000 }, async () => {
// A turn with only discover_agents should NOT trigger maintenance loop detection
// because discover_agents is no longer in IDLE_ONLY_TOOLS
function discoverResponse(uid: string): ReturnType<typeof toolCallResponse> {
return {
id: `resp_${uid}`,
model: "mock-model",
message: {
role: "assistant",
content: "",
tool_calls: [{
id: `call_${uid}`,
type: "function" as const,
function: { name: "discover_agents", arguments: JSON.stringify({ limit: 15 }) },
}],
},
toolCalls: [{
id: `call_${uid}`,
type: "function" as const,
function: { name: "discover_agents", arguments: JSON.stringify({ limit: 15 }) },
}],
usage: { promptTokens: 100, completionTokens: 50, totalTokens: 150 },
finishReason: "tool_calls",
};
}
const inference = new MockInferenceClient([
discoverResponse("d1"),
discoverResponse("d2"),
discoverResponse("d3"), // Would trigger maintenance loop if discover_agents were idle
noToolResponse("Processing discovery results."),
]);
const turns: AgentTurn[] = [];
await runAgentLoop({
identity,
config,
db,
conway,
inference,
onTurnComplete: (turn) => turns.push(turn),
});
// No maintenance loop detection should fire since discover_agents is NOT idle
const maintenanceTurn = turns.find(
(t) => t.input?.includes("MAINTENANCE LOOP DETECTED"),
);
expect(maintenanceTurn).toBeUndefined();
// But the repetitive pattern detector SHOULD fire (3 identical patterns)
const loopWarning = turns.find(
(t) => t.input?.includes("LOOP DETECTED"),
);
expect(loopWarning).toBeDefined();
});
it("read_file turns are retained in context (not classified as idle)", async () => {
conway.files["/tmp/one.txt"] = "one";
conway.files["/tmp/two.txt"] = "two";
conway.files["/tmp/three.txt"] = "three";
const inference = new MockInferenceClient([
toolCallResponse([{ name: "read_file", arguments: { path: "/tmp/one.txt" } }]),
toolCallResponse([{ name: "read_file", arguments: { path: "/tmp/two.txt" } }]),
toolCallResponse([{ name: "read_file", arguments: { path: "/tmp/three.txt" } }]),
noToolResponse("Processed file contents."),
]);
const turns: AgentTurn[] = [];
await runAgentLoop({
identity,
config,
db,
conway,
inference,
onTurnComplete: (turn) => turns.push(turn),
});
const maintenanceTurn = turns.find(
(t) => t.input?.includes("MAINTENANCE LOOP DETECTED"),
);
expect(maintenanceTurn).toBeUndefined();
const loopWarning = turns.find(
(t) => t.input?.includes("LOOP DETECTED"),
);
expect(loopWarning).toBeDefined();
});
it("sleeps early when delegated work is active and no self-assigned parent task remains", async () => {
const tickSpy = vi.spyOn(Orchestrator.prototype, "tick").mockResolvedValue({
phase: "executing",
tasksAssigned: 0,
tasksCompleted: 0,
tasksFailed: 0,
goalsActive: 1,
agentsActive: 1,
});
const inference = new MockInferenceClient([
noToolResponse("This should never be used."),
]);
await runAgentLoop({
identity,
config,
db,
conway,
inference,
});
expect(db.getAgentState()).toBe("sleeping");
expect(db.getKV("sleep_until")).toBeDefined();
expect(inference.calls.length).toBe(0);
tickSpy.mockRestore();
});
it("does not sleep early when the parent has a self-assigned task", async () => {
db.raw.prepare(
"INSERT INTO goals (id, title, description, status, created_at) VALUES (?, ?, ?, ?, ?)",
).run("goal-self", "Self goal", "Self goal description", "active", new Date().toISOString());
db.raw.prepare(
`INSERT INTO task_graph
(id, goal_id, title, description, status, assigned_to, agent_role, priority, dependencies, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
).run(
"task-self",
"goal-self",
"Parent task",
"Handled by parent",
"assigned",
identity.address,
"generalist",
50,
JSON.stringify([]),
new Date().toISOString(),
);
const tickSpy = vi.spyOn(Orchestrator.prototype, "tick").mockResolvedValue({
phase: "executing",
tasksAssigned: 0,
tasksCompleted: 0,
tasksFailed: 0,
goalsActive: 1,
agentsActive: 1,
});
const inference = new MockInferenceClient([
noToolResponse("Still working."),
]);
await runAgentLoop({
identity,
config,
db,
conway,
inference,
});
expect(inference.calls.length).toBeGreaterThan(0);
tickSpy.mockRestore();
});
});