@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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