You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
feat: Redact recorded content before it leaves the archive #1921
The session archive keeps prompts, completions and tool results raw
(core/session/archive/capture.go; the startup log says it "holds raw
prompts, completions and tool results"). That is right for the raw read
(?raw=1, docs/session-api.md) and for replay. Anything that carries
content off the machine, such as #1925 or a shared session, needs it
redacted first. core/redact covers config payloads and headers only, not
bodies.
Proposal
A redaction stage for request bodies and each SSE data: event:
Built-in rules: emails, personal names from a configured list, repository
and internal URLs, internal hostnames, credential-like strings.
A keyed alias for user ids, so the same user maps to the same alias within
one export, and the alias can't be reversed without the key.
User rules in config: extra terms and patterns.
A planted-secret test in the style of TestRecord_CarriesNoContent: plant
a value in every content field, run the stage, and fail if any survives.
We have this built and tested on real sessions outside Cortex, and would port
it.
Proposal (agreed with Hai, 2026-11-17): where it runs
The stored archive stays raw, as today, because the raw read and replay
depend on it.
This note covers what to build, and in which small PRs. No code yet.
1. What to port from claude-record's redactor
Source: the redactor of our (internal) Claude Code trace recorder, about 800 lines of Python with 79 tests, including the edge cases its reviewers found by running hostile inputs. Two kinds of rule:
A. Secrets. These are fixed-prefix regexes, and they map to Go RE2 almost 1:1.
API keys: Anthropic, OpenAI, AWS, GCP, GitHub, GitLab, HF, Slack, Stripe, npm, PyPI, SendGrid, Databricks, and Slack webhooks.
Private and PGP key blocks. RE2 supports lazy [\s\S]*?. Keep the [ ] trick, so the source never looks like a key header to secret scanners (IBM Vault Radar runs on commit).
JWTs, Bearer/Authorization: values, the password in connection strings and URL credentials.
A keyword plus a high-entropy value (Shannon ≥ 4.0). There's a safe-value list (UUIDs, toolu_/msg_ ids, 16/32-hex trace ids). One gap: the Python pattern uses a backreference \1 for the matching quote, and RE2 has none. Match "…", '…' and unquoted values as three alternatives instead.
Secrets inside base64. Decode runs of 64+ base64 characters and test the secret patterns on the decoded text.
B. Identity. This is where the Python leans on lookbehind and lookahead, which RE2 lacks (it has no lookaround at all).
Rules:
names: the user's own name; the listed colleagues (redact-names.txt), matched only Capitalized or UPPER; joined and login forms (dana-levi, dana.levi, danalevi); apostrophe forms; possessives redacted, n't contractions kept; Hebrew one-letter prefixes (ו ה ב כ ל מ ש, up to 3);
the OS username; extra terms;
emails (except git@, noreply);
GitHub owner/repo, with site sections and public owners kept;
internal hostnames by suffix (default res.ibm.com, plus redact-hosts.txt), in URL-encoded, double-encoded, escaped and UNC forms;
IBM Cloud account ids, in CRNs (raw, %3A, %253A, \/) and as account_id;
Claude Code user ids, replaced by a stable HMAC alias (user-<16 hex>) keyed with a local secret.
How to handle the missing lookaround: RE2 finds the candidate, and Go code checks the context.
A word start or end becomes a check of the rune before or after the match: unicode.IsLetter/IsDigit, _ allowed, and a JSON escape \n\t\r counts as a boundary unless the backslash is itself escaped.
The "contraction" and "%25" exceptions become checks on the following or preceding bytes.
Python's \w is Unicode, but Go's is ASCII. Use \p{L}\p{N} explicitly.
The word lists need a small matcher of their own, not a regex. These are the names, terms and usernames. The Python builds a trie regex that backtracks to a shorter word when the boundary check fails. Leftmost-first RE2 won't retry after a code-side rejection. So, at each position whose first rune is in the list's first-rune set, try the words longest first, with case folding (strings.EqualFold per candidate, with Turkish İ handled as the test pins). Accept the first one whose boundaries pass. That's linear in practice for tens to hundreds of names, and the "long name list stays fast" test pins it.
A gain: RE2 is linear-time. The % quadratic-time guard in the email rule and the deep-JSON recursion test are no longer a risk class.
C. JSON-in-JSON. Bodies are JSON, and tool arguments and results are JSON inside JSON strings. The Python works in two ways:
It redacts text, not parsed values. The replacements are plain ASCII with no quotes, so the JSON stays valid.
It first rewrites \uXXXX escapes of non-ASCII characters as the characters themselves (_json_letters_unescaped), because an escaped Hebrew name is invisible to every pattern. Unchanged text is kept byte for byte.
Port both. For Cortex this applies to whole request and response bodies too, not only to OTel attributes.
Not ported. These are claude-record-specific: the OTel JSON_ENCODED_KEYS and SAFE_KEYS lists (Cortex has no OTel attributes), and git identity lookup as the only source (see §3).
2. Where it plugs in
A new package, core/redact/content (name open): Redactor.Bytes(b []byte) ([]byte, Stats) and Redactor.String. It is built once from config. core/redact stays as it is (key-based stripping of config, headers and query). The new package may reuse CredentialName for header names.
Bodies:model.RequestCapture's Original, Forwarded, Translated, Response.Body and Response.Upstream.
SSE: redact the whole stream text. Each data: line is JSON, and the JSON rules above apply. A match never crosses a line, since the patterns can't contain \n (except key blocks, which need the whole body).
Events: the content-bearing fields of SessionEvent, the ones TestRecord_CarriesNoContent lists (inference text, tool arguments and results, MCP/A2A parts, paths, error messages), plus the fold's title.
Redact-at-save: in the archive writer, in write() before appendCapture, and before splitBody (capture.go). Two reasons: the content-addressed dedup must hash the redacted bytes, and nothing raw may reach disk. It runs on the writer goroutine, so request latency is unchanged; its cost shows up as queue depth. Also WriteSession, so agentop import is redacted too. The fold's title must be folded from the redacted event.
3. Config
redaction:
names_file: ~/.cortex/redact-names.txt # colleagues, one full name per linehosts_file: ~/.cortex/redact-hosts.txt # internal domain suffixesterms_file: ~/.cortex/redact-terms.txtnames: [] # inline, merged with the fileshosts: [] # default res.ibm.com is always on? (open)terms: []own_name: ""# the user's own name; default from git config user.name, if git is theresession:
archive:
redact_at_save: false
The files keep claude-record's format: # comments, a BOM is tolerated, host entries are normalized (https://a.b:8443/x, *.a.b), and a single-label host entry is warned about once.
The alias key lives in ~/.cortex/redaction-alias.key (0600), created on first use and never exported.
Identity source: Cortex runs as a service (launchd/systemd), where git config and the login name may not be the user's. So read the user's own name from config first and git second, and the OS username from the service's os/user. Say so in the docs.
Hot reload: only names, hosts and terms (the redactor is rebuilt and swapped atomically). redact_at_save changes take a restart.
4. Tests
A planted-secret test in the style of TestRecord_CarriesNoContent. Plant one secret of each category in every content field of an event and capture (request, SSE response, translated body, tool args as JSON-in-JSON, a \u-escaped Hebrew name). Assert that no planted value survives the encoded output, and that each category is counted. Plus a doc-count pin, like TestDocSecretCountMatchesAllSecrets.
Secret-shaped test data vs. secret scanners. Commits and pushes go through secret scanning (in our case IBM's Block Secrets, plus GitHub's own). So the tests never contain a complete realistic secret: they use obviously fake names and values, and assemble secret-shaped strings at runtime from pieces. Inline "ignore this line" markers aren't relied on; at least one scanner we use doesn't honour them.
Port all 79 Python cases, as table tests. That includes the reviewer-found edge cases: possessives and curly apostrophes; contractions kept; Hebrew prefixes; inner capitals (McDonald); hosts after %XX, UNC and escapes; a host followed by a TLD; URL-encoded CRNs; account-id forms; a stray apostrophe in the list; Turkish dotted İ; a BOM; byte-for-byte unchanged JSON; deep JSON; and the long name list staying fast.
A differential test (dev-only, not in CI): run the Python and Go redactors over the same fixture corpus, and require identical output, or a documented difference.
Archive: with redact_at_save, no planted secret is on disk (scan the segments, as the opt-out test does), and dedup still works on redacted bodies.
5. PR split (small, per Hai's rule)
PR A1:core/redact/content with the secret rules (§1A) and their tests. No wiring.
PR A2: the identity rules (§1B), the word-list matcher and JSON-in-JSON (§1C), with the config block (§3) and their tests. Still no wiring.
PR B:session.archive.redact_at_save: the writer hook, WriteSession, the fold title, and the archive test.
Default categories on export: secrets and identity both on by default, or identity opt-in? Our recorder's default is both. Identity redaction is driven by plain lists the user keeps, e.g. a names file (one colleague's name per line, like our recorder's redact-names.txt), plus the user's own name, emails and internal host suffixes.
Raw export: allowed at all? Behind a flag, loopback only, or not at all?
Redact-at-save scope: bodies only, or also the event fields and the fold title? If bodies only, the session list's title can still show a name.
GET /v1/sessions/{id}/events/{seq}?raw=1 and search: with redact-at-save off, the live API stays raw. Is that acceptable as "the archive stays raw", or should the read API redact too?
Identity values for a service process: config only, or also git and the OS user (§3)?
The res.ibm.com default: IBM-specific in an open-source repo. Keep it as an example only, with an empty default?
Aliasing user ids: wanted in Cortex at all, or just redact them?
Cost: base64 checks on multi-MB image bodies. Skip image content blocks by JSON path?
Languages: word boundaries are Unicode-aware, so names are found in most languages that put spaces between words, and Hebrew's one-letter prefixes (ו, ה, ל, ב, מ, ש, כ glued onto a name) get special handling. Not covered: inflected names (in Russian or Polish, "Ivan" becomes "Ivana" or "Ivanu" depending on its role in the sentence), and languages written without spaces (Chinese, Japanese). Document these as known limits, or handle the inflection with user-supplied variants in the names file?
Comments welcome, especially on the open questions in section 6.
Design update, after testing a first A1 against raw bodies
A first version of A1 applied the ported rules to raw bytes, as the design above proposed. Testing it on real body shapes showed that it doesn't work:
Corruption: patterns could match across JSON values, or across SSE events, which corrupted the output.
Missed secrets: a key split across stream deltas was never seen whole, and several real formats slipped through.
False positives: random image data could match a rule.
Cost: large base64 bodies were slow.
The rules were written for clean text values, and raw bytes carry JSON quoting, escapes and SSE framing. So the design changes in five places:
The rules see decoded text values only.Find(text, ctx) returns edits: byte ranges with a category, and Apply writes the markers. It knows nothing of framing. Every rule is still written to be safe on raw bytes: tight character classes and token boundaries.
JSON: string-span splicing.
A small scanner finds each string literal in the raw body, decodes it, redacts it, and re-encodes only the strings that changed. Everything else is kept byte for byte: key order, whitespace, numbers, escapes.
An unchanged body is identical.
JSON inside a string (tool arguments) is walked too.
The value's key is passed as context ("password": "…").
Decoding also removes the need for a separate \uXXXX step.
SSE: reassemble, then map back.
Each content block's text (text, thinking, tool-argument JSON) is reassembled from its deltas, so a secret split across deltas is found.
Each redaction is then mapped back onto the original delta boundaries. The marker goes into the first delta it touches, and the following deltas lose the rest of the secret.
Event count, order and framing are kept, so a replay keeps the stream's shape.
One consequence: a redaction inside a thinking block makes its signature invalid, so such an export cannot be sent back to Anthropic. The export will count and mark the affected calls (details on feat: Export a session with its content, in replay formats #1925).
Images and binary are skipped by JSON path: base64 image, document and audio data, and data: URIs. Skips are counted. This answers open question 8. A secret inside an image or an attached PDF is not found; the docs will say so.
Rule changes:
provider prefixes need a token boundary;
a URL's password runs up to the last @ before the host, so it may contain @, / or #, and never crosses quotes or whitespace;
Authorization and bearer values use the full base64 alphabet;
more key formats;
the keyword rule gets tiers by name: password names need 6 or more characters and no entropy floor; other secret names need a generated-looking value, with entropy relative to its alphabet, so hex tokens are found;
a one-pass prefilter, so a rule runs only where its trigger appears.
Keys are redacted only by the identity rules (A2), not by the secret rules.
New PR split: A1 is the text API and the rules, now up as #2068 (after two more review rounds on the rules themselves). A1b is the JSON scanner and the skips. A1c is SSE reassembly. Then A2 (identity), B (redact-at-save) and the export, as before.
Tests added to the plan: JSON validity after every case, SSE framing and split keys, a false-positive corpus that must come through unchanged, adversarial inputs with a time bound, and size benchmarks.
Activity
michaljacovi commentedon Nov 19, 2026
Design before the first PR
Agreed in #1920:
This note covers what to build, and in which small PRs. No code yet.
1. What to port from claude-record's redactor
Source: the redactor of our (internal) Claude Code trace recorder, about 800 lines of Python with 79 tests, including the edge cases its reviewers found by running hostile inputs. Two kinds of rule:
A. Secrets. These are fixed-prefix regexes, and they map to Go RE2 almost 1:1.
[\s\S]*?. Keep the[ ]trick, so the source never looks like a key header to secret scanners (IBM Vault Radar runs on commit).Bearer/Authorization:values, the password in connection strings and URL credentials.toolu_/msg_ids, 16/32-hex trace ids). One gap: the Python pattern uses a backreference\1for the matching quote, and RE2 has none. Match"…",'…'and unquoted values as three alternatives instead.B. Identity. This is where the Python leans on lookbehind and lookahead, which RE2 lacks (it has no lookaround at all).
redact-names.txt), matched only Capitalized or UPPER; joined and login forms (dana-levi,dana.levi,danalevi); apostrophe forms; possessives redacted,n'tcontractions kept; Hebrew one-letter prefixes (ו ה ב כ ל מ ש, up to 3);git@, noreply);res.ibm.com, plusredact-hosts.txt), in URL-encoded, double-encoded, escaped and UNC forms;%3A,%253A,\/) and asaccount_id;user-<16 hex>) keyed with a local secret.unicode.IsLetter/IsDigit,_allowed, and a JSON escape\n\t\rcounts as a boundary unless the backslash is itself escaped.\wis Unicode, but Go's is ASCII. Use\p{L}\p{N}explicitly.strings.EqualFoldper candidate, with Turkish İ handled as the test pins). Accept the first one whose boundaries pass. That's linear in practice for tens to hundreds of names, and the "long name list stays fast" test pins it.%quadratic-time guard in the email rule and the deep-JSON recursion test are no longer a risk class.C. JSON-in-JSON. Bodies are JSON, and tool arguments and results are JSON inside JSON strings. The Python works in two ways:
\uXXXXescapes of non-ASCII characters as the characters themselves (_json_letters_unescaped), because an escaped Hebrew name is invisible to every pattern. Unchanged text is kept byte for byte.Port both. For Cortex this applies to whole request and response bodies too, not only to OTel attributes.
Not ported. These are claude-record-specific: the OTel
JSON_ENCODED_KEYSandSAFE_KEYSlists (Cortex has no OTel attributes), and git identity lookup as the only source (see §3).2. Where it plugs in
core/redact/content(name open):Redactor.Bytes(b []byte) ([]byte, Stats)andRedactor.String. It is built once from config.core/redactstays as it is (key-based stripping of config, headers and query). The new package may reuseCredentialNamefor header names.model.RequestCapture'sOriginal,Forwarded,Translated,Response.BodyandResponse.Upstream.data:line is JSON, and the JSON rules above apply. A match never crosses a line, since the patterns can't contain\n(except key blocks, which need the whole body).core/redact.Headersalready strips credentials.SessionEvent, the onesTestRecord_CarriesNoContentlists (inference text, tool arguments and results, MCP/A2A parts, paths, error messages), plus the fold'stitle.write()beforeappendCapture, and beforesplitBody(capture.go). Two reasons: the content-addressed dedup must hash the redacted bytes, and nothing raw may reach disk. It runs on the writer goroutine, so request latency is unchanged; its cost shows up as queue depth. AlsoWriteSession, soagentop importis redacted too. The fold's title must be folded from the redacted event.3. Config
#comments, a BOM is tolerated, host entries are normalized (https://a.b:8443/x,*.a.b), and a single-label host entry is warned about once.~/.cortex/redaction-alias.key(0600), created on first use and never exported.git configand the login name may not be the user's. So read the user's own name from config first and git second, and the OS username from the service'sos/user. Say so in the docs.names,hostsandterms(the redactor is rebuilt and swapped atomically).redact_at_savechanges take a restart.4. Tests
TestRecord_CarriesNoContent. Plant one secret of each category in every content field of an event and capture (request, SSE response, translated body, tool args as JSON-in-JSON, a\u-escaped Hebrew name). Assert that no planted value survives the encoded output, and that each category is counted. Plus a doc-count pin, likeTestDocSecretCountMatchesAllSecrets.%XX, UNC and escapes; a host followed by a TLD; URL-encoded CRNs; account-id forms; a stray apostrophe in the list; Turkish dotted İ; a BOM; byte-for-byte unchanged JSON; deep JSON; and the long name list staying fast.redact_at_save, no planted secret is on disk (scan the segments, as the opt-out test does), and dedup still works on redacted bodies.5. PR split (small, per Hai's rule)
core/redact/contentwith the secret rules (§1A) and their tests. No wiring.session.archive.redact_at_save: the writer hook,WriteSession, the fold title, and the archive test.6. Open questions (Hai, Mariusz)
redact-names.txt), plus the user's own name, emails and internal host suffixes.GET /v1/sessions/{id}/events/{seq}?raw=1and search: with redact-at-save off, the live API stays raw. Is that acceptable as "the archive stays raw", or should the read API redact too?res.ibm.comdefault: IBM-specific in an open-source repo. Keep it as an example only, with an empty default?imagecontent blocks by JSON path?Comments welcome, especially on the open questions in section 6.
Assisted-By: Claude (Anthropic AI) [email protected]
Docs: Add the gap split and the collection/export boundary to the spec
Docs: Spec the toolCall export record, and correct the per-tool laten…
michaljacovi commentedon Nov 22, 2026
Design update, after testing a first A1 against raw bodies
A first version of A1 applied the ported rules to raw bytes, as the design above proposed. Testing it on real body shapes showed that it doesn't work:
The rules were written for clean text values, and raw bytes carry JSON quoting, escapes and SSE framing. So the design changes in five places:
Find(text, ctx)returns edits: byte ranges with a category, andApplywrites the markers. It knows nothing of framing. Every rule is still written to be safe on raw bytes: tight character classes and token boundaries."password": "…").\uXXXXstep.data:URIs. Skips are counted. This answers open question 8. A secret inside an image or an attached PDF is not found; the docs will say so.@before the host, so it may contain@,/or#, and never crosses quotes or whitespace;New PR split: A1 is the text API and the rules, now up as #2068 (after two more review rounds on the rules themselves). A1b is the JSON scanner and the skips. A1c is SSE reassembly. Then A2 (identity), B (redact-at-save) and the export, as before.
Tests added to the plan: JSON validity after every case, SSE framing and split keys, a false-positive corpus that must come through unchanged, adversarial inputs with a time bound, and size benchmarks.
Assisted-By: Claude (Anthropic AI) [email protected]
fix: Address review of core/redact/content
fix: Fix two regressions from the last review round
fix: Keep key-block headers linear, and keep passwords ending in "/"
fix: Bound the query-string rescan, and keep \u headers and quoted my…
fix: Redact a quoted mysql password inside an outer quote, and budget…
fix: Name digits, wrapped base64, and reference and call shapes
fix: Join two-line base64 blocks, and narrow $NAME and PASS1 names
fix: Redact letters-only passwords, $Word-2024 and unknown auth schemes
feat: Add core/redact/content, secret rules for text values
feat: Redact JSON bodies value by value, keeping every other byte
fix: Keep raw-JSON code pieces around mysql -p, and end a password at…
fix: Give each rescan run a floor, and pin the per-run budget in a test
fix: Count the plural secret names: passwords, api_keys
fix: Replace a URL password with "@" that ends in "/" whole
fix: Narrow the "/@" host choice and the mysql redirect to their cases
feat: Redact JSON bodies value by value, keeping every other byte
fix: Keep raw-JSON code pieces around mysql -p, and end a password at…
fix: Give each rescan run a floor, and pin the per-run budget in a test
fix: Count the plural secret names: passwords, api_keys
fix: Replace a URL password with "@" that ends in "/" whole
fix: Narrow the "/@" host choice and the mysql redirect to their cases