Repository navigation
Feat/antigravity adapter - #3
nandinirathod2321 wants to merge 1 commit into
Conversation
83e90cf to
49c9ad1
Compare
Neal006
left a comment
There was a problem hiding this comment.
Thanks for taking this on. The FIFO pairing of parallel tool_calls is the hard part of this format and it is right, the registry wiring is clean, and CI is green on all 9 jobs.
CI can only tell us that the 3 new tests pass, so I wrote a deterministic check matrix for this adapter and ran it against this branch (49c9ad1, up to date with main). 22 of 146 applicable cells fail. They reduce to 9 root causes, each a few lines to fix. Severity, evidence and suggested code are in the inline comments; the harness (so you can run it yourself) and a candidate patch are in the next comment.
Status: not ready to merge yet. F1 and F2 are blocking, F3 to F5 should be fixed, F6 is cheap hardening, and F7 to F9 (†) need one look at a real capture.
Matrix
Parse: scenario × invariant
| scenario | no-throw | pairing | keep | ids | times | simulate | labels | targets | no phantom reruns |
|---|---|---|---|---|---|---|---|---|---|
| PR fixture (real-session.jsonl) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ✅ | · |
| 1 call | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | · | · | · |
| 3 parallel calls | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | · | · | · |
| empty output, 1st of 2 | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | · | · | · |
| empty output, 2nd of 3 | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | · | · | · |
| empty output, last | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | · | · | · |
| text + tool call in one turn | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | · | · | · |
| final answer + tool_calls: [] | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | · | · | · |
| interrupted turn | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | · | · | · |
| bookkeeping records interleaved | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | · | · | · |
| typed result records † | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | · | · | · |
| result with no pending call | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | · | · | · |
| CRLF line endings | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | · | · | · |
| empty file | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | · | · | · |
| garbage + truncated JSON lines | ✅ | · | ✅ | · | · | ✅ | · | · | · |
| a line that is JSON null | ❌ | · | · | · | · | · | · | · | · |
| tool_calls entry is null | ❌ | · | · | · | · | · | · | · | · |
| unparseable created_at | ✅ | ✅ | ✅ | ✅ | ❌ | ✅ | · | · | · |
| no step_index on records | ✅ | ❌ | ✅ | ❌ | ✅ | ✅ | · | · | · |
| 16 different files, read once each | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ |
| a.ts, a.ts again, b.ts | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | · |
| 3 different commands | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | · |
Discovery: on-disk layout × invariant
| scenario | finds each conversation | one file per conversation | only transcripts |
|---|---|---|---|
| transcript.jsonl + sibling *.md artifacts | ✅ | ✅ | ✅ |
| two conversations | ✅ | ✅ | ✅ |
| transcript.jsonl + transcript_full.jsonl † | ✅ | ❌ | ✅ |
Wiring: registry + default dir
| scenario | registered | case-insensitive | listed in errors | ids unique + flag-safe | home default | env override | CLI root reachable † |
|---|---|---|---|---|---|---|---|
| registry | ✅ | ✅ | ✅ | ✅ | · | · | · |
| default dir | · | · | · | · | ✅ | ✅ | ❌ |
CLI end to end: deja audit --agent antigravity
| scenario | exits 0, 1 session, 3 results | report names files + commands |
|---|---|---|
| PR fixture | ✅ | ❌ |
124 ok · 22 FAIL (· = not applicable)
Rows are scenarios (synthetic logs shaped like your fixture, on-disk layouts, wiring, the built CLI) and columns are invariants. · = not applicable. † = rests on third-party documentation of the on-disk format (I found no vendor spec, only third-party write-ups), so please confirm it against a real capture before treating it as a hard requirement.
It is deterministic: fixed timestamps, no randomness, no network, no wall clock, temp dirs only. Two consecutive runs give byte-identical output (about 1.5 s).
What to fix
| ID | Severity | Problem | Cells | Where |
|---|---|---|---|---|
| F1 | blocking | Antigravity's arg keys (Path, CommandLine) never reach the keys deja reads (path, command), so every call is labelled read_file result / run_command result: one target for all files, the report cannot name a file, and simulate() reports re-runs of files that were read once |
9 | L88-104 |
| F2 | blocking | parse() throws on a null line and on a null entry in tool_calls. agents/index.ts says "Must never throw", and one stray line silently removes the whole conversation from the audit |
2 | L55-60 |
| F3 | should fix | A result record with empty content does not consume its pending call, so every later result in that turn lands on the wrong call |
2 | L125-127 |
| F4 | should fix | Assistant text is dropped whenever tool_calls is an array (even []) |
2 | L113-115 |
| F5 | should fix | An unparseable created_at pushes NaN into times; the biller then treats a cold cache as warm |
1 | L62-66 |
| F6 | hardening | No step_index makes every id call_0_0: duplicate tool_use ids, wrong pairing |
2 | L85 |
| F7 | confirm † | Only GENERIC counts as tool output; third-party docs also list typed result records |
2 | L124 |
| F8 | confirm † | .jsonl also matches transcript_full.jsonl, so one conversation is audited twice |
1 | L153 |
| F9 | confirm † | The default dir reaches the editor store but not the CLI's | 1 | L155-158 |
Already solid (all ✅)
FIFO pairing across parallel calls, interrupted turns, bookkeeping records interleaved between calls, CRLF, garbage and truncated JSON lines, an empty file, .md artifacts ignored by discovery, two conversations in one tree, the registry (case-insensitive, listed in errors, unique flag-safe ids), the GEMINI_HOME override, and the CLI end to end (exit 0, 1 session, 3 results).
Two asks
- Fixture provenance, and a real-capture check for F7 to F9. The description says "real anonymized session". Which Antigravity product and version produced it (CLI or editor)? From one real session, could you paste the output of these two commands (record types and file names only, no content)?
jq -r .type transcript.jsonl | sort | uniq -c ls <conversation>/.system_generated/logs/
- CONTRIBUTING rule 3 ("Measure, don't guess"). Please paste the summary lines of
deja audit --agent antigravityon a real session (no conversation content). It matters here because fixing F1 changes the totals: the phantom re-runs go away.
Small stuff
- PR title
Feat/antigravity adaptercould befeat(audit): add Google Antigravity adapter(CONTRIBUTING asks for conventional commit prefixes, and your commit already has one). - The current tests cover the happy path on one fixture. Once the fixes are in, please keep the matrix (or a trimmed version) as the regression suite; it would also make a good template for the other adapter PRs.
- README L114 and L234 only mention Claude Code and Codex (optional follow-up).
Raw failing cells (generated by the harness)
- PR fixture (real-session.jsonl) × labels: 3/3 calls get a label that does not say which file/command: "run_command result" for "git status"
- empty output, 1st of 2 × pairing: call 1 (run_command "mkdir -p build") is given output "On branch main"; the log says ""
- empty output, 2nd of 3 × pairing: call 2 (run_command "mkdir -p build") is given output "export const b_0 = compute(0…" [2739 chars]; the log says ""
- text + tool call in one turn × keep: 1 log string(s) silently dropped, e.g. "Let me check the config."
- final answer + tool_calls: [] × keep: 1 log string(s) silently dropped, e.g. "All done."
- typed result records † × pairing: call 1 (run_command "git status") is given output ""; the log says "On branch main"
- typed result records † × keep: 2 log string(s) silently dropped, e.g. "On branch main"
- a line that is JSON null × no-throw: parse() threw: Cannot read properties of null (reading 'created_at') (index.ts: "Must never throw")
- tool_calls entry is null × no-throw: parse() threw: Cannot read properties of null (reading 'name') (index.ts: "Must never throw")
- unparseable created_at × times: non-finite entry in times: [null]
- no step_index on records × pairing: call 1 (read_file "src/a.ts") is given output "export const a_0 = compute(0…" [5478 chars]; the log says "export const a_0 = compute(0…" [2739 chars]
- no step_index on records × ids: duplicate tool_use id(s): call_0_0
- 16 different files, read once each × labels: 16/16 calls get a label that does not say which file/command: "read_file result" for "src/m0.ts"
- 16 different files, read once each × targets: 1 distinct target(s) instead of 16: "read_file result"
- 16 different files, read once each × no phantom reruns: deja reports 11 re-run(s) of stubbed output although no file is read twice
- a.ts, a.ts again, b.ts × labels: 3/3 calls get a label that does not say which file/command: "read_file result" for "src/a.ts"
- a.ts, a.ts again, b.ts × targets: 1 distinct target(s) instead of 2: "read_file result"
- 3 different commands × labels: 3/3 calls get a label that does not say which file/command: "run_command result" for "git status"
- 3 different commands × targets: 1 distinct target(s) instead of 3: "run_command result"
- transcript.jsonl + transcript_full.jsonl † × one file per conversation: c1: transcript.jsonl + transcript_full.jsonl would be audited as 2 sessions
- default dir × CLI root reachable †: with only ~/.gemini/antigravity-cli/brain on disk, the default dir finds 0 conversations
- PR fixture × report names files + commands: "context hogs" lists "read_file result", "run_command result"
| // Parse stringified args if necessary | ||
| let parsedArgs = call.args ?? {}; | ||
| if (typeof parsedArgs === "object" && parsedArgs !== null) { | ||
| const clean: Record<string, unknown> = {}; | ||
| for (const [k, v] of Object.entries(parsedArgs)) { | ||
| if (typeof v === "string" && v.startsWith('"') && v.endsWith('"')) { | ||
| try { | ||
| clean[k] = JSON.parse(v); | ||
| } catch { | ||
| clean[k] = v; | ||
| } | ||
| } else { | ||
| clean[k] = v; | ||
| } | ||
| } | ||
| parsedArgs = clean; | ||
| } |
There was a problem hiding this comment.
[F1 blocking] Arg keys are not mapped to the keys deja reads.
Matrix cells: labels, targets, no phantom reruns (9 cells, see the table).
You already decode the JSON-encoded values (good), but the keys stay Path / CommandLine. toolLabel (src/core/labels.ts) only looks at command|cmd, file_path|path|filePath|target_file|absolute_path|notebook_path, pattern|query|regex and url, and otherwise falls back to "<name> result". On your own fixture that means:
deja audit"context hogs" listsread_file resultandrun_command result: no file or command is named.- 16 different files, each read once, collapse into 1 target, and
simulate()reports 11 re-runs. Withpathas the key it is 16 targets and 0 re-runs.
Fix: rename the known keys while decoding.
const ARG_ALIAS: Record<string, string> = { Path: "path", CommandLine: "command" };
// ...inside the decode loop
out[ARG_ALIAS[k] ?? k] = decoded;Extend the map for other tools' keys once you have seen them in a real log (I only know these two, from your fixture).
| let step: StepEnvelope; | ||
| try { | ||
| step = JSON.parse(raw) as StepEnvelope; | ||
| } catch { | ||
| continue; | ||
| } |
There was a problem hiding this comment.
[F2 blocking] parse() throws on valid JSON that is not an object.
Matrix cells: a line that is JSON null x no-throw, tool_calls entry is null x no-throw.
JSON.parse("null") is null, so step.created_at (L62) throws; a [null] in tool_calls throws at call.name (L86). agents/index.ts says "Must never throw", and the worker pool turns a throw into a silently skipped session. I put a single null line into your fixture: deja audit reports sessions=0 (1 session / 3 requests without it) and prints no warning.
if (step === null || typeof step !== "object") continue;
// ...
for (const call of Array.isArray(step.tool_calls) ? step.tool_calls : []) {
if (!call || typeof call.name !== "string") continue;FYI the Claude and Codex parsers (transcript.ts, codex.ts) have the same hole for a null line. That is pre-existing and not from this PR, and worth its own fix, but let's not add a third copy.
| const content = step.content ?? ""; | ||
| if (pendingCalls.length > 0 && content) { | ||
| const nextCall = pendingCalls.shift()!; |
There was a problem hiding this comment.
[F3 should fix] An empty result does not consume its call, so every later result shifts.
Matrix cells: empty output, 1st of 2 x pairing, empty output, 2nd of 3 x pairing.
Pairing is positional (as your header comment says), so a record that answers a call has to pop it even when content is empty (mkdir, git add, touch print nothing). With && content the record is skipped and the next output is attached to the wrong call; in the matrix mkdir -p build ends up with the next command's output (On branch main). The independent Agent Sessions parser pops for every result record, including empty or missing content.
const next = pendingCalls.shift();
if (next) { /* push tool_result with content: step.content ?? "" */ }Caveat: I cannot confirm from a real capture that an empty-output command is logged as an empty-content record rather than omitted. If you have one, that settles it.
| } else if (step.content) { | ||
| blocks.push({ type: "text", text: step.content }); | ||
| } |
There was a problem hiding this comment.
[F4 should fix] Assistant text is dropped when the record has tool_calls.
Matrix cells: text + tool call in one turn x keep, final answer + tool_calls: [] x keep.
if (tool_calls is an array) {...} else if (content) {...} loses narration like "Let me check the config." when it sits in the same PLANNER_RESPONSE as a call, and a final answer that carries tool_calls: [] loses its text entirely. That text is part of the prefix the model re-reads every turn, so prompt size is undercounted. The Agent Sessions parser keeps both (text from content, plus one event per call).
if (step.content) blocks.push({ type: "text", text: step.content });
for (const call of Array.isArray(step.tool_calls) ? step.tool_calls : []) { /* ... */ }| const ts = step.created_at ? Date.parse(step.created_at) : undefined; | ||
| if (ts !== undefined && Number.isFinite(ts)) { | ||
| t.start = t.start === undefined ? ts : Math.min(t.start, ts); | ||
| t.end = t.end === undefined ? ts : Math.max(t.end, ts); | ||
| } |
There was a problem hiding this comment.
[F5 should fix] An unparseable created_at leaks NaN into times.
Matrix cell: unparseable created_at x times.
t.start / t.end are guarded with Number.isFinite (L63), but ts itself is what gets pushed to times (L77, L122, L137). The Claude and Codex parsers turn an unparseable stamp into undefined. With NaN, time - lastTime > ttlMs is always false, so the biller treats a cold cache as warm. Repro: 8 requests 10 minutes apart with one tool result stamped "yesterday" moves the simulated baseline cost from 222,305 to 174,105 token-equivalents (-22%, cachedTokens 0 to 41,913).
const parsed = step.created_at ? Date.parse(step.created_at) : Number.NaN;
const ts = Number.isFinite(parsed) ? parsed : undefined;| if (step.tool_calls && Array.isArray(step.tool_calls)) { | ||
| for (let idx = 0; idx < step.tool_calls.length; idx++) { | ||
| const call = step.tool_calls[idx]!; | ||
| const callId = `call_${step.step_index ?? 0}_${idx}`; |
There was a problem hiding this comment.
[F6 hardening] A missing step_index makes every id call_0_0.
Matrix cells: no step_index on records x pairing, x ids.
step.step_index ?? 0 produces duplicate tool_use ids across turns, and results then pair to the wrong call. step_index is part of the record shape the guide documents, so this is cheap insurance rather than a likely bug: fall back to a running counter, e.g. step.step_index ?? `n${planSeq++}`.
| }); | ||
| times.push(ts); | ||
| } | ||
| } else if (step.type === "GENERIC") { |
There was a problem hiding this comment.
[F7 confirm against a real capture †] Only GENERIC counts as a tool result.
Matrix cells: typed result records † x pairing, x keep.
Third-party sources disagree about GENERIC:
- the Agent Sessions guide lists
RUN_COMMAND,VIEW_FILE,LIST_DIRECTORY,GREP_SEARCH,SEARCH_WEBandCODE_ACTIONas the records that carry tool output (incontent), and describesGENERICas "bookkeeping"; - its parser source treats those types and
GENERICas tool output.
If your logs use typed result records, every such output is dropped today: calls without results and understated tool-result tokens. A fix that holds under either reading is to accept a small set of result types (GENERIC plus the six above) instead of === "GENERIC". The jq -r .type ... | uniq -c check from the review summary ("Two asks") settles which one is true.
| export const antigravityAdapter: AgentAdapter = { | ||
| id: "antigravity", | ||
| name: "Google Antigravity", | ||
| extensions: [".jsonl"], |
There was a problem hiding this comment.
[F8 confirm †] .jsonl also matches transcript_full.jsonl.
Matrix cell: transcript.jsonl + transcript_full.jsonl † x one file per conversation.
Per the guide, Antigravity clips long tool output in transcript.jsonl (clipped fields are named in truncated_fields) and keeps the complete text in a sibling transcript_full.jsonl with the same records. With extensions: [".jsonl"] both are discovered, so one conversation is audited twice (2 sessions, doubled requests and savings), and the clipped copy under-counts the very tool output deja is measuring.
Suggestion: one file per conversation, preferring transcript_full.jsonl and falling back to transcript.jsonl. PR #4 (the Cline adapter) adds exactFilename to discoverTranscripts; pinning a single name would be trivial once that lands, but "prefer full, fall back" needs a few lines of its own. ls of one logs dir tells us whether both files exist on a real install.
| defaultDir(env = process.env): string { | ||
| const gemini = env.GEMINI_HOME || join(homedir(), ".gemini"); | ||
| return join(gemini, "antigravity", "brain"); | ||
| }, |
There was a problem hiding this comment.
[F9 confirm †] The default dir only reaches ~/.gemini/antigravity/brain.
Matrix cell: default dir x CLI root reachable †. With only ~/.gemini/antigravity-cli/brain on disk, --agent antigravity without --dir finds 0 conversations and prints "No Google Antigravity transcripts found".
Per the guide and the Agent Sessions discovery code, the CLI keeps its transcripts under ~/.gemini/antigravity-cli/brain/<id>/.system_generated/logs/ and the editor uses ~/.gemini/antigravity/brain, so there are two roots and this reaches one. Since defaultDir() returns a single directory, a pragmatic option is "the CLI root if it exists, else the editor root"; --dir covers everything else.
nit: I could not find GEMINI_HOME documented for Antigravity (antigravity-cli#155 is an open feature request for a relocation variable). It mirrors the CODEX_HOME override in the Codex adapter. Fine to keep as a deja-side override, just do not document it as Antigravity's.
Reproduce the matrixSave the file below as npm run build && npx vitest run test/antigravity.matrix.test.ts
# MATRIX_OUT=matrix.md also writes the Markdown tablesThe CLI cells are skipped when test/antigravity.matrix.test.ts (25 KB)/**
* Deterministic checker matrix for the Antigravity adapter.
*
* Rows are scenarios (synthetic logs, on-disk layouts, the CLI); columns are
* invariants. Every cell is ok / FAIL / n.a., computed from fixed inputs only:
* fixed timestamps, no randomness, no network, no wall clock.
*
* npm run build && npx vitest run test/antigravity.matrix.test.ts
*
* Each failing cell throws a one-line reason. The matrix is printed at the end
* (and written to $MATRIX_OUT as Markdown when that variable is set).
*
* Cells marked † rest on third-party documentation of Antigravity's on-disk
* format (no vendor spec found, only third-party write-ups). Confirm them
* against a real capture.
*/
import { execFile } from "node:child_process";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join, relative, sep } from "node:path";
import { promisify } from "node:util";
import { afterAll, describe, expect, it } from "vitest";
import type { ContentBlock, Message, TextBlock, ToolResultBlock, ToolUseBlock } from "../src/anthropic/types.js";
import { antigravityAdapter } from "../src/audit/agents/antigravity.js";
import { ADAPTERS, getAdapter, supportedAgents } from "../src/audit/agents/index.js";
import { discoverTranscripts } from "../src/audit/discover.js";
import { simulate } from "../src/audit/simulate.js";
import type { Transcript } from "../src/audit/transcript.js";
import { toolLabel } from "../src/core/labels.js";
const run = promisify(execFile);
const ROOT = join(__dirname, "..");
const TRANSCRIPT = "brain/c1/.system_generated/logs/transcript.jsonl";
// ---------------------------------------------------------------- the engine
type Status = "ok" | "FAIL" | "n.a.";
type Verdict = string | null | undefined; // string = why it failed, null = ok, undefined = n.a.
interface Cell {
status: Status;
why?: string;
}
interface Section {
cols: string[];
rows: Map<string, Map<string, Cell>>;
}
const sections = new Map<string, Section>();
function touch(sec: string, row: string, col?: string): void {
const s: Section = sections.get(sec) ?? { cols: [], rows: new Map() };
sections.set(sec, s);
if (!s.rows.has(row)) s.rows.set(row, new Map());
if (col !== undefined && !s.cols.includes(col)) s.cols.push(col);
}
function check(sec: string, row: string, col: string, fn: () => Verdict | Promise<Verdict>, timeout?: number): void {
touch(sec, row, col);
it(
`${sec} | ${row} × ${col}`,
async () => {
let v: Verdict;
try {
v = await fn();
} catch (e) {
v = `threw: ${(e as Error).message}`;
}
const cell: Cell = v === undefined ? { status: "n.a." } : v === null ? { status: "ok" } : { status: "FAIL", why: v };
sections.get(sec)!.rows.get(row)!.set(col, cell);
if (v) throw new Error(v);
},
timeout,
);
}
afterAll(() => {
const md: string[] = [];
const fails: string[] = [];
let ok = 0;
let bad = 0;
for (const [title, s] of sections) {
md.push(`#### ${title}`, "", `| scenario | ${s.cols.join(" | ")} |`, `|:--|${s.cols.map(() => ":-:").join("|")}|`);
for (const [row, cells] of s.rows) {
const marks = s.cols.map((c) => {
const cell = cells.get(c);
if (!cell || cell.status === "n.a.") return "·";
if (cell.status === "ok") return (ok++, "✅");
bad++;
fails.push(`- **${row} × ${c}**: ${cell.why}`);
return "❌";
});
md.push(`| ${row} | ${marks.join(" | ")} |`);
}
md.push("");
}
md.push(`**${ok} ok · ${bad} FAIL** (· = not applicable)`, "", "Failing cells:", ...fails);
const out = md.join("\n");
console.log(`\n${out}\n`);
if (process.env.MATRIX_OUT) writeFileSync(process.env.MATRIX_OUT, `${out}\n`);
});
// ---------------------------------------------------- scenario construction
const T0 = Date.UTC(2026, 10, 9, 10, 0, 0);
const at = (sec: number): string => new Date(T0 + sec * 1000).toISOString();
/** Antigravity JSON-encodes every argument value, e.g. Path: "\"src/a.ts\"" (see the PR fixture). */
const q = (v: string): string => JSON.stringify(v);
type CallSpec = [name: string, args: Record<string, string>];
const read = (p: string): CallSpec => ["read_file", { Path: q(p) }];
const cmd = (c: string): CallSpec => ["run_command", { CommandLine: q(c), WaitMsBeforeAsync: "5000" }];
const body = (tag: string, n = 60): string =>
Array.from({ length: n }, (_, k) => `export const ${tag}_${k} = compute(${k}, "payload ${tag}");`).join("\n");
class Log {
private i = 0;
readonly lines: string[] = [];
push(o: Record<string, unknown>, sec: number): this {
this.lines.push(JSON.stringify({ step_index: this.i++, status: "DONE", created_at: at(sec), ...o }));
return this;
}
raw(line: string): this {
this.lines.push(line);
return this;
}
user(text: string, sec = 0): this {
return this.push({ source: "USER_EXPLICIT", type: "USER_INPUT", content: text }, sec);
}
plan(o: { content?: string; calls?: CallSpec[] }, sec: number): this {
const calls = o.calls?.map(([name, args]) => ({ name, args }));
return this.push(
{ source: "MODEL", type: "PLANNER_RESPONSE", ...(o.content !== undefined ? { content: o.content } : {}), ...(calls ? { tool_calls: calls } : {}) },
sec,
);
}
out(content: string, sec: number, type = "GENERIC"): this {
return this.push({ source: "MODEL", type, content }, sec);
}
get text(): string {
return this.lines.join("\n");
}
}
// ------------------------------------------------------------------- oracle
// What a correct adapter must reproduce. A result record belongs to the oldest
// call of the latest PLANNER_RESPONSE that has not been answered yet, whatever
// its content (an empty output is still a result); unmatched results have no
// call to hang on. The result-type list and the pop-per-result rule mirror the
// independent parser in jazzyalex/agent-sessions (AntigravityTranscriptParser.swift).
const RESULT_TYPES = new Set(["GENERIC", "RUN_COMMAND", "VIEW_FILE", "LIST_DIRECTORY", "GREP_SEARCH", "SEARCH_WEB", "CODE_ACTION"]);
interface Call {
name: string;
ident: string;
out: string;
}
const decode = (v: unknown): string => {
if (typeof v !== "string") return "";
try {
const d: unknown = JSON.parse(v);
return typeof d === "string" ? d : v;
} catch {
return v;
}
};
const identOf = (args: Record<string, unknown> | undefined): string => {
for (const k of ["CommandLine", "command", "Path", "path"]) if (args?.[k] !== undefined) return decode(args[k]);
return "";
};
function oracle(text: string): { calls: Call[]; keep: string[] } {
const calls: Call[] = [];
const keep: string[] = [];
let queue: Call[] = [];
for (const line of text.split("\n")) {
let o: Record<string, unknown> | null;
try {
o = JSON.parse(line) as Record<string, unknown> | null;
} catch {
continue;
}
if (o === null || typeof o !== "object" || Array.isArray(o)) continue;
const content = typeof o.content === "string" ? o.content.trim() : "";
if (o.type === "USER_INPUT") {
queue = [];
if (content) keep.push(content);
} else if (o.type === "PLANNER_RESPONSE") {
queue = [];
if (content) keep.push(content);
for (const c of Array.isArray(o.tool_calls) ? (o.tool_calls as unknown[]) : []) {
const cc = c as { name?: unknown; args?: Record<string, unknown> } | null;
if (!cc || typeof cc.name !== "string") continue;
const call: Call = { name: cc.name, ident: identOf(cc.args), out: "" };
calls.push(call);
queue.push(call);
}
} else if (typeof o.type === "string" && RESULT_TYPES.has(o.type)) {
const call = queue.shift();
if (call) {
call.out = typeof o.content === "string" ? o.content : "";
if (call.out.trim()) keep.push(call.out.trim());
}
}
}
return { calls, keep };
}
// ---------------------------------------------------------------- the checks
const msgs = (t: Transcript): Message[] => t.segments.flatMap((s) => s.messages);
const blocks = (m: Message): ContentBlock[] => (typeof m.content === "string" ? [{ type: "text", text: m.content } as TextBlock] : m.content);
const allBlocks = (t: Transcript): ContentBlock[] => msgs(t).flatMap(blocks);
const uses = (t: Transcript): ToolUseBlock[] => allBlocks(t).filter((b): b is ToolUseBlock => b.type === "tool_use");
const results = (t: Transcript): ToolResultBlock[] => allBlocks(t).filter((b): b is ToolResultBlock => b.type === "tool_result");
const asText = (c: ToolResultBlock["content"]): string =>
typeof c === "string" ? c : (c ?? []).map((x) => (typeof (x as { text?: unknown }).text === "string" ? (x as TextBlock).text : "")).join("");
const show = (s: string): string => (s.length > 28 ? `${JSON.stringify(`${s.slice(0, 28)}…`)} [${s.length} chars]` : JSON.stringify(s));
function pairing(t: Transcript, want: Call[]): Verdict {
const us = uses(t);
const rs = results(t);
const dangling = rs.filter((r) => !us.some((u) => u.id === r.tool_use_id)).length;
if (dangling) return `${dangling} tool_result(s) point at no tool_use`;
if (us.length !== want.length) return `expected ${want.length} tool_use block(s), got ${us.length}`;
for (let i = 0; i < want.length; i++) {
const w = want[i]!;
const u = us[i]!;
const got = rs.filter((r) => r.tool_use_id === u.id).map((r) => asText(r.content)).join("");
if (got !== w.out) return `call ${i + 1} (${w.name} ${show(w.ident)}) is given output ${show(got)}; the log says ${show(w.out)}`;
}
return null;
}
function keeps(t: Transcript, want: string[]): Verdict {
const have = new Set<string>();
for (const b of allBlocks(t)) {
if (b.type === "text" && typeof (b as TextBlock).text === "string") have.add((b as TextBlock).text.trim());
if (b.type === "tool_result") have.add(asText((b as ToolResultBlock).content).trim());
}
const missing = want.filter((w) => !have.has(w));
return missing.length ? `${missing.length} log string(s) silently dropped, e.g. ${show(missing[0]!)}` : null;
}
function ids(t: Transcript): Verdict {
const seen = new Set<string>();
const dup = new Set<string>();
for (const u of uses(t)) (seen.has(u.id) ? dup : seen).add(u.id);
return dup.size ? `duplicate tool_use id(s): ${[...dup].join(", ")}` : null;
}
function times(t: Transcript): Verdict {
for (const s of t.segments) {
if (s.times.length !== s.messages.length) return `times (${s.times.length}) not aligned with messages (${s.messages.length})`;
if (s.times.some((x) => x !== undefined && !Number.isFinite(x))) return `non-finite entry in times: ${JSON.stringify(s.times.filter((x) => x !== undefined && !Number.isFinite(x)))}`;
}
return t.start !== undefined && !Number.isFinite(t.start) ? "start is not finite" : null;
}
function labels(t: Transcript, want: Call[]): Verdict {
const us = uses(t);
const bad = us.flatMap((u, i) => {
const w = want[i];
const label = toolLabel(u.name, u.input);
return w && !label.includes(w.ident) ? [`${JSON.stringify(label)} for ${show(w.ident)}`] : [];
});
return bad.length ? `${bad.length}/${us.length} calls get a label that does not say which file/command: ${bad[0]}` : null;
}
function targets(t: Transcript, want: number): Verdict {
const sim = simulate(t, { strategies: ["baseline", "deja"] });
return sim.targets.size === want ? null : `${sim.targets.size} distinct target(s) instead of ${want}: ${[...sim.targets.keys()].slice(0, 2).map((k) => JSON.stringify(k)).join(", ")}`;
}
function noPhantomReruns(t: Transcript): Verdict {
const sim = simulate(t, { strategies: ["baseline", "deja"] });
const n = sim.bills?.deja?.reruns ?? 0;
return n === 0 ? null : `deja reports ${n} re-run(s) of stubbed output although no file is read twice`;
}
function simulates(t: Transcript): Verdict {
const sim = simulate(t, { strategies: ["baseline", "eager", "dedup", "deja"] });
const us = uses(t);
const answered = results(t).filter((r) => us.some((u) => u.id === r.tool_use_id)).length;
return sim.toolResults === answered ? null : `simulate() sees ${sim.toolResults} tool result(s), transcript has ${answered}`;
}
// ------------------------------------------------------------ parse scenarios
type Col = "no-throw" | "pairing" | "keep" | "ids" | "times" | "simulate" | "labels" | "targets" | "no phantom reruns";
interface Scenario {
id: string;
text: string;
/** Restrict to these columns (malformed input). */
only?: Col[];
/** Expected number of distinct targets; enables `labels`, `targets`. */
targets?: number;
/** Nothing is read twice; enables `no phantom reruns`. */
noReruns?: boolean;
}
const S: Scenario[] = [];
const add = (id: string, build: (l: Log) => void, extra: Partial<Scenario> = {}): void => {
const l = new Log();
build(l);
S.push({ id, text: l.text, ...extra });
};
const fixture = readFileSync(join(__dirname, "fixtures", "antigravity", "real-session.jsonl"), "utf8");
S.push({ id: "PR fixture (real-session.jsonl)", text: fixture, targets: 2 });
add("1 call", (l) => l.user("read a").plan({ calls: [read("src/a.ts")] }, 5).out(body("a"), 10).plan({ content: "done" }, 15));
add("3 parallel calls", (l) =>
l.user("go").plan({ calls: [read("src/a.ts"), read("src/b.ts"), cmd("npm test")] }, 5).out(body("a"), 10).out(body("b"), 11).out("ok", 12).plan({ content: "done" }, 15),
);
add("empty output, 1st of 2", (l) =>
l.user("go").plan({ calls: [cmd("mkdir -p build"), cmd("git status")] }, 5).out("", 10).out("On branch main", 11).plan({ content: "done" }, 15),
);
add("empty output, 2nd of 3", (l) =>
l.user("go").plan({ calls: [read("src/a.ts"), cmd("mkdir -p build"), read("src/b.ts")] }, 5).out(body("a"), 10).out("", 11).out(body("b"), 12).plan({ content: "done" }, 15),
);
add("empty output, last", (l) =>
l.user("go").plan({ calls: [read("src/a.ts"), cmd("mkdir -p build")] }, 5).out(body("a"), 10).out("", 11).plan({ content: "done" }, 15),
);
add("text + tool call in one turn", (l) =>
l.user("go").plan({ content: "Let me check the config.", calls: [read("src/config.ts")] }, 5).out(body("c"), 10).plan({ content: "done" }, 15),
);
add("final answer + tool_calls: []", (l) => l.user("go").plan({ calls: [read("src/a.ts")] }, 5).out(body("a"), 10).plan({ content: "All done.", calls: [] }, 15));
add("interrupted turn", (l) =>
l.user("go").plan({ calls: [read("src/a.ts"), read("src/b.ts")] }, 5).out(body("a"), 10).user("stop", 20).plan({ content: "ok" }, 25),
);
add("bookkeeping records interleaved", (l) =>
l
.user("go")
.plan({ calls: [read("src/a.ts")] }, 5)
.push({ source: "SYSTEM", type: "CHECKPOINT", content: "checkpoint 1" }, 6)
.push({ source: "SYSTEM", type: "SYSTEM_MESSAGE", content: "ephemeral note" }, 7)
.push({ source: "MODEL", type: "CONVERSATION_HISTORY", content: "earlier summary" }, 8)
.out(body("a"), 10)
.plan({ content: "done" }, 15),
);
add("typed result records †", (l) =>
l.user("go").plan({ calls: [cmd("git status"), read("src/a.ts")] }, 5).out("On branch main", 10, "RUN_COMMAND").out(body("a"), 11, "VIEW_FILE").plan({ content: "done" }, 15),
);
add("result with no pending call", (l) => l.user("go").out("stray output", 3).plan({ content: "done" }, 15));
S.push({ id: "CRLF line endings", text: new Log().user("go").plan({ calls: [read("src/a.ts")] }, 5).out(body("a"), 10).plan({ content: "done" }, 15).text.replace(/\n/g, "\r\n") });
S.push({ id: "empty file", text: "" });
add("garbage + truncated JSON lines", (l) =>
l.user("go").raw("not json at all").raw('{"step_index":9,"type":"PLANNER_RESP').raw("").plan({ content: "done" }, 15),
{ only: ["no-throw", "keep", "simulate"] },
);
add("a line that is JSON null", (l) => l.user("go").raw("null").plan({ content: "done" }, 15), { only: ["no-throw", "keep", "simulate"] });
add("tool_calls entry is null", (l) =>
l.user("go").push({ source: "MODEL", type: "PLANNER_RESPONSE", tool_calls: [null, { name: "read_file", args: { Path: q("src/a.ts") } }] }, 5).out(body("a"), 10).plan({ content: "done" }, 15),
{ only: ["no-throw", "keep", "simulate"] },
);
add("unparseable created_at", (l) =>
l.user("go").push({ source: "MODEL", type: "PLANNER_RESPONSE", created_at: "yesterday", content: "thinking" }, 5).plan({ content: "done" }, 15),
);
add("no step_index on records", (l) =>
l
.user("go")
.push({ step_index: undefined, source: "MODEL", type: "PLANNER_RESPONSE", tool_calls: [{ name: "read_file", args: { Path: q("src/a.ts") } }] }, 5)
.out(body("a"), 10)
.push({ step_index: undefined, source: "MODEL", type: "PLANNER_RESPONSE", tool_calls: [{ name: "read_file", args: { Path: q("src/b.ts") } }] }, 15)
.out(body("b"), 20)
.plan({ content: "done" }, 25),
);
add(
"16 different files, read once each",
(l) => {
l.user("read every module");
for (let i = 0; i < 16; i++) l.plan({ calls: [read(`src/m${i}.ts`)] }, (i + 1) * 360).out(body(`m${i}`), (i + 1) * 360 + 5);
l.plan({ content: "done" }, 17 * 360);
},
{ targets: 16, noReruns: true },
);
add(
"a.ts, a.ts again, b.ts",
(l) =>
l
.user("go")
.plan({ calls: [read("src/a.ts")] }, 5)
.out(body("a"), 10)
.plan({ calls: [read("src/a.ts")] }, 15)
.out(body("a"), 20)
.plan({ calls: [read("src/b.ts")] }, 25)
.out(body("b"), 30)
.plan({ content: "done" }, 35),
{ targets: 2 },
);
add(
"3 different commands",
(l) =>
l
.user("go")
.plan({ calls: [cmd("git status"), cmd("npm test"), cmd("ls -la")] }, 5)
.out("On branch main", 10)
.out("3 passed", 11)
.out("total 4", 12)
.plan({ content: "done" }, 15),
{ targets: 3 },
);
for (const sc of S) {
const sec = "Parse: scenario × invariant";
touch(sec, sc.id);
const parsed = (() => {
try {
return { t: antigravityAdapter.parse(sc.text, TRANSCRIPT) };
} catch (e) {
return { err: (e as Error).message.split("\n")[0]! };
}
})();
const on = (c: Col): boolean => !sc.only || sc.only.includes(c);
const withT = (fn: (t: Transcript) => Verdict): Verdict => (parsed.t ? fn(parsed.t) : undefined);
const { calls, keep } = oracle(sc.text);
check(sec, sc.id, "no-throw", () => (parsed.err ? `parse() threw: ${parsed.err} (index.ts: "Must never throw")` : null));
if (on("pairing")) check(sec, sc.id, "pairing", () => withT((t) => pairing(t, calls)));
if (on("keep")) check(sec, sc.id, "keep", () => withT((t) => keeps(t, keep)));
if (on("ids")) check(sec, sc.id, "ids", () => withT(ids));
if (on("times")) check(sec, sc.id, "times", () => withT(times));
if (on("simulate")) check(sec, sc.id, "simulate", () => withT(simulates));
if (sc.targets !== undefined) {
check(sec, sc.id, "labels", () => withT((t) => labels(t, calls)));
check(sec, sc.id, "targets", () => withT((t) => targets(t, sc.targets!)));
}
if (sc.noReruns) check(sec, sc.id, "no phantom reruns", () => withT(noPhantomReruns));
}
// ------------------------------------------------------------------ discovery
describe("discovery", () => {
const sec = "Discovery: on-disk layout × invariant";
const t1 = "c1/.system_generated/logs/transcript.jsonl";
const full = "c1/.system_generated/logs/transcript_full.jsonl";
const layouts: Array<{ id: string; files: string[]; want: Record<string, number> }> = [
{ id: "transcript.jsonl + sibling *.md artifacts", files: [t1, "c1/task.md", "c1/task.md.metadata.json", "c1/task.md.resolved"], want: { c1: 1 } },
{ id: "two conversations", files: [t1, "c2/.system_generated/logs/transcript.jsonl"], want: { c1: 1, c2: 1 } },
{ id: "transcript.jsonl + transcript_full.jsonl †", files: [t1, full], want: { c1: 1 } },
];
const dir = mkdtempSync(join(tmpdir(), "deja-ag-matrix-"));
afterAll(() => rmSync(dir, { recursive: true, force: true }));
for (const [n, lay] of layouts.entries()) {
const root = join(dir, `L${n}`);
for (const f of lay.files) {
mkdirSync(dirname(join(root, f)), { recursive: true });
writeFileSync(join(root, f), "{}\n");
}
// Same call the CLI makes (src/cli/commands/audit.ts).
const found = (): string[] =>
discoverTranscripts(root, { extensions: antigravityAdapter.extensions }).map((f) => relative(root, f.path).split(sep).join("/")).sort();
const perConv = (): Map<string, string[]> => {
const m = new Map<string, string[]>();
for (const f of found()) m.set(f.split("/")[0]!, [...(m.get(f.split("/")[0]!) ?? []), f.split("/").pop()!]);
return m;
};
check(sec, lay.id, "finds each conversation", () => {
const m = perConv();
const missing = Object.keys(lay.want).filter((c) => !m.has(c));
return missing.length ? `no transcript found for ${missing.join(", ")}` : null;
});
check(sec, lay.id, "one file per conversation", () => {
const m = perConv();
const bad = Object.entries(lay.want).filter(([c, n]) => (m.get(c)?.length ?? 0) !== n);
return bad.length ? `${bad[0]![0]}: ${m.get(bad[0]![0])!.join(" + ")} would be audited as ${m.get(bad[0]![0])!.length} sessions` : null;
});
check(sec, lay.id, "only transcripts", () => {
const extra = found().filter((f) => !/\/transcript(_full)?\.jsonl$/.test(f));
return extra.length ? `picked up ${extra.join(", ")}` : null;
});
}
});
// --------------------------------------------------------------------- wiring
describe("wiring", () => {
const sec = "Wiring: registry + default dir";
check(sec, "registry", "registered", () => (getAdapter("antigravity") === antigravityAdapter ? null : "getAdapter('antigravity') is not the adapter"));
check(sec, "registry", "case-insensitive", () => (getAdapter("AntiGravity") === antigravityAdapter ? null : "--agent is documented as case-insensitive"));
check(sec, "registry", "listed in errors", () => (supportedAgents().split(", ").includes("antigravity") ? null : `supportedAgents() = ${supportedAgents()}`));
check(sec, "registry", "ids unique + flag-safe", () => {
const all = [...ADAPTERS.values()].map((a) => a.id);
return new Set(all).size === all.length && all.every((i) => /^[a-z0-9-]+$/.test(i)) ? null : `ids: ${all.join(", ")}`;
});
check(sec, "default dir", "home default", () => {
const d = antigravityAdapter.defaultDir({});
return d !== undefined && d.endsWith(join(".gemini", "antigravity", "brain")) ? null : `defaultDir() = ${d}`;
});
check(sec, "default dir", "env override", () => {
const d = antigravityAdapter.defaultDir({ GEMINI_HOME: join(sep, "x") });
return d === join(sep, "x", "antigravity", "brain") ? null : `defaultDir({GEMINI_HOME}) = ${d}`;
});
// † Third-party guides put CLI transcripts under ~/.gemini/antigravity-cli/brain
// (the editor store under ~/.gemini/antigravity/brain). Hermetic: a throwaway HOME.
check(sec, "default dir", "CLI root reachable †", () => {
const home = mkdtempSync(join(tmpdir(), "deja-ag-home-"));
const saved = { HOME: process.env.HOME, USERPROFILE: process.env.USERPROFILE };
try {
const logs = join(home, ".gemini", "antigravity-cli", "brain", "c1", ".system_generated", "logs");
mkdirSync(logs, { recursive: true });
writeFileSync(join(logs, "transcript.jsonl"), "{}\n");
process.env.HOME = process.env.USERPROFILE = home;
const d = antigravityAdapter.defaultDir({});
const n = d ? discoverTranscripts(d, { extensions: antigravityAdapter.extensions }).length : 0;
return n > 0 ? null : "with only ~/.gemini/antigravity-cli/brain on disk, the default dir finds 0 conversations";
} finally {
for (const [k, v] of Object.entries(saved)) if (v === undefined) delete process.env[k];
else process.env[k] = v;
rmSync(home, { recursive: true, force: true });
}
});
});
// ------------------------------------------------------------------ CLI e2e
describe.skipIf(!existsSync(join(ROOT, "dist", "cli.js")))("cli", () => {
const sec = "CLI end to end: deja audit --agent antigravity";
const dir = mkdtempSync(join(tmpdir(), "deja-ag-e2e-"));
const logs = join(dir, "c1", ".system_generated", "logs");
mkdirSync(logs, { recursive: true });
writeFileSync(join(logs, "transcript.jsonl"), fixture);
afterAll(() => rmSync(dir, { recursive: true, force: true }));
let report: { agentName: string; sessions: number; toolResults: number; heaviest: Array<{ target: string }> } | undefined;
const load = async () =>
(report ??= JSON.parse(
(
await run(process.execPath, [join(ROOT, "dist", "cli.js"), "audit", "--agent", "antigravity", "--dir", dir, "--since", "all", "--json"], {
env: { ...process.env, DEJA_HOME: mkdtempSync(join(tmpdir(), "deja-ag-home-")) },
})
).stdout,
) as NonNullable<typeof report>);
check(sec, "PR fixture", "exits 0, 1 session, 3 results", async () => {
const r = await load();
return r.agentName === antigravityAdapter.name && r.sessions === 1 && r.toolResults === 3 ? null : `agentName=${r.agentName} sessions=${r.sessions} toolResults=${r.toolResults}`;
}, 60_000);
check(sec, "PR fixture", "report names files + commands", async () => {
const names = (await load()).heaviest.map((h) => h.target);
return names.some((n) => n.includes("src/index.ts")) && names.some((n) => n.includes("git status")) ? null : `"context hogs" lists ${names.map((n) => JSON.stringify(n)).join(", ")}`;
}, 60_000);
});
it("matrix is wired", () => expect(S.length).toBeGreaterThan(0));Candidate patchI applied this to a scratch copy of this branch: the matrix goes from 124 ok · 22 FAIL to 149 ok · 1 FAIL (the remaining cell is F8, which needs a decision on discovery rather than a code fix), typecheck and build are clean, and the full existing suite (656 tests, yours included) still passes. It is one way to do it; take what is useful and keep your own style. antigravity.patch (101 changed lines, apply with
|
Summary
src/audit/agents/antigravity.ts) fordeja audit --agent antigravity.PLANNER_RESPONSEturns containing multipletool_callsfollowed by sequentialGENERICoutputs.src/audit/agents/index.ts).test/fixtures/antigravity/real-session.jsonl).test/antigravity.test.ts.