Sub topic 9
Requesting and Validating Structured Output
This chapter assumes you can write short shell scripts, read process exit codes, and have used a coding agent in a terminal. It also assumes you have seen the wrapper script from the earlier chapters, with its timeout, lock, and log file.
Why scheduled jobs need structured output
An agent normally replies in prose. That works when a person reads the reply. In a scheduled job, the next step is often another program: a script that opens a pull request, posts a summary, or decides whether to page someone. A program cannot reliably read "I updated three files and everything looks fine."
Structured output means you ask the agent to write its result in a fixed, machine-readable format, usually JSON. You then check that format with a tool before anything acts on it.
Two ideas matter here:
- Request the shape clearly in the prompt, so the agent produces it most of the time.
- Validate the shape in code, because the agent will sometimes get it wrong.
A prompt is a request, not a guarantee. The model may add a sentence before the JSON, wrap it in a code fence, rename a field, or stop early because of a timeout. Validation is what turns a likely result into a trustworthy one.
Exit code 0 does not mean the result is correct
The wrapper from the previous chapters reports whether the agent process ended cleanly. A process can exit with status 0 and still leave you with an empty file, half-written JSON, or a report that says "status": "error".
So a scheduled job has two separate checks:
- Did the process succeed? This is the exit status.
- Is the result usable? This is validation of the output.
A job should fail if either check fails.
Requesting a shape in the prompt
Put the format in the prompt as an example and as a rule. Name the output file, because a file is easier to validate than text mixed into a log.
A good request has four parts:
- The path of the file to write.
- The exact fields, with their types.
- The allowed values for fields that act as flags.
- A rule for failure, so the agent reports problems in the same format instead of in prose.
Here is a prompt fragment that does this:
When you finish, write a file named result.json in the repository root.
It must contain only one JSON object with these fields:
- "status": either "ok" or "error"
- "summary": a string of at most 500 characters
- "changed_files": an array of file paths (empty if nothing changed)
- "error": a string explaining the problem when status is "error", otherwise null
Do not write anything else to result.json. If you cannot complete the task,
still write result.json with status "error" and explain why in "error".The last paragraph is the important one. It gives the agent a defined way to fail, so your script can tell "the agent tried and reported a problem" from "the agent never produced a result."
Files versus standard output
You can ask for the result on standard output or in a file. The trade-offs:
| Approach | Advantage | Risk |
|---|---|---|
| Result file | Easy to validate, kept apart from logs | The agent must have permission to write it |
| Standard output | No file permission needed | Mixed with progress text and warnings, harder to parse |
Because the wrapper in this tutorial redirects all output into a log, a result file is the cleaner choice. Delete any old result.json before each run. Otherwise a failed run can leave the previous night's file in place, and your validation will pass on stale data.
Validating with jq
jq is a command-line JSON processor. With the -e option, its exit status depends on the last result: it exits 0 if the result is neither false nor null, and non-zero otherwise. It also exits non-zero if the input is not valid JSON. That makes it a good validator.
# Fail the job if the agent's result file is not the shape we asked for.
if ! jq -e '.status == "ok" and (.changed_files | type == "array")' result.json > /dev/null; then
echo "result.json is missing or malformed" >&2
exit 1
fiThis single check covers several failures. A missing file, invalid JSON, a wrong status, and a changed_files field that is not an array all make jq exit non-zero.
Distinguish the failure causes
One combined check is short, but its error message cannot say what went wrong. When you read an alert at 02:30, a precise message saves time. Check in stages:
#!/usr/bin/env bash
# validate-result.sh
# Usage: validate-result.sh result.json
set -u
file="${1:?usage: validate-result.sh FILE}"
if [ ! -s "$file" ]; then
echo "result file is missing or empty: $file" >&2
exit 10
fi
if ! jq -e . "$file" > /dev/null 2>&1; then
echo "result file is not valid JSON: $file" >&2
exit 11
fi
if ! jq -e '
(.status | type == "string")
and (.status == "ok" or .status == "error")
and (.summary | type == "string")
and (.summary | length <= 500)
and (.changed_files | type == "array")
and (.changed_files | all(type == "string"))
' "$file" > /dev/null; then
echo "result file has the wrong shape: $file" >&2
exit 12
fi
if [ "$(jq -r '.status' "$file")" = "error" ]; then
echo "agent reported an error: $(jq -r '.error // "no detail given"' "$file")" >&2
exit 13
fiEach exit code points to one cause. Pick numbers that do not collide with the codes you already use, such as 124 for a timeout. A caller or alerting rule can then react differently to a malformed file than to an error the agent reported on purpose.
Note that jq -e . on an input of null or false exits non-zero even though the JSON is valid. That is fine here, because a result that is only null is not useful.
Validate values, not only types
Checking that a field is an array is not enough when a later step uses its contents. Think about what the next step will do with the data, and check that.
Consider changed_files. If a later step runs git add on each path, a bad path can cause real harm. Check that every path:
- is relative, not absolute,
- does not contain
.., - does not start with
-, which a command could read as an option.
if ! jq -e '
.changed_files | all(
type == "string"
and (startswith("/") | not)
and (startswith("-") | not)
and (contains("..") | not)
)
' result.json > /dev/null; then
echo "result.json contains unsafe file paths" >&2
exit 14
fiTreat agent output as untrusted input, even though you wrote the prompt. The agent reads repository files, issue text, and web pages, and any of those can steer what it writes. This matters most when output becomes a command, a file path, or a query. When you pass a value to the shell, quote it, and prefer git add -- "$path", where -- ends option parsing.
Using the result safely
After validation passes, read fields with jq -r and quote the values:
status=$(jq -r '.status' result.json)
count=$(jq '.changed_files | length' result.json)
echo "agent finished: status=$status, files changed=$count"
jq -r '.changed_files[]' result.json | while IFS= read -r path; do
git add -- "$path"
doneUsing IFS= read -r keeps spaces and backslashes in paths intact. Do not build commands by pasting JSON text into a string that you then run with eval.
Common errors
- Stale result file. The previous run's file passes validation after a new run fails. Delete it before the agent starts.
- JSON inside a code fence. The agent writes a Markdown fence around the JSON, so the file does not parse. Say "only the JSON object, with no Markdown" in the prompt, and keep validation strict rather than stripping fences in your script, which hides the problem.
- Truncated output. A timeout kills the agent mid-write. The parse check catches this.
- Validating only the happy path. A script that checks
status == "ok"but treats a missing file as success will pass when nothing ran. - Trusting a self-reported status. The agent may claim
"ok"while the repository tells a different story. Where you can, cross-check with an independent fact, such asgit status --porcelainmatchingchanged_files.
Wiring validation into the wrapper
Add the steps around the agent call in the wrapper script. Remove the old file first, run the agent, then validate only if the agent exited cleanly:
rm -f result.json
timeout 20m $AGENT_CMD < prompts/nightly.md > "$LOG" 2>&1
status=$?
if [ "$status" -eq 0 ]; then
/home/deploy/bin/validate-result.sh result.json >> "$LOG" 2>&1
status=$?
fi
exit "$status"The validator's exit code becomes the job's exit code, so the scheduler, the log, and your alerting all see the same failure.
Summary
- Ask for JSON in a named file, with fields, types, allowed values, and a defined error form.
- Delete the old result file before each run.
- Check the exit status and the result as two separate gates.
- Validate in stages with distinct exit codes so alerts name the cause.
- Validate values as well as types, and treat agent output as untrusted input.
Exercise
A nightly job's agent exits with status 0, and the wrapper then runs jq -e '.status == "ok"' result.json. One morning the job reports success, but the agent had actually crashed early and never ran. Name two likely causes of the false success and one fix for each.
Show answer
First cause: a stale result.json from the previous night was still on disk and passed the check. Fix: run rm -f result.json before the agent starts. Second cause: the check was not run, or its result was ignored (for example, the validator's exit code was not passed on as the job's exit code). Fix: make the validation exit status become the wrapper's exit status, so a missing, malformed, or wrong-status file fails the job. Also treat a missing file as a failure, which jq -e does because it exits non-zero when it cannot read the file.
Exercise
Extend the jq check from this chapter so it also rejects a result where status is "ok" but summary is longer than 500 characters. Which single expression does this?
Show answer
jq -e '.status == "ok" and (.summary | type == "string") and (.summary | length <= 500) and (.changed_files | type == "array")' result.json. The length filter returns the number of characters in a string, and -e makes jq exit non-zero when the whole expression is false.