Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AntigravityChildWork.test.ts

685 lines26.3 KB

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("shares one transcript budget across the batch", () =>
545 Effect.gen(function* () {
546 const filler = JSON.stringify({
547 step_index: 0,
548 type: "VIEW_FILE",
549 status: "DONE",
550 content: "x".repeat(1_000),
551 });
552 const transcript = `${Array.from({ length: 300 }, () => filler).join("\n")}\n`;
553 const { profile } = yield* makeProfile({
554 transcript,
555 steps: (logUri) => [
556 [1, 15, plannerStep(["call-a"])],
557 [
558 2,
559 127,
560 invokeStep({
561 callId: "call-a",
562 launches: Array.from({ length: 16 }, () => LAUNCH),
563 children: Array.from({ length: 16 }, () => ({ id: CHILD, logUri })),
564 }),
565 ],
566 ],
567 });
568 const children = yield* read(profile, `${ROOT}:1`);
569 expect(children).toHaveLength(16);
570 expect(children.every((child) => child.truncated)).toBe(true);
571 expect(JSON.stringify(children).length).toBeLessThan(600 * 1024);
572 }),
573 );
574​
575 it.effect(
576 "detects unread high-priority inbox wakes and trailing waking SYSTEM_MESSAGE steps",
577 () =>
578 Effect.gen(function* () {
579 const fs = yield* FileSystem.FileSystem;
580 const path = yield* Path.Path;
581 const profile = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-pending-reply-" });
582 const write = (segments: ReadonlyArray<string>, body: string) => {
583 const file = path.join(
584 profile,
585 "antigravity-acp",
586 "brain",
587 ROOT,
588 ".system_generated",
589 ...segments,
590 );
591 return fs
592 .makeDirectory(path.dirname(file), { recursive: true })
593 .pipe(Effect.andThen(fs.writeFileString(file, body)));
594 };
595 const pending = () =>
596 readAntigravityPendingReply({ profileDirectory: profile, sessionId: ROOT });
597​
598 // Empty profile or invalid session id fails closed.
599 expect(yield* pending()).toBe(false);
600 expect(
601 yield* readAntigravityPendingReply({ profileDirectory: profile, sessionId: "../escape" }),
602 ).toBe(false);
603​
604 // Low-priority unread notices (e.g. cancelled task / server restart) do not wake the agent.
605 yield* write(
606 ["messages", "low-1.json"],
607 JSON.stringify({ id: "low-1", priority: "MESSAGE_PRIORITY_LOW", sender: "system" }),
608 );
609 expect(yield* pending()).toBe(false);
610​
611 // An unread high-priority message indicates a queued wake.
612 yield* write(
613 ["messages", "high-1.json"],
614 JSON.stringify({
615 id: "high-1",
616 priority: "MESSAGE_PRIORITY_HIGH",
617 sender: `${ROOT}/task-1`,
618 }),
619 );
620 expect(yield* pending()).toBe(true);
621​
622 // Once marked read in read.json and followed by a completed PLANNER_RESPONSE, nothing is pending.
623 yield* write(["messages", "read.json"], JSON.stringify({ "high-1": true }));
624 yield* write(
625 ["logs", "transcript.jsonl"],
626 `${JSON.stringify({ step_index: 1, type: "PLANNER_RESPONSE", status: "DONE", content: "Done." })}\n`,
627 );
628 expect(yield* pending()).toBe(false);
629​
630 // A trailing waking SYSTEM_MESSAGE (even past a >64 KiB prefix) means the reply is in flight.
631 const filler = JSON.stringify({
632 step_index: 0,
633 type: "GENERIC",
634 status: "DONE",
635 content: "x".repeat(8_000),
636 });
637 yield* write(
638 ["logs", "transcript.jsonl"],
639 `${Array.from({ length: 12 }, () => filler).join("\n")}\n${JSON.stringify({
640 step_index: 2,
641 type: "SYSTEM_MESSAGE",
642 status: "DONE",
643 content: "priority=MESSAGE_PRIORITY_HIGH task-2 finished",
644 })}\n`,
645 );
646 expect(yield* pending()).toBe(true);
647​
648 // A low-priority-only trailing SYSTEM_MESSAGE does not hold the turn open.
649 yield* write(
650 ["logs", "transcript.jsonl"],
651 `${JSON.stringify({
652 step_index: 3,
653 type: "SYSTEM_MESSAGE",
654 status: "DONE",
655 content: "priority=MESSAGE_PRIORITY_LOW server restart notice",
656 })}\n`,
657 );
658 expect(yield* pending()).toBe(false);
659​
660 // Corrupt read.json fails closed rather than treating messages as unread.
661 yield* write(["messages", "read.json"], "{not json");
662 expect(yield* pending()).toBe(false);
663​
664 // Symlinked transcript fails closed.
665 const outside = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-pending-outside-" });
666 const external = path.join(outside, "transcript.jsonl");
667 yield* fs.writeFileString(
668 external,
669 `${JSON.stringify({ step_index: 4, type: "SYSTEM_MESSAGE", status: "DONE", content: "priority=MESSAGE_PRIORITY_HIGH" })}\n`,
670 );
671 const transcriptPath = path.join(
672 profile,
673 "antigravity-acp",
674 "brain",
675 ROOT,
676 ".system_generated",
677 "logs",
678 "transcript.jsonl",
679 );
680 yield* fs.remove(transcriptPath);
681 yield* fs.symlink(external, transcriptPath);
682 expect(yield* pending()).toBe(false);
683 }),
684 );
685});