48. Secrets, audit and supply chain
Chapter 47 put a gate between the model’s proposed call and the tool that would run it. The gate decides what may happen next. This chapter is about what the daemon holds while it decides, what it keeps as evidence of what it did, and what it agrees to run in the first place. The code is internal/secrets (a credential broker, the one redactor the tree writes files through, and the process hardening), internal/audit (a hash-chained, head-signed log, the writer that derives records from the trace, and the manifests that pin a skills directory and an MCP server), its wiring in internal/daemon/audit.go, the commands aecd audit and aecd vet, the flag -dumpable, and the lab go/labs/ch48. The log records names, hashes and counts. It never records what anyone said.
Why this layer exists
Part VII’s daemon holds its authority in several places and writes about itself in several files, and none of them was built to survive its own uid. route.Clients reads each provider’s api_key_env once at start (chapter 28). The Mattermost adapter reads its token_env at each use (chapter 41), and so does the Streamable HTTP client for an MCP server’s bearer token (chapter 44); aecd mcp -http reads its own at start. A command server gets whatever pass_env names, a grant the reader wrote. On this book’s host the file the Mattermost token is sourced from has mode 0600 (stat read the mode and nothing of the content). Beneath all of those is the daemon’s own environment, which /proc/<pid>/environ serves to any process that passes a ptrace read check.
What the daemon writes is faithful and unprotected. session.jsonl is the transcript, and it is what the model saw. traces/ holds the spans, ledger.jsonl the durability record (chapter 40, fsynced, unhashed), trials.jsonl one line per turn. Each is mode 0600 in a directory of mode 0700, which keeps other users out and does nothing about the daemon’s own uid, and each can be rewritten by any process of that uid without leaving a mark. What this chapter chains is its own log of hashes of what the daemon did; traces/ itself stays editable (chapter 49 records each closed trace’s hash on turn_end, so an edit of a recorded trace leaves a mark against the chain). The daemon trusts a configuration word: a server marked trusted has its calls unmarked and its readOnlyHint believed (chapter 44), and a skills directory is loaded whole (chapter 36).
Chapter 48 owns the part of this that is particular to an agent, and spec §4 says so: no TLS, Linux or secrets-101 primer.
There are two adversaries. The first is chapter 46’s: someone who got text into a turn, who can make the model propose a call and cannot touch the daemon’s files. The second is a process of the reader’s own uid, which is every program he runs, including the ones a bad call starts. SO_PEERCRED (unix(7): the credentials of the connecting process at connect time) on the control socket establishes that a connecting process has the daemon’s uid, and checkPeer refuses any other before a byte is read (chapter 40). The second adversary has that uid, so the check proves nothing against it. (A second uid has not been tried end to end, since the host has none; the tests make the check refuse by changing the daemon’s idea of its own uid, with a mutant that turns it off.) The audit log is built so that a rewrite by the second adversary is detectable by someone who holds one number the adversary could not reach, and the chapter says in every section what that costs and what it leaves.
Mechanism
The broker
aecd.json gains a secrets block, a map from a logical name to an environment variable name ("zai": "ZAI_API_KEY"). secrets.Open reads each variable once, at start.
// Broker holds the values. Spec maps a logical name to a variable name
// (aecd.json's "secrets": {"zai": "ZAI_API_KEY", "mattermost":
// "AEC_MATTERMOST_TOKEN", "mcp_http": "AEC_MCP_TOKEN"}); Open reads each at
// start and refuses, naming the variable and never its value, when one is
// unset or empty, as route.Clients does. Token hands a value to the daemon's
// own clients; Names lists what is held; Redactor returns the values-first
// redactor over everything the daemon writes.
type Broker struct {
values map[string]string // logical name -> value
names map[string]string // logical name -> variable name
}
var ErrUnset = errors.New("secrets: a named variable is unset or empty")
// varName is what a variable may be called: an identifier, so a spec that
// pastes a value where a name belongs is refused before anything is read.
var varName = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
// Open reads every variable spec names, in sorted order of the logical
// names, and returns the broker or the first refusal. The error names the
// logical name and the variable; it never carries a value.
func Open(spec map[string]string) (*Broker, error) { return OpenFrom(spec, os.LookupEnv) }
// Token is the value held under a logical name.
func (b *Broker) Token(name string) (string, bool) {
if b == nil {
return "", false
}
v, ok := b.values[name]
return v, ok
}
// Redactor is the values-first, deep redactor over everything the daemon
// writes (the audit log's inputs and the trace under a secrets block).
func (b *Broker) Redactor() Redactor {
if b == nil {
return Redactor{Deep: true}
}
// Only a value of minValue bytes or more: a shorter one (a locale name in a
// pass_env that the completeness check made the block list) would redact
// ordinary text wherever it occurs. A variable like HOME that is listed
// anyway has its value redacted everywhere it is written; the block is for
// credentials.
vals := make([]string, 0, len(b.values))
for _, v := range b.values {
if len(v) >= minValue {
vals = append(vals, v)
}
}
return Redactor{Values: vals, Deep: true}
}
Open is OpenFrom over the process environment; chapter 51’s aecd serve and aecd mcp pass a reader that looks in systemd’s credentials directory first (the -http listener’s own token is still read from the environment, below). The loop is OpenFrom’s:
// OpenFrom is Open with the reader of variables injected: Open passes
// os.LookupEnv. aecd serve passes a reader that looks in
// $CREDENTIALS_DIRECTORY/<variable> first when systemd set that directory
// (LoadCredential=, chapter 51's module), then the environment, so a token
// a unit was given as a credential file never has to be an environment
// variable at all. The value is read once, here, and never again. A nil
// lookup is os.LookupEnv.
func OpenFrom(spec map[string]string, lookup func(string) (string, bool)) (*Broker, error) {
if lookup == nil {
lookup = os.LookupEnv
}
b := &Broker{values: map[string]string{}, names: map[string]string{}}
logical := make([]string, 0, len(spec))
for k := range spec {
logical = append(logical, k)
}
sort.Strings(logical)
for _, k := range logical {
v := spec[k]
if k == "" || !varName.MatchString(v) {
return nil, fmt.Errorf("secrets: %q names %q, which is not a variable name", k, v)
}
val, ok := lookup(v)
if !ok || val == "" {
return nil, fmt.Errorf("%w: %s (secrets.%s)", ErrUnset, v, k)
}
b.values[k], b.names[k] = val, v
}
return b, nil
}
A variable that is unset or empty is refused with its name and the logical name that asked for it, and the error never carries a value. A value that is not an identifier where a variable name belongs is refused before anything is read: a configuration that pasted a key into the block would otherwise be looked up as a variable, found unset, and reported as unset, hiding that the key is now in a file.
The block is the whole list. With one present, Open runs the completeness check: a provider whose api_key_env, a gateway or MCP server whose token_env, a server whose pass_env, or the daemon’s own mcp_serve.token_env, names a variable the block does not list, is refused at start, naming the variable and the place that named it. The reason is the redactor. A value can only be replaced by equality if the daemon knows it, and a variable that reached a client without passing through the block is one the redactor does not know. Without the block every reader reads its own variable as in Part VII, byte for byte (TestNoBlocksIsPartVII).
The broker also hands the values to the clients. route.ClientsWith(cfg, lookup) builds the same clients route.Clients does, with the lookup given (Clients is ClientsWith over os.LookupEnv, so chapter 28’s tests are unchanged), and the daemon passes the broker’s Value. The Mattermost adapter and the Streamable client gained a Token field that is used in place of reading token_env. One reader still reads its variable itself: aecd mcp -http takes the bearer token for its listener from the environment, and the block checks only that the variable is among those listed.
What reaches a tool is unchanged by the block. Chapter 27’s allowlist, chapter 43’s Isolation.Env and chapter 44’s serverEnvNames decide what a child sees; none of them holds a brokered value except through pass_env, which is the reader’s explicit grant. Under the block, a pass_env name must be listed, and it is written by name to the mount record of the server it was granted to. Two holes were open. The first is that grant, which is the reader’s. The second is the environment of the daemon itself.
Hardening: why one prctl closes the environment read
Chapter 43 measured that code a model runs in the plain or scope-only sandbox can read /proc/<ppid>/environ and get every variable the daemon holds, and left the fix unbuilt. The question is why a process of the same uid is allowed. proc_pid_environ(5) says that access to the file is “governed by a ptrace access mode PTRACE_MODE_READ_FSCREDS check”, and ptrace(2) gives the algorithm for such a check. Step 3 denies unless the target’s real, effective and saved user and group IDs match the caller’s, or the caller has CAP_SYS_PTRACE in the target’s user namespace. A same-uid caller passes. Step 4 then reads:
Deny access if the target process “dumpable” attribute has a value other than 1 (
SUID_DUMP_USER[…]), and the caller does not have theCAP_SYS_PTRACEcapability in the user namespace of the target process.
The attribute is the one prctl(PR_SET_DUMPABLE, 0) clears, and PR_SET_DUMPABLE(2const) adds that when it is clear “the ownership of files in the process’s /proc/pid directory” changes. A caller without the capability is refused at step 4 for every access mode, READ included. The one syscall is the fix, and Harden is nothing else.
// Harden sets PR_SET_DUMPABLE to 0 on Linux, so same-uid code cannot
// read /proc/<pid>/environ or ptrace the daemon, at the price of no core
// dump; a no-op elsewhere. aecd serve and aecd mcp call it unless -dumpable.
func Harden() error { return hardenOS() }
// Dumpable reads the attribute back (PR_GET_DUMPABLE); true where the
// system has no such attribute.
func Dumpable() (bool, error) { return dumpableOS() }
Yama’s ptrace_scope is not part of this. ptrace(2) says the Yama LSM limits PTRACE_MODE_ATTACH checks and PTRACE_TRACEME, and the environment read is a READ check, which Yama does not limit. That is why the file was readable at ptrace_scope 1, which is the setting on wntrmute and on straylight (both read 1; suid_dumpable reads 2 on both, which the page gives as what the attribute resets to when a process’s credentials change).
The measurement, on wntrmute, with a sentinel that is not a credential planted in the daemon’s environment and read by a same-uid process (a short script outside the tree):
### aecd serve
owner of /proc/PID/environ: uid 0 (mine: 1000)
read /proc/PID/environ: Permission denied
### aecd serve -dumpable
owner of /proc/PID/environ: uid 1000 (mine: 1000)
read /proc/PID/environ: 9819 bytes, sentinel found
The first is the default and the second is the flag. The tests that hold this are TestHardenHidesEnviron (a re-exec’d child under Harden answers permission denied to its parent’s read, and the opt-out child is readable with the planted sentinel), TestServeHardens and TestMCPHardens (the daemon binaries call it), TestVetHardens (the same for aecd vet mcp, whose command servers are children of the vetting process), and each fails when its call is removed. They pass on wntrmute and, in the gate, on straylight.
The cost is in the page’s first sentence: whether core dumps are produced. A hardened aecd that crashes leaves nothing for coredumpctl, and -dumpable restores the old behaviour on serve, mcp and vet mcp. The default is to harden and pay that, and the flag is one word. Hardening protects the daemon’s environment and no other process’s: code that runs as the reader’s uid can still read the environment of every other process of that uid that has not done the same, so a secret does not belong in the environment of anything else the reader runs.
“Acting as” is chapter 40’s other half: it gave the daemon an explicit principal, and chapter 48 adds the audit line per outward action and one list of the credentials the daemon holds. One daemon acts for one principal, so the broker holds that daemon’s credentials and the log is that principal’s; credentials per principal are not built, as follows. Every record that is about an action names its Actor: principal, peer:<id> for a non-principal’s turn, sched for a job, worker for a delegate’s call (on the approval and tool records, which read the call’s owner; a policy record names the turn’s actor and session, because the gate decides before the batch’s owner is registered), daemon for the daemon’s own. The credential an action used is the one its provider’s api_key_env names, and a record names the provider, so the broker’s logical names are enough to say which credential was used and never what it was. A second principal is a second state directory; per-principal brokering would need a keyring, a tool set and gate rules per principal, and is not built. The agent value the record’s comment lists as an actor is unused: the model’s calls are the turn’s principal’s authority (chapter 27).
One redactor, two strengths
Chapter 21’s rule for text that leaves the reader’s hands, which was Python, and chapter 24’s, which was four patterns in aec-capture, are now one function.
// Redactor replaces, in this order, every known value (so a value that
// itself holds a shape is replaced whole), then every shape in Patterns:
// chapter 24's rule, which eval.Redact and cmd/aec-capture keep, so Part
// VI's committed trials and traces stay fixed points. With Deep set (the
// daemon's audit and trace paths) it also replaces, before the shapes,
// every base64 token that decodes to printable text holding a secret, and
// after them every value a secret's name announces (NAME=VALUE, "name":
// "value", NAME VALUE, --flag VALUE) and every high-entropy run of 24 or
// more base64 characters, judged one path segment at a time (chapter 21's
// whole rule, with the hex and UUID facts re-measured in Go). A 32-character
// provider call id is kept by the shallow form and goes under Deep: the
// two strengths are named in the chapter. Every pattern is RE2 and linear,
// and the value scanner is one pass; a timing test holds the pipeline, and
// the patterns together, to linear growth on adversarial input.
type Redactor struct {
Values []string
Deep bool
}
const R = "[REDACTED]"
// Patterns is the one shape list the tree uses: eval.Redact and
// cmd/aec-capture's redactText call Redactor so the three sets cannot drift.
var Patterns = func() []*regexp.Regexp {
out := make([]*regexp.Regexp, len(shapes))
for i, s := range shapes {
out[i] = s.re
}
return out
}()
// Redact is the whole pipeline over decoded text. Run it on parsed JSON
// values (RedactJSON), never on raw JSON text, where a JSON escape (a
// backslash, a u and four hex digits standing for a hyphen) hides what a
// pattern looks for.
func (r Redactor) Redact(s string) string {
s = r.values(s)
if !r.Deep {
return shapesOnly(s)
}
s = b64RE.ReplaceAllStringFunc(s, secretB64)
return redactText(s)
}
// RedactJSON redacts every string of a parsed JSON value, keys included, and
// replaces whole the value under a key that names a secret; two keys that
// redact to the same string are refused.
func RedactJSON(v any, r Redactor) (any, error) { return r.redactJSON(v, 0) }
eval.Redact and aec-capture keep the shallow form, so Part VI’s committed trials and traces are fixed points of the new code (the chapter 26 and 37 goldens are byte for byte what they were), and a provider’s 32-character call id survives it, which is what lets a trial link to its spans. The deep form is the daemon’s, and a call id goes under it.
Values go first, and the order is the point. A planted value that itself holds a token shape (sk- followed by its own tail) would otherwise be cut by the shape, leaving the part before and after it; replacing the whole value first makes the shape unnecessary for it. A header, Authorization: Bearer <token>, is replaced whole, name and token, and a header whose token had already gone by value is still replaced whole, because the shape accepts [REDACTED] where a token goes.
Why this is a scanner and not a list of regular expressions. Chapter 21’s patterns use a conditional on the opening quote, a backreference to it, and lookahead. RE2 has none of them, and the part’s rule for a pattern over untrusted text is that it is RE2 and linear. So the announced formats (private-key blocks, sk-, xai-, ghp_, hf_, AWS key ids, JWTs, scheme://user:password@, docker’s "auth", query parameters, .netrc and .pgpass) are RE2 shapes, and the named-secret forms (NAME=VALUE, "name": "value", NAME VALUE, --flag VALUE) are found by a regular expression that matches only the name and its separator, after which scanValue reads the value in code.
The reason a value cannot be a pattern is a count. In a quoted value a backslash takes the character after it. If a backslash could also stand alone as a unit, a run of backslashes could be split into units in ways. The first unit is one backslash or two, so , with and : the Fibonacci numbers, growing by a factor per backslash (the ratio computed here is 1.6180), and a failed match tries every split. With the rule “a backslash always takes the next character” a run has one parse, and the scanner is one pass. The whole pipeline, and the patterns run together, are held to linear growth over runs of up to 40,000 backslashes in each quoted form and 160 kB of x_key_key_…, a-a-…, a.a.… and blank lines, alone and inside a teacher prompt. The test asserts a ratio, not a time, because a time limit fails on a loaded host. The cost of 16x the input, measured in the process’s CPU time beside the cost of 1x, may be at most 60x. Linear work costs 16x, a pure quadratic 256x, and a backtracking match is exponential in the run (TestRedactorTiming, passing on straylight; TestRedactorTimingDetectsQuadratic shows that a scanner which rescans from every position exceeds the limit). The Python module’s slowest adversarial call was 0.17 s (talos, 2026-09-30).
The scanner decodes runes: 0x85 and 0xA0 are continuation bytes of à, Å and ą, and a byte-wise space test would cut a secret there and leave its tail (TestBareValueNotCutInsideARune).
Where Go answers differently from Python, and in which direction. Parity is not the goal; erring closed is. Every row of the Python test tables was run in Go (TestRedactorSecrets, TestRedactorKeepsOrdinaryText, TestRedactorStructure), and the rows that differ are listed in TestRedactorPort:
- A header goes whole. Python keeps
Authorization: Bearerand replaces the token; Go removes the header (curl -H 'Authorization: Bearer ghp_…' xbecomescurl -H '[REDACTED]' x, on wntrmute). This errs closed. - The
sk-shape’s floor is 8 characters where Python’s is 16,bearerneeds no word boundary, and anauthorizationvalue has no length floor. Each errs closed. - A quoted value stops at a line end in every form. Python lets a plain character be a newline and redacts
API_KEY="abcnewlinedef0123456789"; Go keeps it whole. This errs open: a secret quoted across a line is not found. - An empty quoted value,
PASSWORD="", is kept whole where Python replaces it. This errs open, and nothing is lost: there is no value.
What Go keeps and Python also keeps, because a security feature reads it (chapter 28’s f_struct): a path. A value is not replaced when it starts with /, ~, $, ., - or a backslash, or holds /. or .ssh, or holds * or ? with a /, so --token=~/.ssh/token survives, and so does a bare number (max_token: 512). The price is exactly those values: a secret that starts with one of those characters is kept. For a key it is small, since ., *, ?, ~, $ and the backslash are in neither base64 alphabet. And NOPASSWD:ALL stays, because the name pattern is password and not passwd: an earlier draft of the Python pattern erased ALL from kyle ALL=(ALL) NOPASSWD:ALL, the string that makes the call dangerous.
The entropy rule, and a bound that is true at equality. The last stage looks at runs of 24 or more characters from the base64 and base64url alphabets (a JSON-escaped \/ stays inside a run) and replaces a run whose empirical entropy is at least 4 bits per character when it mixes letters and digits, or at least 4.5 bits when it is letters only. For a run of length in which the distinct characters occur times,
How high can go? Let be a distribution over the characters that occur and the uniform one over the same characters. The Gibbs inequality (chapter 4) is with equality only when , and so
using . Hence , with equality only when every character occurs equally often. Three things follow.
- A hexadecimal string never exceeds 4 bits per character. For hex, , so . The bar is “at least 4”, so equality redacts: a string in which all sixteen digits occur equally often scores exactly 4.0 and goes (
0123456789abcdef0123456789abcdefis replaced;TestBalancedHexIsRedactedpins it). How often a random hex string lands on it is a count: a balanced 32-digit string has each digit exactly twice, so the number of balanced strings is , out of : a probability of . For 64 digits it is out of , (both computed exactly, outside the tree). A 24-digit run cannot be balanced, because 24 is not a multiple of 16; its maximum is eight digits twice and eight once, 3.918 bits (moving one occurrence from a more frequent character to a less frequent one raises , so the most even split of 24 over 16 maximises it). A 40-digit git commit id cannot reach 4 either: the most even split of 40 over sixteen digits is eight digits three times and eight twice, 3.971 bits, so every commit id is kept and a tool call full of them stays readable (the commit id chapter 21’s redaction tests keep,1d1a95cb…, scores 3.835, and the 40-digit idc062ba22…, a commit of this part, scores 3.516, computed outside the tree). - A run with no digit needs at least 23 distinct characters, since its bar is 4.5 and and is an integer. The name
the_quick_brown_fox_jumps_over_itscores 4.127 and is kept. - A UUID has a seventeenth character. Its hyphens are in the run alphabet, so and ; a few random version-4 UUIDs pass 4 bits.
The counts below come from TestRedactorCounts: 100,000 random strings of each kind, one draw per character from a PCG generator seeded with (0, 0), the same on wntrmute and straylight. Python’s came from random.Random(0) on straylight on 2026-09-30, so the samples differ and the rule is the same, and no claim is made that two machines or two languages draw alike.
| Kind | Go (wntrmute and straylight) | Python (straylight, 2026-09-30) |
|---|---|---|
| hex, 32 digits | 0 of 100,000 redacted, highest entropy 3.976 | 0, highest 3.953 |
| hex, 64 digits | 0 of 100,000, highest 3.977 | 0, highest 3.983 |
| UUID version 4 | 3 of 100,000, highest 4.017 | 6, highest 4.017 |
| base64, 24 characters | 90.30% redacted; of the 9,703 kept, 5,916 under their entropy bar and 5,526 holding a / |
90.43%; of the 9,573 kept, 5,859 and 5,447 |
| base64, 40 characters | 99.04%; of the 962 kept, 10 under the bar and 956 holding a / |
99.08%; of the 917 kept, 915 held a / |
a / in the 40-character strings that hold one |
956 of 46,965 kept, 2.04% | 1.96% |
The residue in the last row is the path rule’s price. A run that starts with /, or whose slash-separated segments are mostly not a mix of upper case, lower case and digits, is judged one segment at a time, so /var/lib/postgresql/16/main/base/16384 (4.112 bits whole) has no segment of 24 characters and is kept, and a store path keeps its /nix/store/ prefix and loses the segment that holds the hash. A 40-character key with a slash in it and no name before it is kept about one time in fifty (2.04% on the Go draw); with its name before it, as after AWS’s aws_secret_access_key, the named form catches it whatever its entropy. A key-format pattern never depends on luck, which is why the known formats come first.
The rule also costs on public hashes. The narHash in this repository’s flake.lock, sha256-ZoxIApko70jCdbH3l20HWXOBaT2HZd87orzd2yJ9dVE=, is a 51-character run at 5.015 bits, and the deep form replaces it. The shallow form keeps it, since the shallow form has no entropy stage.
What goes through which strength. The audit log’s records hold no text, so the redactor is not what keeps text out of them; the next section and TestNoTextInRecords are. What the daemon writes or posts beyond the audit log, and which stage each gets:
trials.jsonl: the shallow form (eval.Redact, as in Part VI) and then the broker’s values. The values pass is the fix for a variable that is not named*_API_KEYor*_TOKEN, which the shallow form’s environment scan never saw.- Trace attributes: under a
secretsblock only, the shallow form plus the broker’s values, through a writer between the tracer and the file. A provider’s call id survives, so anapprovalrecord still joins its trace line. What trace attributes do not get is the entropy stage, the named-value scanner and the base64 pass: a secret that only the entropy rule would catch (a bare high-entropy key with no announced shape, held by no variable the block lists) can reach a trace attribute. That is the cost of keeping ids. A tool’s error text does not reach an attribute (atool_callspan carries a result kind); what carries tool-supplied text is theapprovalspan’sreason, where the test plants the value. - Channel text, under a block: a reply, a delivery and an approval request displayed to the principal have the broker’s values taken out (the call’s hash, id and nonce are untouched, so the answer still binds to the call that was asked about). A chat server is off the machine.
- Not covered:
session.jsonl, which is faithful and the reader’s evidence (mode 0600; a redactor over it would make a second, weaker transcript), and the body fileskeep_bodieswrites, which are inspection material the reader opted into.
TestNothingSecretIsWritten plants a value in a variable named AEC_TEST_SECRET, has a tool hand it to the model once as a result and once as an error, has the model repeat it in its answer, and then looks for it in every line of the audit directory, every trial, every attribute of the trace and every log line and warning. It is in the session file and nowhere else.
The audit log
What a record is. A record is a name, a hash, a decision and a handful of short attributes. Nothing in it is model text or the reader’s text.
// Record is one audited event. Kind is one of the closed set Kinds; Subject
// names what it is about (a tool name, a provider, a channel, a section
// Source, a server prefix); Hash is the sha256 of the subject's content (a
// call's hash, a request_hash, a section's text, a tool list) and never the
// content itself; Private says the turn was private. Nothing in a record
// is model text or the reader's text: the audit log is about what happened,
// and the session file and the trace hold what was said.
type Record struct {
Seq uint64 `json:"seq"`
At time.Time `json:"at"`
Kind string `json:"kind"`
Session string `json:"session,omitempty"`
Turn int `json:"turn,omitempty"`
Actor string `json:"actor,omitempty"` // principal | agent | sched | peer:<id> | daemon | worker
Subject string `json:"subject,omitempty"`
Hash string `json:"hash,omitempty"`
Decision string `json:"decision,omitempty"`
Reason string `json:"reason,omitempty"`
Private bool `json:"private,omitempty"`
Attrs map[string]string `json:"attrs,omitempty"`
}
// Kinds is the closed set: Verify refuses any other.
var Kinds = []string{
"open", "close", "config", // the daemon started with these file hashes; stopped; a configuration file's hash
"turn_begin", "turn_end", // a turn, with its peer, channel and privacy
"section", // a system-prompt section by Source, with its text's hash (identity, operator, user-model, skills-index)
"policy", // a chapter 47 Decision
"approval", // an approval request and its answer, with the nonce and the call hash
"tool", // an outward tool call: network, write_outside, exec, mcp
"model", // a model call: provider, model, request_hash
"embed", // an embedder call: host, number of texts
"send", // a gateway send: channel, conversation, bytes
"mount", // an MCP mount: server, trust, the tool list's hash
"ledger", // a ledger event the daemon applied on resume
"skills", // the skills index hash
"rotate", // the chain continued into a new file
"anchor", // the head was published (where)
}
// Line is what the file holds: the record, the previous line's hash, this
// line's hash, and the head signature on a rotation or close line.
type Line struct {
Record Record `json:"record"`
Prev string `json:"prev"`
Hash string `json:"hash"`
Sig string `json:"sig,omitempty"`
}
The kinds are a closed set, and Verify refuses any other. Each is written from a particular place:
| Kind | Written by | Subject, hash and attributes |
|---|---|---|
open, close |
Open, Close |
deterministic, and the daemon’s version |
config |
Open |
one per file the daemon was configured from (config, routes, gateways, weights): the sha256 of its bytes |
skills |
Open |
the skills index hash; lock: matched, drifted or missing |
mount |
each MCP mount | the server, a hash of its sorted tool names, trust, transport, lock state; a command server’s resolved program and pass_env names |
turn_begin, turn_end |
a turn | peer and channel; how the turn stopped, the model turns and calls it took, and (from chapter 49) the trace file’s name, sha256 and line count as it was closed |
section |
a turn | one per system-prompt section by its Source, the hash of its text |
model |
the span writer, and three paths outside the loop | provider, the request’s hash, status; path for compaction, the deriver and memory_chat |
approval |
the span writer | the call’s hash, the nonce, the answer and who gave it (by) |
tool |
a wrapper around each tool | an outward call: its name, its hash, the capabilities it used (chapter 47’s table) and how it ended; never read_file, scratch_read or a write inside the workspace |
policy |
the gate’s OnDecision hook |
a chapter 47 Decision: tier, escalated, overridable, risk, p_ask, threshold, the rule’s pattern and source, the capabilities, the taints as source:name, model_err, and refused_by_tool |
embed |
each embedder | the host and the number of texts, and the path (memory, policy, route); never a text |
send |
each channel send | the channel, the conversation and the byte count |
ledger |
resume | the tool, the action the resume rule applied, the call id, the number of ledger lines at that time |
rotate, anchor |
the log and the daemon | the bytes of the finished file; where a head went |
A model record exists for every completion the daemon sends, not only the agent loop’s: the memory deriver, the compaction summariser and memory_chat’s auxiliary client send text to a provider the loop never sees, so each writes a model record with its path before the call, and embed records are written before the text goes. The policy record agrees with the trace’s policy_decision span on every call, the private-turn override included (a call the turn’s own tool refuses is allow with refused_by_tool, as the span’s reason says), and its rule_source is the message id chapter 35’s Rule.Source carries, so the chain from a refused call goes back to the message the reader wrote. A tool record is made by a wrapper that sees the call and its result, because a span carries a call’s name and hash and not its arguments, and the capability table needs the arguments.
Private on a record says the text behind it belonged to a private turn. An embed record carries it when the embedder was called for such a turn: the inbound message’s and the reply’s memory records, and the gate’s model tier (path policy), which sends a private turn’s call text to its embedder only when the operator set embedder_local and skips the model tier otherwise (chapter 47), so a private embed record with that path is the audit’s evidence that the text went where the operator said it could. The router’s gate is not consulted on a private request (chapter 45), so no route record is marked private. TestPrivateTurnEmbedRecordsAreMarked pins the marks, with a mutant for each of the two paths that once lacked one.
The span writer is how model and approval records are made without changing the trace.
// SpanWriter wraps a trace file's writer: every ended span the tracer
// writes passes through it, and the spans the audit reads (model_call,
// tool_call of an outward tool, approval, policy_decision) become records
// through Sink. The trace file is unchanged byte for byte; the audit log is
// a derived view of it plus what the trace cannot see (the embedder, the
// gateway, the ledger).
func SpanWriter(w io.Writer, sink func(obs.Span) []Record, emit func(Record) error) io.Writer {
return &spanWriter{w: w, sink: sink, emit: emit}
}
It writes the bytes through first (the trace is the record of record, and an audit failure must not lose it), then parses each complete line and emits what the sink makes of it. A torn or non-span line passes through and makes no record, and an emit error is returned with the full count so that the tracer’s Err carries it. Under a secrets block the span writer sits outside the redacting writer, so it sees the raw span, and scrub replaces any record subject or attribute that contains a brokered value with its sha256: a call id the model chose could be a value it was shown, and ordinary ids are kept.
The exceptions to “nothing in a record is text” are named, and they are the reader’s configuration and not a model’s words: a mount record’s program path and pass_env names, and a policy record’s rule pattern and model_err, cut at audit.MaxField (200 bytes) on a rune boundary. CheckNoText is the rule the tests apply to every record against a payload, the model’s replies and the sentinels: no field past MaxField and none holding one of those texts.
The chain. Write a log as records , and let be the canonical JSON of (chapter 21’s encoding, canon.JSON, which request_hash already uses; includes its own seq and clock reading). Let be the 64 lowercase hexadecimal characters of the hash of line , as ASCII. Then
and a line is {"record": r_i, "prev": p_i, "hash": h_i}, hash and prev written as hex. The genesis is the hash of the log’s id, so the same lines under another id do not verify (TestGenesisBoundToID).
// HashLine is the chain rule: hex(sha256(prev || canon.JSON(record))),
// where prev is the previous line's Hash and, for the first line of a log,
// the Genesis of the log's id. The derivation in the chapter shows what a
// change to any line does to every later hash and what it cannot show.
func HashLine(prev string, r Record) (string, error) {
b, err := canon.JSON(r)
if err != nil {
return "", err
}
h := sha256.New()
h.Write([]byte(prev))
h.Write(b)
return hex.EncodeToString(h.Sum(nil)), nil
}
// Genesis is the first prev: hex(sha256("aec audit v1\n" + id)).
func Genesis(id string) string {
sum := sha256.Sum256([]byte("aec audit v1\n" + id))
return hex.EncodeToString(sum[:])
}
Rotation names a finished file after the last seq it holds, so Verify walks the files as one chain and refuses a gap in the names or a file whose name does not match what it ends with. A crash between the rotate line and the rename leaves audit.jsonl ending with it; Open finishes the rename (TestRotateCrashCompleted). A crash between a write and its newline leaves a torn last line, and Open cuts it, as the ledger cuts its own, and the daemon warns.
A log that does not verify at start. Open walks the whole chain by the rule Verify applies with no key and no anchor. A chain error anywhere in it (a changed byte, a line removed or swapped, a kind outside the set, a file whose name does not match what it ends with) does not stop the daemon. The second adversary needs one byte to do that, and so does a bad sector, and a daemon that will not start does none of the reader’s work while it guards a log nobody has read. Instead Open moves every log file into Dir/audit/audit.broken-<n>/ (the smallest n not taken) with a copy of id and key.pub, so that aecd audit verify, given a configuration whose audit.dir names that directory, still prints the verdict it would have printed before the move (aecd audit verify -config aecd-broken.json, where that file’s audit.dir is the audit.broken-1 directory; TestOpenMovesABrokenLogAside compares the two strings). It warns once, and starts a new chain from the genesis under the same id and the same key. The new log’s first record is the open record, and it carries broken_dir, broken_seq, broken_head (the last line that still verified under the rule) and broken_verdict; aecd status prints audit: broken: the previous log was moved to … for as long as that daemon runs. TestBrokenAuditLogDoesNotStopTheDaemon changes one byte between two starts and has a mutant that restores the refusal.
The cost is that an adversary of the reader’s uid can force a fresh chain with one byte, and the live log then has nothing before its first line, so the daemon’s evidence is split between two directories until the reader looks. What it keeps is the old directory untouched, the break named in the first record of the new chain and in the warning, and the new chain’s head published by the next anchor. A head the reader copied before the change does not rescue the old lines: Verify reports the chain error before it compares an anchor, so the moved directory says where it broke and not whether the lines before the break are the honest ones. Three refusals remain, because moving aside would hide a mistake and not a break: a directory whose id file names another daemon (the genesis would be wrong from the first line), a second writer (the lock), and a log file or directory whose mode is not 0600 or 0700, as for every state file (chapter 40’s ErrMode); the error names the file and its mode. A log cut at a line boundary is not a break at all: it is a shorter valid chain, and only an anchor finds it.
The writer holds an flock on Dir/audit/lock for its life. A file made with O_EXCL would stay behind when the daemon is killed by SIGKILL and the daemon could never reopen its own log; the kernel drops an flock with the process. TestSecondWriterRefused shows both halves, and TestKillBesideLedger below shows it through the chapter 40 rig. Append refuses a caller’s rotate and close records, which are the log’s own, and a kind outside the set.
Verify reads each line with unknown keys refused, because it recomputes the hash from the parsed record and an unknown key would otherwise ride on a line that verifies. A sig on a line that is not rotate or close is refused for the same reason.
// Verify reads every file of a log in order, recomputes every hash, checks
// the signatures when a public key is given, and returns the head. With
// expected set, a head that differs is ErrTruncate or ErrChain: what the
// anchor is for. Alone, a clean verdict says only that the lines are
// consistent under the rule, which any writer can produce for any records.
// Relative to a head the verifier holds from outside (expected), it says
// that lines 1 through its seq are exactly the records hashed into that head,
// in that order: a different set would need a second preimage of SHA-256
// (about 2^256 work for a chosen target) at the first line that differs, and
// the 64-digit prev makes each hashed input unambiguous. Lines after the
// anchored seq are unanchored. With pub, every rotate and close line was
// signed by that key over (hash, seq), so without the key a line at or before
// a signed line cannot change without removing the signed line and
// everything after it. It never proves who wrote a record (a writer with the
// key signs what it likes), nor that a record was not left out before it was
// hashed, nor the wall time. The guarantee is about the record's fields: a
// line with a key the writer never wrote is refused.
//
// expected is "HASH" or "SEQ:HASH" as aecd status and the anchor notice
// print it. With a seq, a line of that seq whose hash differs is ErrChain
// (rewritten) and a log that ends before it is ErrTruncate; without one,
// a hash that appears nowhere in the chain is ErrTruncate (the chapter says
// why the seq tells the two apart).
func Verify(dir string, expected string, pub []byte) (head string, n uint64, err error) {
if pub != nil && len(pub) != ed25519.PublicKeySize {
return "", 0, fmt.Errorf("%w: a public key is %d bytes, not %d", ErrSig, len(pub), ed25519.PublicKeySize)
}
if expected != "" {
if err := checkAnchorForm(expected); err != nil {
return "", 0, err
}
}
raw, err := os.ReadFile(filepath.Join(dir, idFile))
if err != nil {
return "", 0, fmt.Errorf("%w: no id file", ErrChain)
}
st, err := walk(dir, strings.TrimSpace(string(raw)), pub)
if err != nil {
return st.head, st.seq, err
}
if expected != "" {
if err := st.checkAnchor(expected); err != nil {
return st.head, st.seq, err
}
}
return st.head, st.seq, nil
}
What a verdict proves. Three statements, in increasing strength, and what none of them covers.
A clean Verify alone says the lines are consistent under the rule. Any writer can produce that for any records, since the rule needs no secret: the chain is a checksum with a structure.
Relative to a head the verifier holds from outside, it says that lines 1 through its sequence number are exactly the records that were hashed into that head, in that order. Let the honest log be fixed, with hashes and bodies , and let the verifier hold with . Suppose a log with bodies is accepted with its line hashing to , and that for some . Let be the largest such . If , then is the given. If , then by the choice of the line after it has , and is the hex of . The accepted log passed the prev check, so is the hex of , and gives . In both cases
Both and are 64 bytes, so the concatenations are equal only if both halves are, which they are not. The two inputs differ and have the same digest: a second preimage of the honest log’s input at . Finding one for a chosen target costs about evaluations by any generic method, which is an assumption about SHA-256 and not a proof. The 64-digit prefix is what makes the concatenation unambiguous, and the argument runs over the genesis as well (a different id changes , which is ). Lines after are unanchored. The seq is inside each record, so a swap of two lines changes the bytes at both positions and falls under the same argument; this is why the verifier compares the line at a given seq and not only the hash, below.
With a public key, every rotate and close line was signed by that key over its hash and its sequence number. Signing is on by default ("audit": {"no_sign": true} turns it off): the daemon makes an Ed25519 key at its first start, Dir/audit/key with key.pub beside it, both mode 0600. The signature is Ed25519 over hash + LF + the decimal seq, on those two kinds of line only. A writer without the private key who changes a record at or before a signed line changes that line’s hash by the statement above, and the old signature, over the old hash, no longer verifies; he must remove the signed line and everything after it. TestSignatureCoversHashAndSeq pins what it covers: a prefix rewritten and re-chained under the old close signature is refused under the key and accepted without it.
What none of them proves. That a record was not left out before it was hashed (the writer chooses what to append). The wall time (at is the daemon’s clock and is hashed, not witnessed; under -deterministic it is a constant). Who held the key (the daemon’s uid holds it: Dir/audit/key is mode 0600, which keeps other users out and nothing else). And that the log was not cut: every prefix of a valid chain is a valid chain, and a prefix of a signed log verifies under the key. Truncation is found by the anchor and by nothing else. And that every record the daemon meant to write reached the log: an append that fails (a full disk, a directory whose permissions changed) is warned of once and the daemon carries on, so a log can end earlier than the work did, and the records it lacks are not a break in the chain. The audit log fails open on purpose: a daemon that stopped for want of disk space would stop the reader’s work for the sake of the evidence of it, and the trace and the session file still hold what happened.
The anchor. A hash chain is a way to make a published number commit to a sequence. It is no use until the number is held somewhere the writer cannot revise; the linked time-stamps this chain descends from (Haber and Stornetta, 1991) have the same dependence, since a link is only as good as the place the latest stamp is kept. The daemon publishes the head three ways, and the reader should know which of the three he has.
aecd statusprintsaudit: head=<hash> seq=<n> key=<fingerprint>, with the fingerprint read from the running daemon’s own key and not fromkey.pubon disk (TestAuditCommandsreplaceskey.pubwhile the daemon runs).- At every rotation and at close the daemon writes
audit: <event>: head <seq>:<hash> key <fingerprint>to stderr. - With
"audit": {"anchor": "notice"}it also posts the same text to the principal’s channel as a daemon-own notice (Own, which chapter 42’s notifier never scores).
Verify accepts the anchored head as SEQ:HASH or HASH, and checks the form first (64 hex digits, optional SEQ:; a malformed argument is a usage error, exit 2, about the argument and not a verdict on the log). With a sequence number the verdict tells two failures apart: the log ends before SEQ (ErrTruncate) or the line at SEQ has another hash (ErrChain, rewritten). With the hash alone, a head that appears nowhere in the chain is one of the two and the verifier cannot say which; it says truncation, and the walkthrough shows it saying that of a rewrite. So the notice carries the sequence number.
The fingerprint travels with the head for a reason: a key.pub beside the log is the writer’s to replace. A log re-signed with another key verifies against a key.pub replaced to match, and audit verify prints the fingerprint of the key it used, to be compared with the one in the anchor.
The log calls the anchor hook after releasing its lock; the hook writes the stderr line and queues the head, and one worker sends the notice and writes the anchor record. The worker exists because an Append can be inside a memory-service call that holds the service’s lock, and the notifier takes the same lock through the user model, so a notice sent from Append’s caller would never return (TestAnchorNoticeUnderMemory runs that situation). An anchor record does not itself rotate the log, since a record that rotated would anchor again without end. A rotation that happens while Open is still running is published as soon as Open returns, because the notifier does not exist before.
Two weaknesses remain, and neither is repaired. The anchor record’s subject says where the head went: notice only when the channel took the post, queued when the notifier queued it (quiet hours, a failed send, no decision model), failed when it could be neither sent nor queued, stderr otherwise. A queued notice waits in a file the daemon’s uid can revise, and the daemon warns of it once. So during quiet hours the anchor is stderr alone, which is only as safe as where the reader sent it (a file of the reader’s uid is within the same reach); that is the cost of not making the notice Critical, which would interrupt the reader at every rotation. Second, a post is made with the daemon’s own bot token. Whether the chat server lets that token edit or delete its own post is the server’s configuration, which this chapter did not test; the property claimed does not depend on it. The head the reader read or copied, wherever he put it, is outside every file the daemon can reach, and an anchor nobody reads is a number nobody holds.
The alternatives are not built, for stated reasons. An append-only file attribute needs root to set and to keep. A second uid that takes the appends needs an account and a socket. A transparency log, the shape of RFC 9162’s Merkle tree with its consistency proofs, adds third-party monitors and the proof that a log only grew, and it is a service.
The ledger as an input. ledger.jsonl is chapter 40’s durability record: a begin before a non-idempotent call, an end after it, fsynced, so that a daemon killed in the middle knows what was in flight. It is unhashed on purpose; durability wants small appends and the audit log wants a chain. What the audit log records of it is what the resume rule decided (ledger records: the tool, the action abort, confirm or replay, the call id), and the call id ties the record to the begin line it resolved. TestKillBesideLedger is chapter 40’s crash with a log beside it:
ledger.jsonl: begin call_id=c1 ... resolved
audit.jsonl: ledger subject=barrier decision=abort call_id=c1 ledger_lines=3
The daemon is killed by SIGKILL with a tool in flight, aecd audit verify on the dead directory passes or reports the torn line and nothing else, and a second daemon opens the same directory, which it could not if the lock were a file. Captured on wntrmute.
What -deterministic does to the log. A captured or tested daemon’s id is a constant rather than a hash of its directory, so that two runs in two directories are the same bytes, except that from chapter 49 a turn_end record hashes its turn’s trace, so a turn whose spans name a path under the state directory (an approved outward write’s reason does) records a different hash in each directory; two deterministic logs therefore share a genesis. It is a capture flag, and nothing else should use it.
Vetting before trusted
Chapter 44 said that “chapter 48 is where a server earns the word”, and chapter 36 loaded a skills directory whole. What the reader looked at has to be recorded in a form that can be compared with what loads.
// SkillsManifest is what vetting a skills directory pins: every file of
// every skill by sha256 and size, the index hash chapter 40 writes into
// Trial.Extra, and the whole manifest's hash. A later load that differs is
// reported file by file.
type SkillsManifest struct {
Index string `json:"index"` // sha256 of skill.Index
Files map[string]FileEntry `json:"files"` // "<skill>/<path>" -> entry
Hash string `json:"hash"`
}
type FileEntry struct {
SHA256 string `json:"sha256"`
Size int64 `json:"size"`
Executable bool `json:"executable"`
}
func Skills(skills []skill.Skill) (SkillsManifest, error) {
m := SkillsManifest{Files: map[string]FileEntry{}}
for _, s := range skills {
root, err := os.OpenRoot(s.Dir)
if err != nil {
return SkillsManifest{}, fmt.Errorf("audit: skill %s: %w", s.Name, err)
}
rels := []string{"SKILL.md"}
for _, f := range s.Files {
rels = append(rels, f.Path)
}
for _, rel := range rels {
e, err := hashFile(root, rel)
if err != nil {
root.Close()
return SkillsManifest{}, fmt.Errorf("audit: skill %s: %s: %w", s.Name, rel, err)
}
m.Files[s.Name+"/"+rel] = e
}
root.Close()
}
m.Index = sha256Hex([]byte(skill.Index(skills)))
h, err := manifestHash(m)
if err != nil {
return SkillsManifest{}, err
}
m.Hash = h
return m, nil
}
A skills manifest is every file of every skill by sha256, size and executable bit (chapter 36’s rule: any execute bit, or a path under a directory named scripts at any depth, case-folded), the index hash chapter 40 already writes into Trial.Extra, and the manifest’s own hash. Files are read through os.Root, never through a symlink, and a file that changes between the check and the open is refused. At Open, with a skills.lock present, a differing file is warned of by name and the skills record carries the verdict; no lock is not an error. Nothing is refused: skills are text the model reads, and the reader decides what he does with a warning.
An MCP manifest is the server’s info and supported versions, and for each tool the sha256 of its description, of its input schema and of its annotations. The schema and annotations are hashed as canonical JSON, so a server that reorders its keys has not changed its tool. A command server’s manifest also carries its reach: the resolved program path, the program’s sha256, and the pass_env names, beside chapter 44’s warning that it runs unsandboxed with the daemon’s uid. The program is hashed before it is started; a swap between the exec and a later hash would go unseen.
// MCPManifest pins what a server offered at vetting: each tool's name, the
// sha256 of its description, of its input schema and of its annotations,
// the server's info and supported versions. Trust "trusted" in aecd.json is
// honoured at Open only when the server's current list matches its manifest
// (a rug pull drops the server to untrusted and warns); a command
// server's manifest also carries the program's path and sha256 and the
// names pass_env grants it (its reach).
type MCPManifest struct {
Server string `json:"server"`
Info mcp.Info `json:"info"`
Versions []string `json:"versions"`
Tools map[string]ToolEntry `json:"tools"`
Program *ProgramEntry `json:"program,omitempty"`
Hash string `json:"hash"`
}
type ToolEntry struct {
Description string `json:"description"` // sha256
Schema string `json:"schema"` // sha256
Annotations string `json:"annotations"` // sha256
}
type ProgramEntry struct {
Path string `json:"path"`
SHA256 string `json:"sha256"`
PassEnv []string `json:"pass_env,omitempty"`
}
func MCP(ctx context.Context, c *mcp.Client, name string, program *ProgramEntry) (MCPManifest, error) {
disc, err := c.Discover(ctx)
if err != nil {
return MCPManifest{}, err
}
tools, err := c.ListTools(ctx)
if err != nil {
return MCPManifest{}, err
}
return MCPFrom(disc.ServerInfo, disc.SupportedVersions, tools, name, program)
}
// MCPFrom is MCP over a tool list the caller already holds. The daemon builds
// the manifest from the tools it mounted, so the list compared with mcp.lock
// is the list the model is given, and a server that answers tools/list
// differently the second time cannot show the lock one list and the model
// another.
func MCPFrom(info mcp.Info, versions []string, tools []mcp.Tool, name string, program *ProgramEntry) (MCPManifest, error) {
m := MCPManifest{Server: name, Info: info, Versions: append([]string(nil), versions...), Tools: map[string]ToolEntry{}, Program: program}
sort.Strings(m.Versions)
for _, t := range tools {
e, err := toolEntry(t)
if err != nil {
return MCPManifest{}, fmt.Errorf("audit: tool %s: %w", t.Name, err)
}
m.Tools[t.Name] = e
}
h, err := manifestHash(m)
if err != nil {
return MCPManifest{}, err
}
m.Hash = h
return m, nil
}
The rug-pull rule. A server configured trusted is trusted only against Dir/mcp.lock, the file aecd vet mcp -write stores. If the lock is missing, the server has no entry, or the manifest of the tools the daemon actually mounted differs from the entry, the server is mounted untrusted (every call marked) with one warning that names each change. The consequence is that readOnlyHint and the unmarked calls a trusted server enjoys (chapter 44) are earned by a description the reader vetted and lost when it changes. The file’s name and shape (one deterministic lockfile, a record per server with its transport, its tools and a content hash, sorted so a diff is readable) are tirith’s .tirith/mcp.lock, which tirith mcp lock writes (its README at commit 22a60f2, line 484), cited for the shape alone; none of its code is here, and this lock differs in what it hashes, which is the tool descriptions the model is given.
The manifest is built from the tools mcp.Mount returned and not from a second tools/list. So the list compared is the list the model is given, and a server cannot show the lock one list and the model another (TestRugPullAlternatingList). The rule’s cost is a command run once per server and again when a change is accepted.
aecd vet mcp -config FILE mounts every configured server as the daemon would and prints each manifest. It prints the cleaned, cut description of each tool beside the hash, because a reader cannot approve a hash. Three facts about it belong in the usage text and are there. It starts every command server it is given, as a child of the vetting process, in a directory of its own under the state directory. It takes the state directory’s lock, so a running daemon makes it exit 3 and a serve started meanwhile exits 3 too. And it hardens itself as serve does, because the program under vetting is by definition not yet vetted: an unhardened vetting process hands its environment to a command server that reads its parent’s (TestVetHardens). It exits 1 when a server did not mount unless -write is given, in which case the lock keeps the other entries and the exit is 0.
Two behaviours change for a configuration written before this chapter, with no block present. A trusted server with no lock mounts untrusted with a warning, so an attended turn gains prompts, and a scheduled job, which cannot be asked, does not run those calls until the server is vetted (chapters 42 and 47 say what an unattended job does with a marked call). And the 5-minute idle default on mcp.sock, below, applies without a block. The first is the price of the rule and is named in its warning; the second is a default of the daemon and is named nowhere but here and in the configuration’s idle key.
The hardening list chapter 44 carried. Three items, each with the limit it keeps.
- The parent-death signal. A command server gets
SIGTERMif the daemon dies bySIGKILL, set withPdeathsig.PR_SET_PDEATHSIG(2const)ties the signal to “the parent thread”, the thread that forked the child, and not to the process, and says the setting is cleared for the child of afork. A Go program forks from whichever thread the scheduler gave it, and a thread can exit while the process lives, so a barePdeathsigkills a healthy server when its forking thread exits, which is why Part VII declined it.Startforks from a goroutine that keeps its thread locked until the child has exited, so the signal fires only when every thread of the daemon is gone (TestServerSurvivesCallerThreadExitfails under the bare form). The signal reaches the child only. A descendant of the server is outside it, and one that callssetsidis outside the group kill thatCloseperforms as well, which a daemon that died bySIGKILLnever runs. Those stay stated limits. - The idle deadline.
ServeListenerIdlecloses a connection toDir/mcp.sockthat has been silent for the configured time (mcp_serve.idle, default 5 minutes,"0"for none). A read deadline armed before every read cuts a request while it is being answered, since the reply of a request in flight races the close. So the rule is: the deadline is armed when no request is in flight and cleared while one is, set and read under one lock, and the reader goroutine never decides on a timeout. It reports and waits, and the loop, which knows what it has registered, closes the connection or clears the deadline. A request that outlives the idle time is not cut. - The hard-link refusal.
aecd mcp’swrite_filerefuses a regular file with more than one name (noHardLink), so the outside name is not changed. The read half stays open, as chapter 44 states.
OAuth 2.1 and Client ID Metadata Documents are discussed here and not built. The MCP authorization page at revision 2026-07-28 says authorization is “OPTIONAL for MCP implementations”, and that implementations using a stdio transport “SHOULD NOT follow this specification, and instead retrieve credentials from the environment”. The broker is that. For an HTTP transport the page says implementations SHOULD conform to it: an MCP server MUST implement OAuth 2.0 Protected Resource Metadata (RFC 9728), a client MUST use it to find the authorization server, a client MUST send resource indicators (RFC 8707), authorization servers and clients SHOULD support Client ID Metadata Documents, and dynamic client registration is deprecated and kept for servers that lack them. OAuth 2.1 adds the restrictions of current practice to OAuth 2.0 and requires PKCE (the draft says so in its overview). The page cites the OAuth 2.1 draft mostly at -13 and the metadata-document draft at -00, while the datatracker showed, when this chapter was written (October 2026), draft-ietf-oauth-v2-1 at -16 (3 September 2026) and draft-ietf-oauth-client-id-metadata-document at -02 (6 July 2026), and by November they had moved to -17 and -03; a standard still moving is one more reason not to build to it yet. The book’s HTTP mount is a static bearer from token_env, compared in constant time on loopback or TLS: the credential model of the page’s stdio paragraph carried over a socket. Building the client side would need a metadata fetch, authorization-server discovery, a PKCE flow with a loopback redirect, a client metadata document at an HTTPS URL the daemon owns, token refresh and a fake authorization server to test against. The cost of leaving it is that an HTTP server that demands OAuth cannot be mounted in Part VIII. Chapter 51 takes it up if the capstone mounts one.
The binary. aecd has a test build with hooks (a barrier tool, a -tools flag, two config keys) and a production build without them. TestProductionBinaryHasNoHooks builds the production binary and shows it has no -tools flag, refuses the two keys as unknown fields, and does not contain the hooks’ names in its bytes. That is a supply-chain property of the one artefact the reader runs, and no proof about its compiler: after Thompson’s “Reflections on trusting trust” (1984), a test of a binary’s bytes cannot rule out a toolchain that adds what the test looks for.
The private run
Chapter 21 states the run’s rules: it is optional and the reader’s, nothing of it is committed, the history goes only to local teachers through LocalFleet (which refuses every host but the two MagicDNS names, straylight.scylla-hammerhead.ts.net and dixie.scylla-hammerhead.ts.net, compared whole, and sends nothing through a proxy or a redirect), the results live in a runtime directory outside the repository (mode 0700, files 0600), text is redacted before anything is embedded or written, and the database is opened read-only. This section adds what that statement leaves out.
Why the host name is compared whole. Short names are refused: with Tailscale down the tailnet’s domain leaves the resolver’s search list, and straylight alone can fall through to another network’s. localhost is refused too; on the machine that runs the script it could be a tunnel or a proxy to anything. The same proxy fix is in Go: decide.NewHTTPEmbedder builds a proxy-free transport for a caller whose client has none (TestHTTPEmbedderIgnoresProxy, with a stand-in proxy that sees no connection), and keeps a transport the caller gave.
What the results are. An embedding is not a hash: Morris and colleagues (2023) train a model that, in their words, “is able to recover 92% of 32-token text inputs exactly” from the embedding alone. Labels carry the texts they label, and weights trained on a few hundred of the reader’s items are a function of those items, so all three are stored as carefully as the text.
What redaction runs on. Decoded text: a tool call is redacted where it sits, every string of its parsed arguments in place, and never as raw JSON text, where an escape such as \u002d (a hyphen) hides what a pattern looks for. The price is that aecd receives calls unredacted unless a gate redacts them the same way, so the -grams inside a redacted span differ between training and serving.
The labels are censored. The target of approve is when the reader wants to be asked before the call runs. Hermes’s /approve outcomes cover only the calls Hermes flagged and asked about:
| outcome | strength | |
|---|---|---|
| approve always | 0 | strong, for its pattern |
| approve session | 0 | weak |
| denial, or no answer before the timeout | 1 | strong, if the logs record them |
| the call was not flagged | none |
An unflagged call is unlabelled, not negative: counting it as one would train the student to reproduce Hermes’s rule, the thing chapter 47 compares it with. The flagged calls are not a random sample either. The real labels estimate the false-positive burden, how often a flagged call is one the reader waves through for good, and say nothing about the calls the rule missed, so every claim from them carries “on flagged calls only”. Whether the logs record denials and timeouts at all was the open question chapter 21 deferred, and Hermes’s public source answers part of it. At commit cca83848ec79a4a6a2ecc10285725559bf72c97c, gateway.log takes the loggers whose names start gateway, hermes_plugins or plugins.platforms (hermes_logging.py, COMPONENT_PREFIXES at lines 282 to 290, the file’s rotation at line 374), and the approval module’s logger is tools.approval, in the tools component. The outcome strings (denied, timeout, notify_failed, cancelled, blocked) are a set in tools/approval.py at line 505, and _denied at lines 518 to 525 returns them in the dict the agent receives as the tool result. A gateway wait that times out returns "timeout" with no log line (tools/approval_gateway_wait.py, _poll_event). So gateway.log does not record approval denials or timeouts at that commit; the outcomes are in the tool-result dict, which is a session message and not a log line. Whether the database stores that dict verbatim is not something this book established, and the positives, if there are any, come from the transcript and not from a log.
The run itself is the reader’s script on each host that has a gateway: redact, map Hermes’s outcome strings onto the table and read label_summary before going on, embed and label through LocalFleet, train with student.train_heads, fit temperatures on about 200 gold labels per decision, and end with check_private(), which must return nothing. The shift is measured both ways: the committed jev-lite.safetensors on his gold set, and his artefact on the synthetic gold_eval split.
Each rule is a function with a test, and each test was shown to catch the mistake it names: 54 plausible bugs, applied one at a time to private.py, fleet.py and train_student.py, each made a test fail (talos, 2026-09-30). What no test can check is the run, which is the reader’s script against his own database.
Walkthrough
One session, read record by record
The capture is three turns through the daemon on wntrmute, on 2026-10-18, against wntrmute’s own llama.cpp router (127.0.0.1:8080, model ornith-1.5-35b-a3b). GET /v1/models read the 35b loaded and the 9b sleeping before the run and the same after; no load request was made. The script printed requests: 3 turns, at most 6 completions before the first request, and the log holds six model records: three in the first turn (a write_file, a read_file that checked it, the final answer), two in the second (the terminal call and the answer) and one in the third. The configuration is "audit": {"anchor": "stderr"} and an empty secrets block, so the broker holds nothing, the trace redaction is on, the embedder is empty (no text goes to dixie), there is no policy block, so no gate and no policy record, and the daemon runs -deterministic, which fixes the clock at 2026-10-01T00:00:00Z. The three requests were:
Write the file notes/audit.txt in the workspace containing the single line "audit test" and tell me when it is done.Using the terminal, run uname -s and tell me what it printed.Say the single word done.
Their answers were that the file was written, Linux, and done. aecd status before the shutdown, and aecd audit tail (the first twenty lines; the format is seq, kind, actor, subject, decision, and the first twelve characters of the hash):
audit: head=fc3c4493f1d4d4e7f6f3a546d2233da0295b3b249e62a933c79ba0a6cf2059ab seq=20 key=04350c3210dd0223
1 open daemon - - b928141a0824
2 config daemon config - c5bf5e1b0da7
3 config daemon routes - 93361ca588ac
4 turn_begin principal - - 8386fe8e3862
5 section principal identity - 620cdc1ccc59
6 model principal wntrmute-35b - 6e45893d4e99
7 model principal wntrmute-35b - 7f5b9ff244bb
8 model principal wntrmute-35b - c26eaf4303e7
9 turn_end principal - final cfb0e4023085
10 turn_begin principal - - be45171723bf
11 section principal identity - 61376aa8ab1d
12 model principal wntrmute-35b - 1608f162bbd6
13 approval principal terminal allow d69b8c33f20d
14 tool principal terminal - cf60ce463578
15 model principal wntrmute-35b - 091abc00d14d
16 turn_end principal - final b1795c4193c6
17 turn_begin principal - - 08217a21ada1
18 section principal identity - d0c14505f0f0
19 model principal wntrmute-35b - e2c5c941f2b2
20 turn_end principal - final fc3c4493f1d4
Read it from the top. Lines 1 to 3 are the start: open, then one config record each for aecd.json and routes.json (the sha256 of their bytes; a changed configuration is a changed hash). Line 4 opens the first turn and line 5 is its one system-prompt section, identity, by Source, with the hash of its text. Lines 6 to 8 are the three completions of the first turn. There is no tool record for the write_file and the read_file between them, by design: a write inside the workspace and a read are not outward (chapter 47’s table: no network, no write outside the workspace, no exec), and the ledger saw both. Line 9 closes the turn. In the second turn, line 12 is the completion that proposed terminal, line 13 is the approval (by: control, because the client was started with -approve allow, the nonce d22, the call’s hash), line 14 is the outward call that ran, with capabilities: exec, and line 15 is the completion that answered. The third turn is four lines, and its Decision is again final. These are two of the lines as the file holds them (the model’s own call id is in both, and it is an id and not text):
{"record":{"seq":13,"at":"2026-10-01T00:00:00Z","kind":"approval","session":"ch48","turn":2,"actor":"principal","subject":"terminal","hash":"e15023c1f95665998ef86804089e22c8902fab70c37a6f5597d342e39f7f3b1b","decision":"allow","attrs":{"by":"control","call_id":"4MgUgiXYvmRynsNl2ozwwctlihTusXsQ","nonce":"d22","timeout_s":"60"}},"prev":"1608f162bbd622c9e94a22fcc524fa05d29c989961e9d62d3874fe950d217450","hash":"d69b8c33f20de0c8bbc28414d498e9d5ff9729659477a813c7e32a218a087fc1"}
{"record":{"seq":14,"at":"2026-10-01T00:00:00Z","kind":"tool","session":"ch48","turn":2,"actor":"principal","subject":"terminal","hash":"e15023c1f95665998ef86804089e22c8902fab70c37a6f5597d342e39f7f3b1b","attrs":{"call_id":"4MgUgiXYvmRynsNl2ozwwctlihTusXsQ","capabilities":"exec","result":"ok"}},"prev":"d69b8c33f20de0c8bbc28414d498e9d5ff9729659477a813c7e32a218a087fc1","hash":"cf60ce463578b2c9e1271c4d3a27f83d85fecfa546d0298da8605d6839e00f93"}
The call’s hash, e150…3b1b, is the same in both: that is how an approval, the call it approved and the trace’s span for it are joined. Neither line holds the command. The text is in the session file: grep -c 'audit test' on audit.jsonl prints 0 and on the session’s session.jsonl prints 4.
After aecd shutdown the daemon wrote its close line and published it. The daemon’s stderr ended with
audit: close: head 21:a047383f9b46999583359ec70121b39ea7cfb1718cbf46611511c8db93bf67d5 key 04350c3210dd0223
and the process was gone and the socket removed. Then:
$ aecd audit verify -config aecd.json
ok: head 21:a047383f9b46999583359ec70121b39ea7cfb1718cbf46611511c8db93bf67d5 (21 lines) key 04350c3210dd0223
$ aecd audit verify -config aecd.json -head 20:fc3c4493f1d4d4e7f6f3a546d2233da0295b3b249e62a933c79ba0a6cf2059ab
ok: head 21:a047383f9b46999583359ec70121b39ea7cfb1718cbf46611511c8db93bf67d5 (21 lines) key 04350c3210dd0223
The second is the head status showed, before the close line: it is in the chain at seq 20, and the log goes on to 21. The key is the one status printed, so the fingerprint compares. An independent script outside the tree, written from the rule above and the canonical JSON of each record, recomputed all 21 hashes from the genesis 0890de8e…796a and found no mismatch.
The same log, damaged
Each of these is a copy of the captured directory, damaged, and verified by the real binary (wntrmute).
A field of line 4 changed ("turn":1 to "turn":7), nothing re-chained.
aecd audit verify: audit: the chain is broken: seq 4's hash does not recompute
Exit 1. Found with no key and no anchor, at the first bad line.
Line 4 rewritten ("peer":"kyle" to "peer":"evil") and lines 4 to 21 re-chained, the close line keeping its signature. This is what a writer who holds the file and not the key can do. With no public key available:
ok: head 21:9e83395744ab7d09a03d34265033f8b58872a5a8d6ce1c19af205c6f42e852ec (21 lines) key none
A rewrite verifies, as the first statement said it must. Then each defence in turn:
$ aecd audit verify -config aecd-copy.json # key.pub beside the log
aecd audit verify: audit: a head signature is missing or wrong: seq 21
$ aecd audit verify -config aecd-copy.json -pub state/audit/key.pub
aecd audit verify: audit: a head signature is missing or wrong: seq 21
$ aecd audit verify -config aecd-copy.json -head 20:fc3c4493f1d4d4e7f6f3a546d2233da0295b3b249e62a933c79ba0a6cf2059ab
aecd audit verify: audit: the chain is broken: the line at seq 20 is not the anchored one
$ aecd audit verify -config aecd-copy.json -head fc3c4493f1d4d4e7f6f3a546d2233da0295b3b249e62a933c79ba0a6cf2059ab
aecd audit verify: audit: the log ends before its recorded head: the anchored head is not in the chain
The key finds it because the close signature is over the old hash, and the rewriter has no key to sign the new one. The anchor with its sequence number finds it and names it a rewrite. The anchor with the hash alone also finds it, and calls it truncation, which it is not. All four exit 1.
The last two lines cut (19 of 21 kept).
$ aecd audit verify -config aecd-copy.json # key.pub beside the log
ok: head 19:e2c5c941f2b291cc65d377449b8b73380c42bc7e05b15b4db3922d459748102c (19 lines) key 04350c3210dd0223
$ aecd audit verify -config aecd-copy.json -head 20:fc3c4493f1d4d4e7f6f3a546d2233da0295b3b249e62a933c79ba0a6cf2059ab
aecd audit verify: audit: the log ends before its recorded head: the anchor names seq 20 and the log ends at 19
$ aecd audit verify -config aecd-copy.json -head fc3c4493f1d4d4e7f6f3a546d2233da0295b3b249e62a933c79ba0a6cf2059ab
aecd audit verify: audit: the log ends before its recorded head: the anchored head is not in the chain
The cut log verifies under the key, since a prefix of a signed log has fewer signed lines and no wrong one. Only the anchor finds the cut, and only the sequence number says by how much. These are three of the lab’s five mutants run on the real binary (a byte changed, a cut tail, a rewritten and re-chained suffix); the other two, a line removed and two lines swapped, are TestMutants’ and, like the changed byte, are found with no anchor at the first bad line, where the cut and the rewrite need one.
Vetting a server, and what happens when it changes
The book’s own daemon is an MCP server (aecd mcp, chapter 44), so it is the server to vet. The configuration mounts it as a command server named book, configured trusted, with no model route used and nothing sent anywhere. All four steps are on wntrmute.
No lock. aecd serve warns and mounts the server untrusted:
daemon: mcp "book" is configured trusted but Dir/mcp.lock does not exist; mounted untrusted (aecd vet mcp -write records what you vetted)
aecd vet mcp prints the manifest. The path of the binary is elided here; every other line is as printed.
book:
{
"server": "book",
"info": {
"name": "aecd",
"version": "0"
},
"versions": [
"2026-07-28"
],
"tools": {
"read_file": {
"description": "c299c13a07c5a4d95fa0ea634e683cb767993ac3fbd458c49704102aac3bdf7a",
"schema": "c1f602f917175c2e66e12ae758f40e21471f77e6309e10ccdc59e6a2d1730e65",
"annotations": "74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b"
},
"search_files": {
"description": "be3fa10b91e28a84ca1e3cfd4ac3a331fb9277f75e482075b073c8bbebd93cf9",
"schema": "a085fae98af18539e4f6d2fb3283d16e7abf8044e2060a72739c5040e489f2a7",
"annotations": "74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b"
}
},
"program": {
"path": "…",
"sha256": "feca10485494cec76af8f9d602f764fec2b2ec89bfdf187e090819206d37cb5a"
},
"hash": "7be61951d3bb7de3c42fdc073dcd6f0b1e28c55dce5912a9d5a5c6695f73c0a6"
}
tool read_file: Read a file in the workspace.
tool search_files: Search files in the workspace for a regular expression.
The two tools’ annotations are the same hash because they are the same annotations (both read-only). The last two lines are what the model will read. Run again with -write, the manifest becomes Dir/mcp.lock (mode 0600), and aecd serve starts without the warning; the mount record reads "lock":"matched" and "trust":"trusted".
The program changes. One NUL byte appended to the binary (a copy replaced by rename), the server otherwise the same, the next aecd serve warns:
daemon: mcp "book" is configured trusted but its tools differ from mcp.lock: program sha256 changed; mounted untrusted (aecd vet mcp -write records what you vetted)
and the mount record is "lock":"drifted", "trust":"untrusted". The daemon does not accept the change for the reader. Accepting it is a command he runs after looking, and the manifest above is what he looks at.
Exercises
(a) Show that the first lines of a valid log are a valid log, and say exactly what the anchor adds. Then design an anchor with nothing but loopback resources and the reader’s chat, and say what it cannot survive.
Answer
Every check Verify makes on line reads only lines up to (the genesis, the previous hash, the recomputed hash, the signature if one belongs there), so deleting lines after leaves a log in which each check still passes. One check looks further: a rotated file must end with the rotate line its name gives, so a cut inside audit.N.jsonl passes only after the file is renamed audit.jsonl and the later files are deleted; the conclusion stands. A truncated log is therefore never detectably wrong by itself. The anchor adds a number from outside the file: with the verifier can say the log must reach and that line must hash to , which by the statement in the Mechanism fixes lines through .
With loopback resources only, every file and socket the daemon’s uid can write is the writer’s, so no loopback resource is out of its reach except one that refuses the daemon’s uid, and a process of another uid is an account. The reader’s chat is the exception: post SEQ:HASH to a channel the reader reads, and copy the last one he saw into a note he keeps. It cannot survive the reader deleting or never reading the post, a chat server whose bot token can edit the daemon’s own posts if the reader relies on the post and not on his copy, and a daemon that is killed between two rotations, since the anchor is the head at the last rotation or close, not at the last line.
(b) The head is signed on rotate and close lines only. What would signing every line add against (a) an attacker with the file and not the key, and (b) the daemon’s own uid?
Answer
Against (a) it adds the tail. Without a signature on a line, the lines after the last signed one can be rewritten and re-chained by anyone, and -pub will not notice (the second walkthrough case rewrites line 4 and is caught only because the close line, which is signed, sits after it; a rewrite of a log’s unsigned tail is not). With every line signed the keyless attacker could change no line and append none. It would still not find truncation, because a signed prefix is a valid signed log. Against (b) it adds nothing: the key is mode 0600 under the same uid. The price is a signature per append and a 128-hex-character field on every line.
(c) With ptrace_scope at 0, the reader runs gdb -p on a hardened aecd as himself, and then as root. Which step of the access-mode algorithm decides each, and what restores his debugger?
Answer
Attaching is a PTRACE_MODE_ATTACH check. At scope 0 Yama adds nothing, and as himself the reader passes steps 1 to 3 (same user and group IDs) and is refused at step 4: the target’s dumpable attribute is not 1 and he lacks CAP_SYS_PTRACE. As root the capability satisfies step 3, step 4 and the commoncap check of step 5, so the attach succeeds: hardening is a defence against the reader’s other processes and not against a caller with the capability. aecd serve -dumpable restores the debugger, and the core dump with it. The same arithmetic is why raising the scope to 3 would not have closed the environment read: that is a READ check, which Yama does not limit.
(d) A server you trust updates a tool’s description legitimately. Walk through what the rug-pull rule does at the next start, what the reader runs to accept it, and why the daemon does not accept it for him.
Answer
At the next aecd serve the manifest of the mounted tools differs from the entry in mcp.lock by tool NAME: description changed. The server mounts untrusted with one warning naming that line, every call to it is marked, and the mount record says "lock":"drifted". The reader runs aecd vet mcp -config FILE, reads the cleaned description printed beside its hash, and runs it again with -write if he accepts. A daemon that accepted the change itself would make the rule the thing it exists to prevent: the server that changes its description is the party that could ask for the change to be accepted, and what the daemon sees at start is exactly what the lock was made to disagree with. The command takes the state directory’s lock, so it is run with the daemon stopped.
(e) Find a string holding a real secret that the deep redactor leaves alone, and an ordinary string it replaces. Keep away from the cases the Mechanism worked through. What does each mistake cost, and who pays?
Answer
A miss: mysql -u root -pZ7qkP2vx9 app. The password is glued to its flag, no name announces it, and at nine characters it is far below the 24 the entropy stage looks at; the deep redactor returns it unchanged (wntrmute). Any short password passed as an option is the same case. The password sits in whatever the text is written to, and the redactor is the second guard, not the first. A false positive: the narHash above, which the deep redactor replaces and the shallow one keeps. The reader or the model sees a placeholder where a public hash was, which matters where the erased string is the evidence.
(f) The quoted-value rule stops at a line end, and that errs open. Construct an input where it loses a secret, and say which stage of the pipeline could still catch it.
Answer
export API_KEY="abc, a newline, def0123456789" x: the named-value scan finds API_KEY=, sees a double-quoted value that does not close before the newline, and leaves it. The value is 3 and 13 characters on two lines, so the entropy stage, which needs 24 characters in one run, does not see it either. A key shape would (sk-…, ghp_…), and the brokered-values stage would, if the key were a brokered value. A real key is not usually split across lines inside a quoted shell word, which is why the direction is accepted and stated and not fixed; a multi-line private key is the case the PEM shape handles separately.
Lab
make lab CH=48 IMPL=mine runs go/labs/ch48 against go/labs/ch48/mine/audit.go; IMPL=ref runs it against this chapter’s packages. You write four pieces and the lab supplies the rest: HashLine (the chain rule), OpenLog with Append, Head and Close (an append-only log in Dir/audit.jsonl that stamps, chains, writes and syncs each line and rotates at MaxBytes into audit.<seq>.jsonl), Verify (recompute every hash from the genesis of the log’s id, and tell a rewritten line, audit.ErrChain, from a cut tail, audit.ErrTruncate, when given the head an anchor published) and Redact (the secret-shaped text and the values a daemon holds, replaced by [REDACTED], values first). The tests that use your pieces are these.
TestChainFixture:HashLinereproduces the hash of every line of the committed log, in order, from the genesis the README names.TestMutants: the five edits of a log (a byte changed, a line removed, two lines swapped, the tail cut, the suffix rewritten and re-chained), each throughVerifywith and without the anchor. The first three are found with no anchor, at the first bad line; the last two only with one, and the cut tail isErrTruncatewhere the rewrite isErrChain.TestRotation: twelve records with a smallMaxBytesrotate into several files, andVerifywalks them as one chain, including against the head the log reported before it closed.TestRedaction: every secret row loses its secret and keeps the marker and the text around it, redacting twice changes nothing, every ordinary row comes back byte for byte, and a planted value that holds a token shape is replaced whole.
The reference alone is held to the checks that need the daemon: TestManifests (a changed SKILL.md and a changed tool description each named, without a byte of the text they cover), TestFixtureByteIdentical (the three-turn deterministic session equals the committed log byte for byte, and the README equals what the run says of it), TestNothingSecretIsWritten, TestNoTextInRecords (a payload of chapter 46’s corpus planted in a peer’s recorded message and in a workspace file, a scripted model that obeys it, and CheckNoText over every record), TestKillBesideLedger, and TestNoSecretsInTestdata over the lab’s data. They run on the reference whichever IMPL is set.
Against the starter, make lab CH=48 IMPL=mine fails four tests (TestChainFixture, TestMutants, TestRotation, TestRedaction), each with “chapter 48 lab: not implemented”, and the reference passes in under a second, both on wntrmute.
Further reading
- Stuart Haber and W. Scott Stornetta, How to time-stamp a digital document, Journal of Cryptology 3(2), 99-111 (1991): the linked time-stamp, the ancestor of a chain whose head is published.
- Bruce Schneier and John Kelsey, Secure audit logs to support computer forensics, ACM Transactions on Information and System Security 2(2), 159-176 (1999): a log on a machine that may be captured, with entries made before the compromise impossible to modify or destroy undetectably; what a key per epoch buys that this chapter’s one key does not.
- Ben Laurie, Eran Messeri and Rob Stradling, Certificate Transparency Version 2.0, RFC 9162 (December 2021): the transparency-log shape, a Merkle tree with consistency proofs, that the anchor does not build.
- Ken Thompson, Reflections on trusting trust, Communications of the ACM 27(8), 761-763 (1984): why a test of a binary’s bytes is not a proof about its compiler.
ptrace(2),PR_SET_DUMPABLE(2const),PR_SET_PDEATHSIG(2const),proc_pid_environ(5)andunix(7), the Linux man-pages project at commitc6cefe27dd02beaf518bb654493e5f09e62b3225(the kernel.org mirror): the ptrace access-mode algorithm and Yama, the dumpable attribute, the parent-death signal’s thread, the environment file’s check, andSO_PEERCRED.- Model Context Protocol, Authorization, revision 2026-07-28: authorization optional, stdio credentials from the environment, and the HTTP stack.
- Michael B. Jones, Phil Hunt and Aaron Parecki, OAuth 2.0 Protected Resource Metadata, RFC 9728 (April 2025).
- Dick Hardt, Aaron Parecki and Torsten Lodderstedt, The OAuth 2.1 Authorization Framework, Internet-Draft
draft-ietf-oauth-v2-1-16(3 September 2026), a work in progress. - Aaron Parecki and Emelia Smith, OAuth Client ID Metadata Document, Internet-Draft
draft-ietf-oauth-client-id-metadata-document-02(6 July 2026), a work in progress; the MCP page cites -00. - John X. Morris, Volodymyr Kuleshov, Vitaly Shmatikov and Alexander M. Rush, Text Embeddings Reveal (Almost) As Much As Text, EMNLP 2023 (arXiv 2310.06816): why an embedding of the reader’s text is stored as carefully as the text.
- Nous Research, hermes-agent at commit
cca83848ec79a4a6a2ecc10285725559bf72c97c:hermes_logging.py,tools/approval.pyandtools/approval_gateway_wait.py, the lines the private-run section cites. - sheeki03, tirith, at commit
22a60f22504481f56a5fd4d53bea13da3dbe5a52: the name and shape of the MCP lockfile (tirith mcp lock, README line 484), cited by commit and for the shape alone; the repository is AGPL-3.0 and none of its code is in this book. - Norm Hardy’s The Confused Deputy (1988) and Simon Willison’s The lethal trifecta (2025) are chapter 46’s and are cited there; this chapter’s broker, hardening and log are what is left when the deputy’s confusion has been argued and its credentials are still on the host.