One morning my log had a single FAILED line from the overnight job. The job is the dullest check I run as an indie developer: read the store listings for my wallpaper apps in each language and return, as JSON, every field that goes over its character limit.
My wrapper treated anything other than status: SUCCESS as a failure and threw the result away. So I spent the start of that morning re-running the whole check by hand.
When I finally opened the raw stream, the agent had done its job. It had called the finishing tool, handed over a result that matched the schema, and only then picked up the ERROR. What I had thrown away was the correct answer.
A report with the same shape exists on the Google AI Developers Forum. I compared what happened on my side with that report, and I've written down how I now split an ERROR into failures I may salvage and failures I must not.
The behavior described here follows the official Antigravity CLI headless documentation as of November 2026. I tested the judge script against eight replayed NDJSON streams built in the documented stream-json format.
ERROR is not one thing
The docs fix the order of --output-format stream-json: one init, any number of step_update events, then exactly one result. The result.status is one of SUCCESS, ERROR, CANCELED, INTERRUPTED, INVALID, WAITING, or RUNNING.
The forum report from September 2026 describes what happens inside one particular ERROR:
- At the end of a long autonomous task, the agent calls the
finishtool with arguments that match the schema - The runtime replies that the task is complete and asks for a summary with no more tool calls
- The CLI makes one more
streamGenerateContentrequest to get that summary - With a large context (about 230K tokens in the report), the connection drops with
EOFor "The stream was interrupted" - The summary isn't actually needed, yet the whole run gets
status: ERROR
A forum moderator replied that the report went to the engineering team and recommended updating to the latest release. As far as I could find, nothing yet confirms a fix.
The point I want to make first: ERROR can mean "the work failed" or "the conversation after the work failed." A wrapper that only reads status can't tell the two apart.
The result you need is still in the stream
The clue is in the step_update events. Per the docs, tool steps carry tool_info with name, parameters, output, and an error object only when the tool fails.
So the parameters of the finish step that reached DONE hold exactly what the agent handed over. You can read them even when result has no structured_output.
My first thought was to call any ERROR with a finish step a success. That invites the opposite accident, though: an agent that confidently finishes with a wrong answer and then fails for a real reason would be marked green.
So I narrowed salvage down to four conditions:
| Condition | Where to check | If it fails |
|---|---|---|
The finishing tool reached DONE with no tool error | tool_info in step_update | Failure |
The error text is a transport drop (EOF, stream was interrupted) | result.error | Failure |
| The recovered result satisfies the schema | Your local schema | Failure |
| Something other than the agent can confirm the content | --verify-cmd | Failure |
Only when all four hold do I record a salvage, and I return a different exit code from a plain success. I keep them apart because a run of salvages is my signal to rethink how much context the job carries.
The judge script
This Python script reads agy's stdout directly, keeps the raw NDJSON, and decides. It has no dependencies; the schema check only looks at type, required, properties, and items.
#!/usr/bin/env python3
"""Read agy stream-json and decide success by the output, not by status alone.
Usage:
agy -p "..." --output-format stream-json --json-schema schema.json \
| python3 judge_run.py --schema schema.json --raw run.ndjson --out result.json
Exit codes: 0=success / 10=salvaged (stream dropped, output valid) / 1=failure
"""
import argparse, json, re, subprocess, sys
# Error texts that point to a dropped stream on the final summary turn
TRANSPORT_ERRORS = re.compile(r"(EOF\b|stream was interrupted)", re.I)
FINISH_TOOLS = {"finish"} # Name taken from the report; check raw logs after upgrades
def check(value, schema, path="$"):
"""Minimal, dependency-free check: type / required / properties / items."""
t = schema.get("type")
types = {"object": dict, "array": list, "string": str,
"integer": int, "number": (int, float), "boolean": bool}
if t in types:
if t in ("integer", "number") and isinstance(value, bool):
return [f"{path}: bool is not {t}"]
if not isinstance(value, types[t]):
return [f"{path}: not {t}"]
errs = []
if isinstance(value, dict):
for k in schema.get("required", []):
if k not in value:
errs.append(f"{path}.{k}: required field missing")
for k, sub in schema.get("properties", {}).items():
if k in value:
errs += check(value[k], sub, f"{path}.{k}")
if isinstance(value, list) and "items" in schema:
for i, v in enumerate(value):
errs += check(v, schema["items"], f"{path}[{i}]")
return errs
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--schema", required=True)
ap.add_argument("--raw", required=True, help="where to keep the raw NDJSON")
ap.add_argument("--out", required=True, help="where to save the accepted output")
ap.add_argument("--verify-cmd", help="independent check, run only before a salvage")
a = ap.parse_args()
schema = json.load(open(a.schema, encoding="utf-8"))
result, finish_args, broken = None, None, 0
with open(a.raw, "w", encoding="utf-8") as raw:
for line in sys.stdin:
raw.write(line)
try:
ev = json.loads(line)
except json.JSONDecodeError:
broken += 1
continue
if ev.get("event") == "result":
result = ev["result"]
elif ev.get("event") == "step_update":
su = ev["step_update"]
info = su.get("tool_info") or {}
if (su.get("step_type") == "tool" and su.get("state") == "DONE"
and su.get("tool_name") in FINISH_TOOLS and not info.get("error")):
finish_args = info.get("parameters")
def done(code, verdict, payload=None, note=""):
if payload is not None:
json.dump(payload, open(a.out, "w", encoding="utf-8"), ensure_ascii=False, indent=2)
print(json.dumps({"verdict": verdict, "note": note, "broken_lines": broken},
ensure_ascii=False), file=sys.stderr)
sys.exit(code)
if result is None:
done(1, "NO_RESULT", note="stream ended before any result event")
status, so = result.get("status"), result.get("structured_output")
if status == "SUCCESS" and so is not None and not check(so, schema):
done(0, "SUCCESS", so)
if status != "ERROR" or not TRANSPORT_ERRORS.search(result.get("error") or ""):
done(1, f"FAILED_{status}", note=(result.get("error") or "")[:200])
# Past this point we only suspect a dropped stream after the work was done
candidate = so if so is not None else finish_args
if candidate is None:
done(1, "FAILED_NO_OUTPUT", note="no finish arguments and no structured_output")
errs = check(candidate, schema)
if errs:
done(1, "FAILED_SCHEMA", note="; ".join(errs[:5]))
if a.verify_cmd and subprocess.run(a.verify_cmd, shell=True).returncode != 0:
done(1, "FAILED_VERIFY", note=f"verify command failed: {a.verify_cmd}")
done(10, "SALVAGED", candidate, note=(result.get("error") or "")[:200])
if __name__ == "__main__":
main()A few notes on why it's written this way:
- The raw NDJSON is written first so I can re-judge the same stream if I change the rules later. That morning, the raw log was the only reason I noticed what I had discarded
- The transport-error regex is deliberately narrow so real failures like
invalid model selectionnever become salvage candidates - Even a SUCCESS gets re-checked against the schema because I'd rather decide for myself how far to trust
status. A mismatch stops asFAILED_SUCCESS FINISH_TOOLSis a constant because the finishing tool's name isn't in the docs' tables; I took it from the report. After an upgrade, checktool_namein a raw log first
Replaying eight streams
You can't trigger a real stream drop on purpose. So I built NDJSON files that follow the documented stream-json shape and piped them in to test the judgment alone.
| Replayed situation | Verdict | Exit code |
|---|---|---|
| Normal SUCCESS | SUCCESS | 0 |
| EOF after finish | SALVAGED | 10 |
| Stream interrupted, no finish | FAILED_NO_OUTPUT | 1 |
| Bad model name (a real ERROR) | FAILED_ERROR | 1 |
| Output cut before any result | NO_RESULT | 1 |
| Finish arguments with a wrong type (integer as string) | FAILED_SCHEMA | 1 |
| EOF after finish, verify command fails | FAILED_VERIFY | 1 |
| EOF after finish, verify command passes | SALVAGED | 10 |
What surprised me was that only two of the eight get salvaged. Every condition I added shrank what could be rescued, and with it my worry about rescuing something I shouldn't.
Receiving the verdict in the nightly job
Once the judge sits on the right side of a pipe, agy's own exit code disappears from view. I wrote earlier about a pipe swallowing failures in The pipe in my wrapper was swallowing Antigravity CLI's exit code; this is the mirror image, and both values need to survive.
#!/usr/bin/env bash
set -u
mkdir -p logs
day=$(date +%F)
agy -p "$(cat prompt.txt)" \
--output-format stream-json \
--json-schema schema.json \
--print-timeout 30m \
| python3 judge_run.py \
--schema schema.json \
--raw "logs/${day}.ndjson" \
--out "logs/${day}.result.json" \
--verify-cmd "python3 recount.py metadata/"
codes=("${PIPESTATUS[@]}") # save before the next command overwrites it
agy_code=${codes[0]}; verdict=${codes[1]}
case "$verdict" in
0) echo "${day} OK" >> logs/summary.txt ;;
10) echo "${day} SALVAGED agy_exit=${agy_code}" >> logs/summary.txt ;;
*) echo "${day} FAILED agy_exit=${agy_code}" >> logs/summary.txt; exit 1 ;;
esacWith a fake agy replaying the EOF stream, the log said SALVAGED agy_exit=1; replaying the bad-model stream gave FAILED agy_exit=1. Same exit code from agy, different verdicts.
recount.py is a tiny script that counts listing characters again without any agent involved. To me, the last line of defense for a salvage is not what the agent claims, but being able to confirm the same fact from outside the agent.
When I refuse to salvage, and the real fix
The line I settled on: the output decides success; the log carries the transport failure. Even when all four conditions hold, I don't salvage in these cases:
- Jobs where the agent rewrites files and I can't provide a verify command. A half-written state could be called "done"
- Three salvages in a row. That stops being chance and becomes a design problem with too much context
statusofWAITINGorCANCELED. Those aren't dropped streams; they're waiting on a human decision
The real fix is needing salvage less often. In the report, the drop came on the last round trip after the context passed 200K tokens. Splitting the work into smaller runs and setting a ceiling with --print-timeout will do more than any wrapper trick, I suspect.
For the other side of this, protecting files an agent leaves half-written, the members-only piece When a Timed-Out Unattended Agent Leaves a Half-Written File Behind goes deeper with atomic writes.
One thing before tomorrow night
Switch your current overnight job to --output-format stream-json and keep the raw output in a file. You can change how you judge runs after reading a single night's log.
Before re-running anything by hand on an ERROR morning, open the answer you're about to throw away. That's a habit I intend to keep.