◉ANTIGRAVITY LABJP
Articles/Agents & Manager
◈ Agents & Manager/2026-11-24Intermediate

My Unattended agy Run Ended in ERROR, but the Output Was Right: Judging Success by Content, Not Status

agy headless runs can reach the finish tool and still end with status ERROR when the final summary turn loses its stream. Here is a judge script that pulls the finish arguments out of stream-json, checks them against the schema and an independent test, and where I refuse to salvage.

Antigravity CLI46headless8stream-jsonunattended runs9indie developer20

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:

  1. At the end of a long autonomous task, the agent calls the finish tool with arguments that match the schema
  2. The runtime replies that the task is complete and asks for a summary with no more tool calls
  3. The CLI makes one more streamGenerateContent request to get that summary
  4. With a large context (about 230K tokens in the report), the connection drops with EOF or "The stream was interrupted"
  5. 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:

ConditionWhere to checkIf it fails
The finishing tool reached DONE with no tool errortool_info in step_updateFailure
The error text is a transport drop (EOF, stream was interrupted)result.errorFailure
The recovered result satisfies the schemaYour local schemaFailure
Something other than the agent can confirm the content--verify-cmdFailure

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 selection never 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 as FAILED_SUCCESS
  • FINISH_TOOLS is a constant because the finishing tool's name isn't in the docs' tables; I took it from the report. After an upgrade, check tool_name in 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 situationVerdictExit code
Normal SUCCESSSUCCESS0
EOF after finishSALVAGED10
Stream interrupted, no finishFAILED_NO_OUTPUT1
Bad model name (a real ERROR)FAILED_ERROR1
Output cut before any resultNO_RESULT1
Finish arguments with a wrong type (integer as string)FAILED_SCHEMA1
EOF after finish, verify command failsFAILED_VERIFY1
EOF after finish, verify command passesSALVAGED10

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 ;;
esac

With 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
  • status of WAITING or CANCELED. 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.

Share

Thank You for Reading

Antigravity Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • ✦Copy-paste ready implementation code
  • ✦New advanced guides published daily
  • ✦$5/mo or $10 for lifetime access
View Membership →

If you found this article helpful, a small tip ($1.50) would mean a lot to us. Your support helps keep this site ad-free and covers server and hosting costs.

Related Articles

◈ Agents & Manager2026-10-25
An Unattended Job Stopped With 11MB Free. du Counted Only 59MB; the Other 9GB Was Somewhere I Couldn't See
Two bash scripts that measure free space on the filesystem you are about to write to and stop an unattended agent run before it starts. Includes why du and df disagreed and how to spot a shortage you cannot fix.
◈ Agents & Manager2026-10-30
I moved the stop conditions for a nightly Antigravity CLI run outside the CLI
A wrapper that gives a nightly agy -p run three outer stop conditions: time, output size and overlap. Seven endings tested with fake agy scripts showed a timeout exiting with 137, and a leftover process holding the lock so every night was skipped. Includes a morning triage table.
◈ Agents & Manager2026-10-22
17 Dead References in My Handover Docs Turned Out to Be 2 Files, and the Real Risk Was a Different Site's Playbook Mixed In
The full Python script I use to check the root .md files an agent reads. My naive version counted 17 dead references; fixed, it was 7 across 2 files. Then it missed the real problem. Here is how I found it.