Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off -- fixtures name transcript files by URL.
2import * as NodeURL from "node:url";
3
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import { expect, it } from "@effect/vitest";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Path from "effect/Path";
9
10import {
11 ANTIGRAVITY_SUBAGENT_BATCH_TITLE,
12 antigravitySubagentLaunches,
13 describeAntigravitySubagentLaunches,
14 readAntigravityChildrenAtWork,
15 readAntigravityChildWork,
16 readAntigravityPendingReply,
17} from "./AntigravityChildWork.ts";
18import { sanitizeAntigravityToolPayload } from "./AntigravityProtocol.ts";
19import {
20 autoApproved,
21 CHILD,
22 invokeStep,
23 LAUNCH,
24 makeProfile,
25 plannerStep,
26 ROOT,
27 transcriptLines,
28} from "./AntigravityChildWork.testkit.ts";
29
30const read = (
31 profileDirectory: string,
32 nativeTaskId: string,
33 launch: { readonly title: string | null; readonly prompt: string } = {
34 title: null,
35 prompt: "Readme check",
36 },
37 siblings: ReadonlyArray<{
38 readonly nativeTaskId: string;
39 readonly title: string | null;
40 readonly prompt: string;
41 }> = [],
42) =>
43 readAntigravityChildWork({
44 profileDirectory,
45 rootSessionId: ROOT,
46 nativeTaskId,
47 launch,
48 siblings,
49 });
50
51it.layer(NodeServices.layer)("readAntigravityChildWork", (it) => {
52 it.effect("follows an auto-approved call id through its planner step to the record", () =>
53 Effect.gen(function* () {
54 const { profile } = yield* makeProfile({ steps: autoApproved });
55 const [child, ...rest] = yield* read(profile, `${ROOT}:1`);
56 expect(rest).toEqual([]);
57 expect(child).toMatchObject({
58 conversationId: CHILD,
59 role: LAUNCH.role,
60 prompt: LAUNCH.prompt,
61 truncated: false,
62 });
63 // The launch envelope repeats the prompt shown above, so the steps start with the child's work.
64 expect(child?.steps?.map((step) => step.text ?? step.toolCalls[0]?.name)).toEqual([
65 "view_file",
66 "2: child read marker 4242",
67 "marker 4242 found",
68 ]);
69 expect(child?.steps?.[0]?.toolCalls[0]?.input).toBe('{"AbsolutePath":"/project/README.md"}');
70 }),
71 );
72
73 it.effect("needs proof that the call id belongs to the parent's record", () =>
74 Effect.gen(function* () {
75 const { profile } = yield* makeProfile({
76 steps: (logUri) => [
77 ...autoApproved(logUri),
78 [5, 15, plannerStep(["call-b", "call-c"])],
79 [
80 6,
81 127,
82 invokeStep({ callId: "call-b", launches: [LAUNCH], children: [{ id: CHILD, logUri }] }),
83 ],
84 [
85 7,
86 127,
87 invokeStep({ callId: "call-c", launches: [LAUNCH], children: [{ id: CHILD, logUri }] }),
88 ],
89 ],
90 });
91 // Another session's id, a step that is not the planner call, and parallel calls that share one id.
92 expect(yield* read(profile, `00000000-0000-4000-8000-000000000000:1`)).toEqual([]);
93 expect(yield* read(profile, `${ROOT}:2`)).toEqual([]);
94 expect(yield* read(profile, `${ROOT}:5`)).toEqual([]);
95 }),
96 );
97
98 it.effect("matches a permission-prompt call by its launch text, only when unique", () =>
99 Effect.gen(function* () {
100 const other = { role: "Test Runner", prompt: "Run the tests" };
101 const long = { role: "Long Reader", prompt: `Read this:\n🚀${"x".repeat(7_999)}` };
102 // A role's leading byte order mark is part of its text.
103 const marked = { role: "\uFEFFMarked", prompt: "Check the mark" };
104 const { profile } = yield* makeProfile({
105 steps: (logUri) => [
106 [
107 2,
108 127,
109 invokeStep({ callId: "x", launches: [LAUNCH], children: [{ id: CHILD, logUri }] }),
110 ],
111 [
112 8,
113 127,
114 invokeStep({ callId: "w", launches: [long], children: [{ id: CHILD, logUri }] }),
115 ],
116 [
117 10,
118 127,
119 invokeStep({ callId: "v", launches: [marked], children: [{ id: CHILD, logUri }] }),
120 ],
121 [
122 4,
123 127,
124 invokeStep({ callId: "y", launches: [other], children: [{ id: CHILD, logUri }] }),
125 ],
126 [
127 6,
128 127,
129 invokeStep({ callId: "z", launches: [other], children: [{ id: CHILD, logUri }] }),
130 ],
131 ],
132 });
133 const opaque = "35bea692fa95447fbdae6333fec5515f";
134 const matched = yield* read(profile, opaque, describeAntigravitySubagentLaunches([LAUNCH]));
135 expect(matched.map((child) => child.role)).toEqual([LAUNCH.role]);
136 // T3 knows a second batch with this text that the agent has not recorded yet.
137 const twin = { nativeTaskId: "f00d", ...describeAntigravitySubagentLaunches([LAUNCH]) };
138 expect(
139 yield* read(profile, opaque, describeAntigravitySubagentLaunches([LAUNCH]), [twin]),
140 ).toEqual([]);
141 // T3 stores the launch from the bounded tool payload, which keeps only a long prompt's tail.
142 const stored = antigravitySubagentLaunches(
143 sanitizeAntigravityToolPayload({ Subagents: [{ Role: long.role, Prompt: long.prompt }] }),
144 );
145 const longMatch = yield* read(profile, opaque, describeAntigravitySubagentLaunches(stored!));
146 expect(longMatch.map((child) => child.prompt)).toEqual([long.prompt]);
147 const savedLaunch = {
148 title: long.role,
149 prompt: `[Earlier output truncated]\n\n\uDE80${"x".repeat(7_999)}`,
150 };
151 expect((yield* read(profile, opaque, savedLaunch)).map((child) => child.prompt)).toEqual([
152 long.prompt,
153 ]);
154 expect(
155 yield* read(profile, opaque, describeAntigravitySubagentLaunches([marked])),
156 ).toHaveLength(1);
157 expect(yield* read(profile, opaque, { title: "Marked", prompt: marked.prompt })).toEqual([]);
158 expect(yield* read(profile, opaque, describeAntigravitySubagentLaunches([other]))).toEqual(
159 [],
160 );
161 expect(yield* read(profile, opaque, { title: null, prompt: "Readme check" })).toEqual([]);
162 }),
163 );
164
165 it.effect("leaves an auto-approved batch's record out of a launch-text match", () =>
166 Effect.gen(function* () {
167 const { profile } = yield* makeProfile({ steps: autoApproved });
168 const launch = describeAntigravitySubagentLaunches([LAUNCH]);
169 const opaque = "35bea692fa95447fbdae6333fec5515f";
170 expect(yield* read(profile, opaque, launch)).toHaveLength(1);
171 // An earlier auto-approved batch stored no launch text, but its planner step claims the record.
172 const auto = {
173 nativeTaskId: `${ROOT}:1`,
174 title: ANTIGRAVITY_SUBAGENT_BATCH_TITLE,
175 prompt: "",
176 };
177 expect(yield* read(profile, opaque, launch, [auto])).toEqual([]);
178 // A sibling that cannot be ruled out refuses the match: its planner step is unreadable,
179 // or it is a permission batch whose launch text is missing or cut.
180 for (const sibling of [
181 { ...auto, nativeTaskId: `${ROOT}:99` },
182 { nativeTaskId: "0ld", title: ANTIGRAVITY_SUBAGENT_BATCH_TITLE, prompt: "Running" },
183 // Its stored launch was cut, so it may be this same launch.
184 { nativeTaskId: "cut", title: LAUNCH.role, prompt: "[Earlier output truncated]\n\nmarker" },
185 { nativeTaskId: "cut", title: "[Earlier output truncated]\n\nReader", prompt: "x" },
186 { nativeTaskId: "cut", title: null, prompt: "[Earlier output truncated]\n\nx" },
187 ]) {
188 expect(yield* read(profile, opaque, launch, [sibling])).toEqual([]);
189 }
190 // A cut prompt under different roles is another launch.
191 const other = {
192 nativeTaskId: "cut",
193 title: "Test Runner",
194 prompt: "[Earlier output truncated]\n\nx",
195 };
196 expect(yield* read(profile, opaque, launch, [other])).toHaveLength(1);
197 }),
198 );
199
200 it.effect("reads no transcript outside the child's own profile path", () =>
201 Effect.gen(function* () {
202 const fs = yield* FileSystem.FileSystem;
203 const path = yield* Path.Path;
204 const outside = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-outside-" });
205 const secret = path.join(outside, "transcript.jsonl");
206 yield* fs.writeFileString(secret, JSON.stringify(transcriptLines[3]) + "\n");
207 const named = yield* makeProfile({
208 steps: () => autoApproved(NodeURL.pathToFileURL(secret).href),
209 });
210 const [namedChild] = yield* read(named.profile, `${ROOT}:1`);
211 expect(namedChild?.role).toBe(LAUNCH.role);
212 expect(namedChild?.steps).toBeNull();
213
214 const linked = yield* makeProfile({ steps: autoApproved });
215 yield* fs.remove(linked.transcriptPath);
216 yield* fs.symlink(secret, linked.transcriptPath);
217 const [linkedChild] = yield* read(linked.profile, `${ROOT}:1`);
218 expect(linkedChild?.steps).toBeNull();
219 }),
220 );
221
222 it.effect("reads only the tail of a large transcript", () =>
223 Effect.gen(function* () {
224 const filler = JSON.stringify({
225 step_index: 0,
226 type: "VIEW_FILE",
227 status: "DONE",
228 content: "x".repeat(10_000),
229 });
230 const { profile } = yield* makeProfile({
231 steps: autoApproved,
232 transcript: `${Array.from({ length: 40 }, () => filler).join("\n")}\n${JSON.stringify(transcriptLines[3])}\n`,
233 });
234 const [child] = yield* read(profile, `${ROOT}:1`);
235 expect(child?.truncated).toBe(true);
236 expect(child?.steps?.length).toBeLessThan(40);
237 expect(child?.steps?.at(-1)?.text).toBe("marker 4242 found");
238 expect(child?.steps?.[0]?.text?.length).toBeLessThanOrEqual(4_001);
239
240 const lastLine = JSON.stringify(transcriptLines[3]) + "\n";
241 const step = { step_index: 2, type: "VIEW_FILE", content: "" };
242 const remaining = 256 * 1024 - Buffer.byteLength(JSON.stringify(step) + "\n" + lastLine);
243 const firstLine = JSON.stringify({
244 ...step,
245 content: "é".repeat(Math.floor(remaining / 2)) + "x".repeat(remaining % 2),
246 });
247 const aligned = yield* makeProfile({
248 steps: autoApproved,
249 transcript: `${filler}\n${firstLine}\n${lastLine}`,
250 });
251 const [alignedChild] = yield* read(aligned.profile, `${ROOT}:1`);
252 expect(alignedChild).toMatchObject({
253 truncated: true,
254 steps: [{ index: 2 }, { index: 3 }],
255 });
256
257 const paddedLine = firstLine.padEnd(firstLine.length + Buffer.byteLength(lastLine) + 1);
258 const undelimited = yield* makeProfile({
259 steps: autoApproved,
260 transcript: filler + paddedLine,
261 });
262 const [undelimitedChild] = yield* read(undelimited.profile, `${ROOT}:1`);
263 expect(undelimitedChild).toMatchObject({ truncated: true, steps: [] });
264 }),
265 );
266
267 it.effect("refuses links between children and sessions inside the same profile", () =>
268 Effect.gen(function* () {
269 const fs = yield* FileSystem.FileSystem;
270 const path = yield* Path.Path;
271 const sibling = "b468c0e1d2f34a5b6c7d8e9f0a1b2c3d";
272 // The record names this child's literal path, but the child directory links to a sibling.
273 const linked = yield* makeProfile({ steps: autoApproved });
274 const brain = path.join(linked.profile, "antigravity-acp", "brain");
275 yield* fs.rename(path.join(brain, CHILD), path.join(brain, sibling));
276 yield* fs.symlink(path.join(brain, sibling), path.join(brain, CHILD));
277 const [child] = yield* read(linked.profile, `${ROOT}:1`);
278 expect(child?.role).toBe(LAUNCH.role);
279 expect(child?.steps).toBeNull();
280
281 // This session's database links to another session's records.
282 const other = yield* makeProfile({ steps: autoApproved });
283 const conversations = path.join(other.profile, "antigravity-acp", "conversations");
284 const peer = path.join(conversations, "00000000-0000-4000-8000-000000000000.db");
285 yield* fs.rename(path.join(conversations, `${ROOT}.db`), peer);
286 yield* fs.symlink(peer, path.join(conversations, `${ROOT}.db`));
287 expect(yield* read(other.profile, `${ROOT}:1`)).toEqual([]);
288 }),
289 );
290
291 it.effect("declines a launch-text match it cannot prove unique within its scan bounds", () =>
292 Effect.gen(function* () {
293 const record = (callId: string, logUri: string) =>
294 invokeStep({ callId, launches: [LAUNCH], children: [{ id: CHILD, logUri }] });
295 const other = { role: "Test Runner", prompt: "Run the tests" };
296 const filler = (idx: number, logUri: string) =>
297 [
298 idx,
299 127,
300 invokeStep({ callId: `f${idx}`, launches: [other], children: [{ id: CHILD, logUri }] }),
301 ] as const;
302 const opaque = "35bea692fa95447fbdae6333fec5515f";
303 const launch = describeAntigravitySubagentLaunches([LAUNCH]);
304 const cases = [
305 // More records than one open may scan.
306 (logUri: string) => [
307 [1, 127, record("x", logUri)] as const,
308 ...Array.from({ length: 200 }, (_, index) => filler(index + 2, logUri)),
309 ],
310 // An oversized record could hold an identical launch.
311 (logUri: string) => [
312 [1, 127, record("x", logUri)] as const,
313 [2, 127, new Uint8Array(1024 * 1024 + 1)] as const,
314 ],
315 // So could one this reader cannot decode.
316 (logUri: string) => [
317 [1, 127, record("x", logUri)] as const,
318 [2, 127, Uint8Array.from([0xff, 0xff])] as const,
319 ],
320 ];
321 for (const steps of cases) {
322 const { profile } = yield* makeProfile({ steps });
323 expect(yield* read(profile, opaque, launch)).toEqual([]);
324 }
325 }),
326 );
327
328 it.effect("keeps the batch view for a batch over the child limit", () =>
329 Effect.gen(function* () {
330 const { profile } = yield* makeProfile({
331 steps: (logUri) => [
332 [1, 15, plannerStep(["call-a"])],
333 [
334 2,
335 127,
336 invokeStep({
337 callId: "call-a",
338 launches: Array.from({ length: 17 }, () => LAUNCH),
339 children: Array.from({ length: 17 }, () => ({ id: CHILD, logUri })),
340 }),
341 ],
342 ],
343 });
344 expect(yield* read(profile, `${ROOT}:1`)).toEqual([]);
345 }),
346 );
347
348 it.effect("follows a detached 1.5 launch id through the child's inbox to its transcript", () =>
349 Effect.gen(function* () {
350 const fs = yield* FileSystem.FileSystem;
351 const path = yield* Path.Path;
352 const profile = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-detached-" });
353 const sibling = "b468c0e1-d2f3-4a5b-6c7d-8e9f0a1b2c3d";
354 const writeJson = (segments: ReadonlyArray<string>, value: unknown) => {
355 const file = path.join(profile, "antigravity-acp", "brain", ...segments);
356 return fs
357 .makeDirectory(path.dirname(file), { recursive: true })
358 .pipe(Effect.andThen(fs.writeFileString(file, JSON.stringify(value))));
359 };
360 const writeTranscript = (
361 conversationId: string,
362 lines: ReadonlyArray<Record<string, unknown>>,
363 ) => {
364 const file = path.join(
365 profile,
366 "antigravity-acp",
367 "brain",
368 conversationId,
369 ".system_generated",
370 "logs",
371 "transcript.jsonl",
372 );
373 return fs
374 .makeDirectory(path.dirname(file), { recursive: true })
375 .pipe(
376 Effect.andThen(
377 fs.writeFileString(file, lines.map((line) => JSON.stringify(line)).join("\n") + "\n"),
378 ),
379 );
380 };
381
382 // Matches real agy 1.5.12 records (no legacy step_type=127 database row).
383 yield* writeJson([ROOT, ".system_generated", "subagents", `${CHILD}.json`], {
384 conversationId: CHILD,
385 subagentDescriptor: { typeName: "research", role: LAUNCH.role },
386 state: "SUBAGENT_STATE_ALIVE",
387 });
388 yield* writeJson([CHILD, ".system_generated", "messages", "launch.json"], {
389 sender: ROOT,
390 content: LAUNCH.prompt,
391 sourceMetadata: {
392 tool: {
393 conversationId: ROOT,
394 stepIndex: 2,
395 toolCall: {
396 id: "call_11340266277043349041",
397 name: "invoke_subagent",
398 argumentsJson: JSON.stringify({
399 TypeName: "research",
400 Role: LAUNCH.role,
401 Prompt: LAUNCH.prompt,
402 }),
403 },
404 },
405 },
406 });
407 yield* writeJson([CHILD, ".system_generated", "messages", "read.json"], { launch: true });
408 yield* writeTranscript(CHILD, [
409 {
410 step_index: 0,
411 type: "SYSTEM_MESSAGE",
412 status: "DONE",
413 content: `<SYSTEM_MESSAGE>\n[Message] sender=${ROOT} content=${LAUNCH.prompt}\n</SYSTEM_MESSAGE>`,
414 },
415 {
416 step_index: 1,
417 type: "PLANNER_RESPONSE",
418 status: "DONE",
419 tool_calls: [{ name: "read_file", args: { Path: '"/project/README.md"' } }],
420 },
421 {
422 step_index: 2,
423 type: "GENERIC",
424 status: "DONE",
425 content: "2: MAGIC_TOKEN=probe-38478-ok",
426 },
427 ]);
428
429 // A second detached child without argumentsJson falls back to descriptor role + message content.
430 yield* writeJson([ROOT, ".system_generated", "subagents", `${sibling}.json`], {
431 conversationId: sibling,
432 subagentDescriptor: { typeName: "research", role: "Line Counter" },
433 });
434 yield* writeJson([sibling, ".system_generated", "messages", "launch.json"], {
435 sender: ROOT,
436 content: "Count lines in README.md",
437 sourceMetadata: {
438 tool: {
439 toolCall: { id: "call_22340266277043349042", name: "invoke_subagent" },
440 },
441 },
442 });
443 // A follow-up send_message must not be treated as a launch.
444 yield* writeJson([sibling, ".system_generated", "messages", "followup.json"], {
445 sender: ROOT,
446 content: "Also check LICENSE",
447 sourceMetadata: {
448 tool: {
449 toolCall: { id: "call_followup", name: "send_message" },
450 },
451 },
452 });
453
454 const [first, ...firstRest] = yield* read(profile, "call_11340266277043349041", {
455 title: LAUNCH.role,
456 prompt: LAUNCH.prompt,
457 });
458 expect(firstRest).toEqual([]);
459 expect(first).toMatchObject({
460 conversationId: CHILD,
461 role: LAUNCH.role,
462 prompt: LAUNCH.prompt,
463 truncated: false,
464 });
465 expect(first?.steps?.map((step) => step.text ?? step.toolCalls[0]?.name)).toEqual([
466 "read_file",
467 "2: MAGIC_TOKEN=probe-38478-ok",
468 ]);
469 expect(first?.steps?.[0]?.toolCalls[0]?.input).toBe('{"Path":"/project/README.md"}');
470
471 // Missing transcript still returns the proven child with steps: null.
472 const [second] = yield* read(profile, "call_22340266277043349042", {
473 title: "Line Counter",
474 prompt: "Count lines in README.md",
475 });
476 expect(second).toEqual({
477 conversationId: sibling,
478 role: "Line Counter",
479 prompt: "Count lines in README.md",
480 steps: null,
481 truncated: false,
482 });
483
484 // Unknown id and send_message id return nothing.
485 expect(yield* read(profile, "call_unknown")).toEqual([]);
486 expect(yield* read(profile, "call_followup")).toEqual([]);
487
488 // Another child claiming the same toolCall id makes ownership ambiguous.
489 yield* writeJson([sibling, ".system_generated", "messages", "dup.json"], {
490 sender: ROOT,
491 content: LAUNCH.prompt,
492 sourceMetadata: {
493 tool: {
494 toolCall: { id: "call_11340266277043349041", name: "invoke_subagent" },
495 },
496 },
497 });
498 expect(yield* read(profile, "call_11340266277043349041")).toEqual([]);
499 }),
500 );
501
502 it.effect("counts a detached child killed before it reported as no longer at work", () =>
503 Effect.gen(function* () {
504 const fs = yield* FileSystem.FileSystem;
505 const path = yield* Path.Path;
506 const profile = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-killed-" });
507 const killed = "0a591388-d9d9-439d-a2a0-90932fd25b39";
508 const writeJson = (segments: ReadonlyArray<string>, value: unknown) => {
509 const file = path.join(profile, "antigravity-acp", "brain", ...segments);
510 return fs
511 .makeDirectory(path.dirname(file), { recursive: true })
512 .pipe(Effect.andThen(fs.writeFileString(file, JSON.stringify(value))));
513 };
514 const child = (conversationId: string, state: string, callId: string) =>
515 Effect.all([
516 writeJson([ROOT, ".system_generated", "subagents", `${conversationId}.json`], {
517 conversationId,
518 subagentDescriptor: { typeName: "research", role: LAUNCH.role },
519 state,
520 }),
521 writeJson([conversationId, ".system_generated", "messages", "launch.json"], {
522 sender: ROOT,
523 content: LAUNCH.prompt,
524 sourceMetadata: {
525 tool: { conversationId: ROOT, toolCall: { id: callId, name: "invoke_subagent" } },
526 },
527 }),
528 ]);
529
530 // agy 1.5.13 `manage_subagents(kill)` only rewrites the record's state; nothing reaches the parent's inbox.
531 yield* child(CHILD, "SUBAGENT_STATE_ALIVE", "call_alive");
532 yield* child(killed, "SUBAGENT_STATE_KILLED", "call_killed");
533
534 expect(
535 yield* readAntigravityChildrenAtWork({
536 profileDirectory: profile,
537 rootSessionId: ROOT,
538 toolCallIds: ["call_alive", "call_killed"],
539 }),
540 ).toEqual(["call_alive"]);
541 }),
542 );
543
544 it.effect(
545 "reads legacy disk-backed swarm worker transcripts and tracks working vs parked or killed members",
546 () =>
547 Effect.gen(function* () {
548 const fs = yield* FileSystem.FileSystem;
549 const path = yield* Path.Path;
550 const profile = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-swarm-disk-" });
551 const workerOne = "11111111-1111-4000-8000-111111111111";
552 const workerTwo = "22222222-2222-4000-8000-222222222222";
553 const workerKilled = "33333333-3333-4000-8000-333333333333";
554 const writeFile = (segments: ReadonlyArray<string>, body: string) => {
555 const file = path.join(profile, "antigravity-acp", "brain", ...segments);
556 return fs
557 .makeDirectory(path.dirname(file), { recursive: true })
558 .pipe(Effect.andThen(fs.writeFileString(file, body)));
559 };
560 const writeWorker = (
561 convId: string,
562 name: string,
563 callId: string,
564 args: Record<string, unknown>,
565 reply: string,
566 ) =>
567 Effect.all([
568 writeFile(
569 [ROOT, ".system_generated", "subagents", `${convId}.json`],
570 JSON.stringify({
571 conversationId: convId,
572 subagentDescriptor: { typeName: "self", role: `Swarm Worker (${name})` },
573 state: "SUBAGENT_STATE_ALIVE",
574 }),
575 ),
576 writeFile(
577 [convId, ".system_generated", "messages", "launch.json"],
578 JSON.stringify({
579 sender: ROOT,
580 content: `Task for ${name}`,
581 sourceMetadata: {
582 tool: {
583 conversationId: ROOT,
584 toolCall: { id: callId, name: "swarm", argumentsJson: JSON.stringify(args) },
585 },
586 },
587 }),
588 ),
589 writeFile(
590 [convId, ".system_generated", "logs", "transcript.jsonl"],
591 `${JSON.stringify({ step_index: 0, type: "PLANNER_RESPONSE", status: "DONE", content: reply })}\n`,
592 ),
593 ]);
594
595 const batchArgs = {
596 action: "add",
597 name: "shard",
598 brief: "Inspect shard",
599 tasks: ["First shard", "Second shard"],
600 };
601 yield* writeWorker(workerOne, "shard-1", "call_batch", batchArgs, "shard-1 finished");
602 yield* writeWorker(workerTwo, "shard-2", "call_batch", batchArgs, "shard-2 working");
603 yield* writeWorker(
604 workerKilled,
605 "retired",
606 "call_retired",
607 { action: "add", name: "retired", brief: "Old task" },
608 "stopped",
609 );
610 yield* writeFile(
611 [ROOT, ".system_generated", "swarm", "members.json"],
612 JSON.stringify({
613 title: "Shard audit",
614 members: {
615 coordinator: { conversation_id: ROOT, role: "coordinator", wake_mode: "mentions" },
616 "shard-1": { conversation_id: workerOne, role: "worker", wake_mode: "mentions" },
617 "shard-2": { conversation_id: workerTwo, role: "worker", wake_mode: "working" },
618 retired: {
619 conversation_id: workerKilled,
620 role: "worker",
621 desired_state: "KILLED",
622 phase: "KILLED",
623 wake_mode: "working",
624 },
625 },
626 }),
627 );
628
629 // shard-1 is parked on mentions and retired is killed; only shard-2 keeps call_batch active.
630 expect(
631 yield* readAntigravityChildrenAtWork({
632 profileDirectory: profile,
633 rootSessionId: ROOT,
634 toolCallIds: ["call_batch", "call_retired"],
635 }),
636 ).toEqual(["call_batch"]);
637
638 const batchChildren = yield* read(profile, "call_batch");
639 expect(batchChildren.map((child) => [child.role, child.prompt])).toEqual([
640 ["@shard-1", "Inspect shard\n\nFirst shard"],
641 ["@shard-2", "Inspect shard\n\nSecond shard"],
642 ]);
643 expect(batchChildren[0]?.steps?.[0]?.text).toBe("shard-1 finished");
644
645 expect(antigravitySubagentLaunches({ action: "add", name: "w", n: 1e9 })).toHaveLength(64);
646 }),
647 );
648
649 it.effect("shares one transcript budget across the batch", () =>
650 Effect.gen(function* () {
651 const filler = JSON.stringify({
652 step_index: 0,
653 type: "VIEW_FILE",
654 status: "DONE",
655 content: "x".repeat(1_000),
656 });
657 const transcript = `${Array.from({ length: 300 }, () => filler).join("\n")}\n`;
658 const { profile } = yield* makeProfile({
659 transcript,
660 steps: (logUri) => [
661 [1, 15, plannerStep(["call-a"])],
662 [
663 2,
664 127,
665 invokeStep({
666 callId: "call-a",
667 launches: Array.from({ length: 16 }, () => LAUNCH),
668 children: Array.from({ length: 16 }, () => ({ id: CHILD, logUri })),
669 }),
670 ],
671 ],
672 });
673 const children = yield* read(profile, `${ROOT}:1`);
674 expect(children).toHaveLength(16);
675 expect(children.every((child) => child.truncated)).toBe(true);
676 expect(JSON.stringify(children).length).toBeLessThan(600 * 1024);
677 }),
678 );
679
680 it.effect(
681 "detects unread high-priority inbox wakes and trailing waking SYSTEM_MESSAGE steps",
682 () =>
683 Effect.gen(function* () {
684 const fs = yield* FileSystem.FileSystem;
685 const path = yield* Path.Path;
686 const profile = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-pending-reply-" });
687 const write = (segments: ReadonlyArray<string>, body: string) => {
688 const file = path.join(
689 profile,
690 "antigravity-acp",
691 "brain",
692 ROOT,
693 ".system_generated",
694 ...segments,
695 );
696 return fs
697 .makeDirectory(path.dirname(file), { recursive: true })
698 .pipe(Effect.andThen(fs.writeFileString(file, body)));
699 };
700 const pending = () =>
701 readAntigravityPendingReply({ profileDirectory: profile, sessionId: ROOT });
702
703 // Empty profile or invalid session id fails closed.
704 expect(yield* pending()).toBe(false);
705 expect(
706 yield* readAntigravityPendingReply({ profileDirectory: profile, sessionId: "../escape" }),
707 ).toBe(false);
708
709 // Low-priority unread notices (e.g. cancelled task / server restart) do not wake the agent.
710 yield* write(
711 ["messages", "low-1.json"],
712 JSON.stringify({ id: "low-1", priority: "MESSAGE_PRIORITY_LOW", sender: "system" }),
713 );
714 expect(yield* pending()).toBe(false);
715
716 // An unread high-priority message indicates a queued wake.
717 yield* write(
718 ["messages", "high-1.json"],
719 JSON.stringify({
720 id: "high-1",
721 priority: "MESSAGE_PRIORITY_HIGH",
722 sender: `${ROOT}/task-1`,
723 }),
724 );
725 expect(yield* pending()).toBe(true);
726
727 // Once marked read in read.json and followed by a completed PLANNER_RESPONSE, nothing is pending.
728 yield* write(["messages", "read.json"], JSON.stringify({ "high-1": true }));
729 yield* write(
730 ["logs", "transcript.jsonl"],
731 `${JSON.stringify({ step_index: 1, type: "PLANNER_RESPONSE", status: "DONE", content: "Done." })}\n`,
732 );
733 expect(yield* pending()).toBe(false);
734
735 // A trailing waking SYSTEM_MESSAGE (even past a >64 KiB prefix) means the reply is in flight.
736 const filler = JSON.stringify({
737 step_index: 0,
738 type: "GENERIC",
739 status: "DONE",
740 content: "x".repeat(8_000),
741 });
742 yield* write(
743 ["logs", "transcript.jsonl"],
744 `${Array.from({ length: 12 }, () => filler).join("\n")}\n${JSON.stringify({
745 step_index: 2,
746 type: "SYSTEM_MESSAGE",
747 status: "DONE",
748 content: "priority=MESSAGE_PRIORITY_HIGH task-2 finished",
749 })}\n`,
750 );
751 expect(yield* pending()).toBe(true);
752
753 // A low-priority-only trailing SYSTEM_MESSAGE does not hold the turn open.
754 yield* write(
755 ["logs", "transcript.jsonl"],
756 `${JSON.stringify({
757 step_index: 3,
758 type: "SYSTEM_MESSAGE",
759 status: "DONE",
760 content: "priority=MESSAGE_PRIORITY_LOW server restart notice",
761 })}\n`,
762 );
763 expect(yield* pending()).toBe(false);
764
765 // Corrupt read.json fails closed rather than treating messages as unread.
766 yield* write(["messages", "read.json"], "{not json");
767 expect(yield* pending()).toBe(false);
768
769 // Symlinked transcript fails closed.
770 const outside = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-pending-outside-" });
771 const external = path.join(outside, "transcript.jsonl");
772 yield* fs.writeFileString(
773 external,
774 `${JSON.stringify({ step_index: 4, type: "SYSTEM_MESSAGE", status: "DONE", content: "priority=MESSAGE_PRIORITY_HIGH" })}\n`,
775 );
776 const transcriptPath = path.join(
777 profile,
778 "antigravity-acp",
779 "brain",
780 ROOT,
781 ".system_generated",
782 "logs",
783 "transcript.jsonl",
784 );
785 yield* fs.remove(transcriptPath);
786 yield* fs.symlink(external, transcriptPath);
787 expect(yield* pending()).toBe(false);
788 }),
789 );
790});