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 readAntigravityChildWork,
15} from "./AntigravityChildWork.ts";
16import { sanitizeAntigravityToolPayload } from "./AntigravityProtocol.ts";
17import {
18 autoApproved,
19 CHILD,
20 invokeStep,
21 LAUNCH,
22 makeProfile,
23 plannerStep,
24 ROOT,
25 transcriptLines,
26} from "./AntigravityChildWork.testkit.ts";
27β
28const read = (
29 profileDirectory: string,
30 nativeTaskId: string,
31 launch: { readonly title: string | null; readonly prompt: string } = {
32 title: null,
33 prompt: "Readme check",
34 },
35 siblings: ReadonlyArray<{
36 readonly nativeTaskId: string;
37 readonly title: string | null;
38 readonly prompt: string;
39 }> = [],
40) =>
41 readAntigravityChildWork({
42 profileDirectory,
43 rootSessionId: ROOT,
44 nativeTaskId,
45 launch,
46 siblings,
47 });
48β
49it.layer(NodeServices.layer)("readAntigravityChildWork", (it) => {
50 it.effect("follows an auto-approved call id through its planner step to the record", () =>
51 Effect.gen(function* () {
52 const { profile } = yield* makeProfile({ steps: autoApproved });
53 const [child, ...rest] = yield* read(profile, `${ROOT}:1`);
54 expect(rest).toEqual([]);
55 expect(child).toMatchObject({
56 conversationId: CHILD,
57 role: LAUNCH.role,
58 prompt: LAUNCH.prompt,
59 truncated: false,
60 });
61 // The launch envelope repeats the prompt shown above, so the steps start with the child's work.
62 expect(child?.steps?.map((step) => step.text ?? step.toolCalls[0]?.name)).toEqual([
63 "view_file",
64 "2: child read marker 4242",
65 "marker 4242 found",
66 ]);
67 expect(child?.steps?.[0]?.toolCalls[0]?.input).toBe('{"AbsolutePath":"/project/README.md"}');
68 }),
69 );
70β
71 it.effect("needs proof that the call id belongs to the parent's record", () =>
72 Effect.gen(function* () {
73 const { profile } = yield* makeProfile({
74 steps: (logUri) => [
75 ...autoApproved(logUri),
76 [5, 15, plannerStep(["call-b", "call-c"])],
77 [
78 6,
79 127,
80 invokeStep({ callId: "call-b", launches: [LAUNCH], children: [{ id: CHILD, logUri }] }),
81 ],
82 [
83 7,
84 127,
85 invokeStep({ callId: "call-c", launches: [LAUNCH], children: [{ id: CHILD, logUri }] }),
86 ],
87 ],
88 });
89 // Another session's id, a step that is not the planner call, and parallel calls that share one id.
90 expect(yield* read(profile, `00000000-0000-4000-8000-000000000000:1`)).toEqual([]);
91 expect(yield* read(profile, `${ROOT}:2`)).toEqual([]);
92 expect(yield* read(profile, `${ROOT}:5`)).toEqual([]);
93 }),
94 );
95β
96 it.effect("matches a permission-prompt call by its launch text, only when unique", () =>
97 Effect.gen(function* () {
98 const other = { role: "Test Runner", prompt: "Run the tests" };
99 const long = { role: "Long Reader", prompt: `Read this:\nπ${"x".repeat(7_999)}` };
100 // A role's leading byte order mark is part of its text.
101 const marked = { role: "\uFEFFMarked", prompt: "Check the mark" };
102 const { profile } = yield* makeProfile({
103 steps: (logUri) => [
104 [
105 2,
106 127,
107 invokeStep({ callId: "x", launches: [LAUNCH], children: [{ id: CHILD, logUri }] }),
108 ],
109 [
110 8,
111 127,
112 invokeStep({ callId: "w", launches: [long], children: [{ id: CHILD, logUri }] }),
113 ],
114 [
115 10,
116 127,
117 invokeStep({ callId: "v", launches: [marked], children: [{ id: CHILD, logUri }] }),
118 ],
119 [
120 4,
121 127,
122 invokeStep({ callId: "y", launches: [other], children: [{ id: CHILD, logUri }] }),
123 ],
124 [
125 6,
126 127,
127 invokeStep({ callId: "z", launches: [other], children: [{ id: CHILD, logUri }] }),
128 ],
129 ],
130 });
131 const opaque = "35bea692fa95447fbdae6333fec5515f";
132 const matched = yield* read(profile, opaque, describeAntigravitySubagentLaunches([LAUNCH]));
133 expect(matched.map((child) => child.role)).toEqual([LAUNCH.role]);
134 // T3 knows a second batch with this text that the agent has not recorded yet.
135 const twin = { nativeTaskId: "f00d", ...describeAntigravitySubagentLaunches([LAUNCH]) };
136 expect(
137 yield* read(profile, opaque, describeAntigravitySubagentLaunches([LAUNCH]), [twin]),
138 ).toEqual([]);
139 // T3 stores the launch from the bounded tool payload, which keeps only a long prompt's tail.
140 const stored = antigravitySubagentLaunches(
141 sanitizeAntigravityToolPayload({ Subagents: [{ Role: long.role, Prompt: long.prompt }] }),
142 );
143 const longMatch = yield* read(profile, opaque, describeAntigravitySubagentLaunches(stored!));
144 expect(longMatch.map((child) => child.prompt)).toEqual([long.prompt]);
145 const savedLaunch = {
146 title: long.role,
147 prompt: `[Earlier output truncated]\n\n\uDE80${"x".repeat(7_999)}`,
148 };
149 expect((yield* read(profile, opaque, savedLaunch)).map((child) => child.prompt)).toEqual([
150 long.prompt,
151 ]);
152 expect(
153 yield* read(profile, opaque, describeAntigravitySubagentLaunches([marked])),
154 ).toHaveLength(1);
155 expect(yield* read(profile, opaque, { title: "Marked", prompt: marked.prompt })).toEqual([]);
156 expect(yield* read(profile, opaque, describeAntigravitySubagentLaunches([other]))).toEqual(
157 [],
158 );
159 expect(yield* read(profile, opaque, { title: null, prompt: "Readme check" })).toEqual([]);
160 }),
161 );
162β
163 it.effect("leaves an auto-approved batch's record out of a launch-text match", () =>
164 Effect.gen(function* () {
165 const { profile } = yield* makeProfile({ steps: autoApproved });
166 const launch = describeAntigravitySubagentLaunches([LAUNCH]);
167 const opaque = "35bea692fa95447fbdae6333fec5515f";
168 expect(yield* read(profile, opaque, launch)).toHaveLength(1);
169 // An earlier auto-approved batch stored no launch text, but its planner step claims the record.
170 const auto = {
171 nativeTaskId: `${ROOT}:1`,
172 title: ANTIGRAVITY_SUBAGENT_BATCH_TITLE,
173 prompt: "",
174 };
175 expect(yield* read(profile, opaque, launch, [auto])).toEqual([]);
176 // A sibling that cannot be ruled out refuses the match: its planner step is unreadable,
177 // or it is a permission batch whose launch text is missing or cut.
178 for (const sibling of [
179 { ...auto, nativeTaskId: `${ROOT}:99` },
180 { nativeTaskId: "0ld", title: ANTIGRAVITY_SUBAGENT_BATCH_TITLE, prompt: "Running" },
181 // Its stored launch was cut, so it may be this same launch.
182 { nativeTaskId: "cut", title: LAUNCH.role, prompt: "[Earlier output truncated]\n\nmarker" },
183 { nativeTaskId: "cut", title: "[Earlier output truncated]\n\nReader", prompt: "x" },
184 { nativeTaskId: "cut", title: null, prompt: "[Earlier output truncated]\n\nx" },
185 ]) {
186 expect(yield* read(profile, opaque, launch, [sibling])).toEqual([]);
187 }
188 // A cut prompt under different roles is another launch.
189 const other = {
190 nativeTaskId: "cut",
191 title: "Test Runner",
192 prompt: "[Earlier output truncated]\n\nx",
193 };
194 expect(yield* read(profile, opaque, launch, [other])).toHaveLength(1);
195 }),
196 );
197β
198 it.effect("reads no transcript outside the child's own profile path", () =>
199 Effect.gen(function* () {
200 const fs = yield* FileSystem.FileSystem;
201 const path = yield* Path.Path;
202 const outside = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-outside-" });
203 const secret = path.join(outside, "transcript.jsonl");
204 yield* fs.writeFileString(secret, JSON.stringify(transcriptLines[3]) + "\n");
205 const named = yield* makeProfile({
206 steps: () => autoApproved(NodeURL.pathToFileURL(secret).href),
207 });
208 const [namedChild] = yield* read(named.profile, `${ROOT}:1`);
209 expect(namedChild?.role).toBe(LAUNCH.role);
210 expect(namedChild?.steps).toBeNull();
211β
212 const linked = yield* makeProfile({ steps: autoApproved });
213 yield* fs.remove(linked.transcriptPath);
214 yield* fs.symlink(secret, linked.transcriptPath);
215 const [linkedChild] = yield* read(linked.profile, `${ROOT}:1`);
216 expect(linkedChild?.steps).toBeNull();
217 }),
218 );
219β
220 it.effect("reads only the tail of a large transcript", () =>
221 Effect.gen(function* () {
222 const filler = JSON.stringify({
223 step_index: 0,
224 type: "VIEW_FILE",
225 status: "DONE",
226 content: "x".repeat(10_000),
227 });
228 const { profile } = yield* makeProfile({
229 steps: autoApproved,
230 transcript: `${Array.from({ length: 40 }, () => filler).join("\n")}\n${JSON.stringify(transcriptLines[3])}\n`,
231 });
232 const [child] = yield* read(profile, `${ROOT}:1`);
233 expect(child?.truncated).toBe(true);
234 expect(child?.steps?.length).toBeLessThan(40);
235 expect(child?.steps?.at(-1)?.text).toBe("marker 4242 found");
236 expect(child?.steps?.[0]?.text?.length).toBeLessThanOrEqual(4_001);
237 }),
238 );
239β
240 it.effect("refuses links between children and sessions inside the same profile", () =>
241 Effect.gen(function* () {
242 const fs = yield* FileSystem.FileSystem;
243 const path = yield* Path.Path;
244 const sibling = "b468c0e1d2f34a5b6c7d8e9f0a1b2c3d";
245 // The record names this child's literal path, but the child directory links to a sibling.
246 const linked = yield* makeProfile({ steps: autoApproved });
247 const brain = path.join(linked.profile, "antigravity-acp", "brain");
248 yield* fs.rename(path.join(brain, CHILD), path.join(brain, sibling));
249 yield* fs.symlink(path.join(brain, sibling), path.join(brain, CHILD));
250 const [child] = yield* read(linked.profile, `${ROOT}:1`);
251 expect(child?.role).toBe(LAUNCH.role);
252 expect(child?.steps).toBeNull();
253β
254 // This session's database links to another session's records.
255 const other = yield* makeProfile({ steps: autoApproved });
256 const conversations = path.join(other.profile, "antigravity-acp", "conversations");
257 const peer = path.join(conversations, "00000000-0000-4000-8000-000000000000.db");
258 yield* fs.rename(path.join(conversations, `${ROOT}.db`), peer);
259 yield* fs.symlink(peer, path.join(conversations, `${ROOT}.db`));
260 expect(yield* read(other.profile, `${ROOT}:1`)).toEqual([]);
261 }),
262 );
263β
264 it.effect("declines a launch-text match it cannot prove unique within its scan bounds", () =>
265 Effect.gen(function* () {
266 const record = (callId: string, logUri: string) =>
267 invokeStep({ callId, launches: [LAUNCH], children: [{ id: CHILD, logUri }] });
268 const other = { role: "Test Runner", prompt: "Run the tests" };
269 const filler = (idx: number, logUri: string) =>
270 [
271 idx,
272 127,
273 invokeStep({ callId: `f${idx}`, launches: [other], children: [{ id: CHILD, logUri }] }),
274 ] as const;
275 const opaque = "35bea692fa95447fbdae6333fec5515f";
276 const launch = describeAntigravitySubagentLaunches([LAUNCH]);
277 const cases = [
278 // More records than one open may scan.
279 (logUri: string) => [
280 [1, 127, record("x", logUri)] as const,
281 ...Array.from({ length: 200 }, (_, index) => filler(index + 2, logUri)),
282 ],
283 // An oversized record could hold an identical launch.
284 (logUri: string) => [
285 [1, 127, record("x", logUri)] as const,
286 [2, 127, new Uint8Array(1024 * 1024 + 1)] as const,
287 ],
288 // So could one this reader cannot decode.
289 (logUri: string) => [
290 [1, 127, record("x", logUri)] as const,
291 [2, 127, Uint8Array.from([0xff, 0xff])] as const,
292 ],
293 ];
294 for (const steps of cases) {
295 const { profile } = yield* makeProfile({ steps });
296 expect(yield* read(profile, opaque, launch)).toEqual([]);
297 }
298 }),
299 );
300β
301 it.effect("keeps the batch view for a batch over the child limit", () =>
302 Effect.gen(function* () {
303 const { profile } = yield* makeProfile({
304 steps: (logUri) => [
305 [1, 15, plannerStep(["call-a"])],
306 [
307 2,
308 127,
309 invokeStep({
310 callId: "call-a",
311 launches: Array.from({ length: 17 }, () => LAUNCH),
312 children: Array.from({ length: 17 }, () => ({ id: CHILD, logUri })),
313 }),
314 ],
315 ],
316 });
317 expect(yield* read(profile, `${ROOT}:1`)).toEqual([]);
318 }),
319 );
320β
321 it.effect("follows a detached 1.5 launch id through the child's inbox to its transcript", () =>
322 Effect.gen(function* () {
323 const fs = yield* FileSystem.FileSystem;
324 const path = yield* Path.Path;
325 const profile = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-detached-" });
326 const sibling = "b468c0e1-d2f3-4a5b-6c7d-8e9f0a1b2c3d";
327 const writeJson = (segments: ReadonlyArray<string>, value: unknown) => {
328 const file = path.join(profile, "antigravity-acp", "brain", ...segments);
329 return fs
330 .makeDirectory(path.dirname(file), { recursive: true })
331 .pipe(Effect.andThen(fs.writeFileString(file, JSON.stringify(value))));
332 };
333 const writeTranscript = (
334 conversationId: string,
335 lines: ReadonlyArray<Record<string, unknown>>,
336 ) => {
337 const file = path.join(
338 profile,
339 "antigravity-acp",
340 "brain",
341 conversationId,
342 ".system_generated",
343 "logs",
344 "transcript.jsonl",
345 );
346 return fs
347 .makeDirectory(path.dirname(file), { recursive: true })
348 .pipe(
349 Effect.andThen(
350 fs.writeFileString(file, lines.map((line) => JSON.stringify(line)).join("\n") + "\n"),
351 ),
352 );
353 };
354β
355 // Matches real agy 1.5.12 records (no legacy step_type=127 database row).
356 yield* writeJson([ROOT, ".system_generated", "subagents", `${CHILD}.json`], {
357 conversationId: CHILD,
358 subagentDescriptor: { typeName: "research", role: LAUNCH.role },
359 state: "SUBAGENT_STATE_ALIVE",
360 });
361 yield* writeJson([CHILD, ".system_generated", "messages", "launch.json"], {
362 sender: ROOT,
363 content: LAUNCH.prompt,
364 sourceMetadata: {
365 tool: {
366 conversationId: ROOT,
367 stepIndex: 2,
368 toolCall: {
369 id: "call_11340266277043349041",
370 name: "invoke_subagent",
371 argumentsJson: JSON.stringify({
372 TypeName: "research",
373 Role: LAUNCH.role,
374 Prompt: LAUNCH.prompt,
375 }),
376 },
377 },
378 },
379 });
380 yield* writeJson([CHILD, ".system_generated", "messages", "read.json"], { launch: true });
381 yield* writeTranscript(CHILD, [
382 {
383 step_index: 0,
384 type: "SYSTEM_MESSAGE",
385 status: "DONE",
386 content: `<SYSTEM_MESSAGE>\n[Message] sender=${ROOT} content=${LAUNCH.prompt}\n</SYSTEM_MESSAGE>`,
387 },
388 {
389 step_index: 1,
390 type: "PLANNER_RESPONSE",
391 status: "DONE",
392 tool_calls: [{ name: "read_file", args: { Path: '"/project/README.md"' } }],
393 },
394 {
395 step_index: 2,
396 type: "GENERIC",
397 status: "DONE",
398 content: "2: MAGIC_TOKEN=probe-38478-ok",
399 },
400 ]);
401β
402 // A second detached child without argumentsJson falls back to descriptor role + message content.
403 yield* writeJson([ROOT, ".system_generated", "subagents", `${sibling}.json`], {
404 conversationId: sibling,
405 subagentDescriptor: { typeName: "research", role: "Line Counter" },
406 });
407 yield* writeJson([sibling, ".system_generated", "messages", "launch.json"], {
408 sender: ROOT,
409 content: "Count lines in README.md",
410 sourceMetadata: {
411 tool: {
412 toolCall: { id: "call_22340266277043349042", name: "invoke_subagent" },
413 },
414 },
415 });
416 // A follow-up send_message must not be treated as a launch.
417 yield* writeJson([sibling, ".system_generated", "messages", "followup.json"], {
418 sender: ROOT,
419 content: "Also check LICENSE",
420 sourceMetadata: {
421 tool: {
422 toolCall: { id: "call_followup", name: "send_message" },
423 },
424 },
425 });
426β
427 const [first, ...firstRest] = yield* read(profile, "call_11340266277043349041", {
428 title: LAUNCH.role,
429 prompt: LAUNCH.prompt,
430 });
431 expect(firstRest).toEqual([]);
432 expect(first).toMatchObject({
433 conversationId: CHILD,
434 role: LAUNCH.role,
435 prompt: LAUNCH.prompt,
436 truncated: false,
437 });
438 expect(first?.steps?.map((step) => step.text ?? step.toolCalls[0]?.name)).toEqual([
439 "read_file",
440 "2: MAGIC_TOKEN=probe-38478-ok",
441 ]);
442 expect(first?.steps?.[0]?.toolCalls[0]?.input).toBe('{"Path":"/project/README.md"}');
443β
444 // Missing transcript still returns the proven child with steps: null.
445 const [second] = yield* read(profile, "call_22340266277043349042", {
446 title: "Line Counter",
447 prompt: "Count lines in README.md",
448 });
449 expect(second).toEqual({
450 conversationId: sibling,
451 role: "Line Counter",
452 prompt: "Count lines in README.md",
453 steps: null,
454 truncated: false,
455 });
456β
457 // Unknown id and send_message id return nothing.
458 expect(yield* read(profile, "call_unknown")).toEqual([]);
459 expect(yield* read(profile, "call_followup")).toEqual([]);
460β
461 // Another child claiming the same toolCall id makes ownership ambiguous.
462 yield* writeJson([sibling, ".system_generated", "messages", "dup.json"], {
463 sender: ROOT,
464 content: LAUNCH.prompt,
465 sourceMetadata: {
466 tool: {
467 toolCall: { id: "call_11340266277043349041", name: "invoke_subagent" },
468 },
469 },
470 });
471 expect(yield* read(profile, "call_11340266277043349041")).toEqual([]);
472 }),
473 );
474β
475 it.effect("shares one transcript budget across the batch", () =>
476 Effect.gen(function* () {
477 const filler = JSON.stringify({
478 step_index: 0,
479 type: "VIEW_FILE",
480 status: "DONE",
481 content: "x".repeat(1_000),
482 });
483 const transcript = `${Array.from({ length: 300 }, () => filler).join("\n")}\n`;
484 const { profile } = yield* makeProfile({
485 transcript,
486 steps: (logUri) => [
487 [1, 15, plannerStep(["call-a"])],
488 [
489 2,
490 127,
491 invokeStep({
492 callId: "call-a",
493 launches: Array.from({ length: 16 }, () => LAUNCH),
494 children: Array.from({ length: 16 }, () => ({ id: CHILD, logUri })),
495 }),
496 ],
497 ],
498 });
499 const children = yield* read(profile, `${ROOT}:1`);
500 expect(children).toHaveLength(16);
501 expect(children.every((child) => child.truncated)).toBe(true);
502 expect(JSON.stringify(children).length).toBeLessThan(600 * 1024);
503 }),
504 );
505});