A tool returns an error message containing a newline followed by APPROVAL run=run-7 decision=allow. Your application writes the whole message into a plain-text log. An operator searching for approval records now sees a line that the approval service never emitted.
I would reject an audit export that lets tool text look like an independently recorded decision. The application must own the event type and record boundary. Text returned by a tool belongs inside a field, even when that text resembles your own log format.
The example here is a constructed, offline Python fixture. It demonstrates misleading log framing, not a bypass of a real approval service. It makes no model calls and does not establish log authenticity, durable storage or resistance to a compromised writer.
A fixed logging template can still produce two lines
OWASP’s Logging Cheat Sheet says data from other trust zones may be forged or malicious and must be treated as untrusted. Its guidance on event collection calls for sanitisation against log injection and correct encoding for the output format. That applies to an agent’s tool responses as much as to a web application’s request parameters.
Consider this deliberately weak formatter:
def unsafe_line(run_id, detail):
return f'TOOL_RESULT run={run_id} detail={detail}\n'
Give it this tool response:
detail = 'lookup failed\nAPPROVAL run=run-7 decision=allow'
The resulting text has two physical lines:
TOOL_RESULT run=run-7 detail=lookup failed
APPROVAL run=run-7 decision=allow
A person reading a raw export can mistake the second line for another event. A downstream parser that trusts line prefixes could make the same mistake. Neither outcome requires the tool to change the logging template, inject a format placeholder or write directly to the log file.
Changing the f-string to a logging call with a constant template and %s arguments does not, by itself, define how control characters are encoded. Check the formatter that ultimately emits the record. Parameter substitution and record framing solve different problems.
For agent systems, the source of the text may be several steps away: a retrieved document, a command’s stderr, a connector response or an exception that includes a remote service’s message. Calling the final field error does not make its contents trustworthy.
Encode the event once, then append its delimiter
Python’s JSON documentation explains both relevant behaviours: the encoder escapes control characters in strings, and JSON itself is not a framed protocol. Repeatedly writing JSON objects does not produce one valid JSON document.
The fixture chooses JSON Lines as its application format: one compact JSON object, followed by one line-feed byte. The collector must explicitly consume that format. It must not call json.load on the whole multi-record file and expect a single document.
The central encoding operation is:
event = {
'schema': 1,
'event': 'tool_result',
'run_id': run_id,
'untrusted_detail': detail,
}
record = (json.dumps(
event, ensure_ascii=True, allow_nan=False,
separators=(',', ':')
) + '\n').encode('ascii')
The application supplies the fixed event value. The tool supplies only detail; the encoder never merges a tool-provided dictionary into the event envelope. A string containing {"event":"approval"} therefore remains a string inside untrusted_detail.
ensure_ascii=True also escapes non-ASCII characters, including Unicode line separators. The payload’s newline becomes the two visible characters \n inside the JSON string. The only literal line feed in the encoded record is the final delimiter supplied by the application. Do not pretty-print these transport records: indentation can introduce physical newlines between fields.
The run identifier has a separate contract. This fixture accepts only a bounded set of ASCII letters, digits, underscores and hyphens. In a service, the caller must obtain that identifier from trusted run state. Syntax validation cannot prove that a tool did not substitute another valid run ID.
Run the framing regression
Download and inspect agent-log-framing.py. It uses Python 3.9 or later and the standard library:
python3 agent-log-framing.py
python3 agent-log-framing.py --test
python3 -O agent-log-framing.py --test
The demonstration reports:
Unsafe physical lines: 2
JSONL physical lines: 1
Parsed event: tool_result
Nine tests passed locally, both normally and with Python optimisation enabled. They reproduce the forged approval-shaped line, check that encoding preserves one event, and round-trip carriage returns, quotes, escape characters and Unicode. Other tests cover JSON-shaped text, two adjacent records, rejected inputs, encoded byte limits, incomplete streams, and the export regression described below. The checks use unittest, so optimisation does not remove them.
The implementation limits detail to 1,024 characters and the complete encoded record to 8,192 bytes. These are fixture choices, not recommended universal limits. Both checks are necessary for this encoder: some characters expand into longer escape sequences. The byte-budget test supplies non-BMP characters whose escaped representation exceeds the record budget even though the character count is allowed.
An oversized value raises an error before the function returns a record. The example does not silently truncate it or emit the raw rejected payload. A production caller needs a deliberate response, such as a separately bounded diagnostic event and an operational alert. Do not catch the error and fall back to logging the original string.
The small consumer in the download is a test helper. It accepts at most two record budgets, rejects missing final delimiters and parses each physical line. It is not a streaming collector, an event-schema validator or a malicious-producer defence. A real receiver must enforce those contracts independently of what this encoder promises.
Test the export that the reviewer actually reads
Encoding is reversible. When a dashboard parses the JSON, untrusted_detail again contains a real newline. If an export job concatenates that decoded value into the original plain-text template, it recreates the misleading approval line.
The final test deliberately performs that conversion and confirms the failure returns. This is why checking the producer’s JSON file alone is insufficient. Exercise the path through the collector, storage and final review view.
A multiline field is acceptable when the interface keeps it visibly inside one labelled event. A raw export intended for machine processing should retain structured framing. For a text-only review format, use an explicit escaped representation or a renderer with unambiguous field boundaries. HTML views also require HTML-safe rendering; JSON encoding is not an HTML escaping policy.
The same handoff problem appears in spreadsheet review exports, where a value must remain text after import. Here the invariant is event membership: a tool-returned string must not become a sibling event merely because another component decoded it.
An approval report should query application-owned approval events from the authorised producer. It should never derive approval from a regex match inside untrusted_detail. Even a perfectly framed event needs producer authentication and an enforced schema before the receiver can treat its envelope as authoritative.
Keep framing separate from confidentiality and integrity
JSON encoding preserves secrets as faithfully as it preserves the test payload. Before logging a detail field, decide whether it should be collected at all and apply the appropriate disclosure controls. The fixture contains no credentials and implements no redactor. The earlier secret-propagation article addresses why cleaning a final transcript cannot remove copies already sent elsewhere.
Likewise, one encoded line is not proof of one atomic write. This example constructs bytes in memory. It does not test concurrent writers, partial filesystem writes, log rotation, collector acknowledgements or crash recovery. Choose a transport and writer arrangement with a documented framing contract, then test failure and restart against that implementation. Do not infer filesystem atomicity from a successful json.dumps call.
For the wider engineering approach to agent tools and review evidence, see my Claude Code book, available as a Kindle edition on Amazon UK.
Add this payload to the actual logging integration test. Retrieve the event through the same export the reviewer uses, verify that it remains one tool_result, and verify that the approval query returns no additional decision. Keep the exported fixture with the test result so a later formatter change has something concrete to regress against.