From a8627e73bd66174a94f77887aeed67222977f033 Mon Sep 17 00:00:00 2001 From: Zachary Lowden Date: Wed, 11 Nov 2026 11:17:46 -0600 Subject: [PATCH 1/3] wip: narrow F2 to cache-root path Co-Authored-By: Claude Opus 5.5 (1M context) From 84aeb2954c8e281d745dc7ecc04e190165ba8d43 Mon Sep 17 00:00:00 2001 From: Zachary Lowden Date: Wed, 11 Nov 2026 11:33:26 -0600 Subject: [PATCH 2/3] fix(scopeuse): narrow F2 from the bare substring to the cache-root path F2 made a session owner-only (`*`) whenever any tool input contained `subsystem-store`. The 2026-11-11 re-census found all 13 derived-`*` sessions in the fresh cohort got it from F2, overwhelmingly from named reads of one cache file, plus false positives that are not cache reads at all (a kubectl namespace, a repo path, a script name, ~/.config/...). Now a tool input naming `<...cache...>/subsystem-store//...` adds THAT scope (folded into R_header, so the capture agent and the pod's re-derivation both carry it through the existing paths). Still `*`: the bare root, an invalid/glob/$VAR component, another instance's `subsystem-store-` root (derived scopes carry no instance), a sync staging sibling, a relative root, a root under an unreadable parent spelling (`$C/subsystem-store`), and any input with a `..` component or a `cd` into the cache. Adds nothing: a non-cache mention (namespace, literal repo/config parent, longer word, the `.lock` sibling). Tests: f2_test.go (named, fail-closed, non-cache tables; the client's own CacheRootFor; a linearity test that caught a 52 s quadratic in an intermediate version). Mutant battery: the F2 row is re-pointed and five rows added (bare-substring, bare-root-not-star, component-not-validated, other-instance-scope-trusted, unknown-parent-not-a-cache), each KILLED. Co-Authored-By: Claude Opus 5.5 (1M context) --- claudedocs/plan-cairn-plugins.md | 9 + internal/transcript/scopeuse/f2_test.go | 196 +++++++++++++ internal/transcript/scopeuse/scopeuse.go | 267 +++++++++++++++++- internal/transcript/scopeuse/scopeuse_test.go | 11 +- tests/control_mutants.py | 64 ++++- 5 files changed, 529 insertions(+), 18 deletions(-) create mode 100644 internal/transcript/scopeuse/f2_test.go diff --git a/claudedocs/plan-cairn-plugins.md b/claudedocs/plan-cairn-plugins.md index e3ade1bb..4edc6b76 100644 --- a/claudedocs/plan-cairn-plugins.md +++ b/claudedocs/plan-cairn-plugins.md @@ -916,6 +916,15 @@ script that prints only counts. `~/.config/subsystem-store/` over-matches too; that fails safe. ⚠ F2 does NOT see a local store copy at a path without that name — a `--cache ` root (`internal/client/cli.go:339`) or a `CAIRN_MIRROR_ROOT` mirror (`cli.go:834`) read by file tools; T3 names it. + *2026-11-11, superseding the bare-substring rule above and O18's "F2 is not narrowed": the + operator chose to narrow F2 to the cache-root PATH (the 2026-11-11 census: all 13 derived-`*` + sessions in the fresh cohort came from F2, mostly named reads of one cache file). A + `…cache…/subsystem-store//…` path now adds that scope; a path it cannot + attribute to one default-instance scope (bare root, glob or `$VAR` component, another + instance's `subsystem-store-`, a relative or unreadably-spelled root, a `..` component, + a `cd` into the cache) still adds `*`; a non-cache mention (a namespace, a repo path, + `~/.config/subsystem-store/`) adds nothing. The exact rule is + `internal/transcript/scopeuse`'s `eachCacheRead`.* A call is never matched to "its" ledger record: the rules ask only "is the ledger empty" and "does any input name the cache", which is what keeps the shell grammar out of the design. - *DELETED in revision 13 (O11), with the ledger in its place:* the shell-command-line parser diff --git a/internal/transcript/scopeuse/f2_test.go b/internal/transcript/scopeuse/f2_test.go new file mode 100644 index 00000000..aa6ae57a --- /dev/null +++ b/internal/transcript/scopeuse/f2_test.go @@ -0,0 +1,196 @@ +package scopeuse + +import ( + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "github.com/ZacxDev/cairn/internal/client" +) + +// The F2 cases with LITERAL expectations. Every scope name is distinct from every other case's and +// from every constant the code names (`subsystem-store`, `cache`, `personal`, `lock`, `*`), so a +// mutant that hardcodes a literal, or returns another case's answer, cannot pass. + +// TestF2NamedCacheReadAddsThatScope: case 1 — a path INTO the default cache root, `//…` +// with a valid scope, is a NAMED read in every spelling of the root, and adds that scope, not `*`. +func TestF2NamedCacheReadAddsThatScope(t *testing.T) { + cases := map[string][]string{ + "grep -n rate ~/.cache/subsystem-store/quartz-lantern/prom-s.md": {"quartz-lantern"}, + "sed -n 1,40p /home/zach/.cache/subsystem-store/ember_7/nix.md": {"ember_7"}, + `F=/home/zach/.cache/subsystem-store/Velvet-Fox/civ-dp.md; cat "$F"`: {"Velvet-Fox"}, + "cat $HOME/.cache/subsystem-store/oak9/x.md": {"oak9"}, + `cat "${HOME}/.cache/subsystem-store/moss-ridge/a.md"`: {"moss-ridge"}, + "cat ${XDG_CACHE_HOME:-$HOME/.cache}/subsystem-store/tern-a/b.md": {"tern-a"}, + "cat $XDG_CACHE_HOME/subsystem-store/tern-b/x.md": {"tern-b"}, + "cat ~/.CACHE/SUBSYSTEM-STORE/Kite3/x.md": {"Kite3"}, + "ls ~/.cache/subsystem-store/heron-2": {"heron-2"}, + "/tmp/h1/.cache/subsystem-store/plover/x.md": {"plover"}, + "cat ~/.cache/subsystem-store/wren/*.md": {"wren"}, + "$(cat ~/.cache/subsystem-store/gull4/a.md)": {"gull4"}, + "cat ~/.cache/subsystem-store/stilt/a.md ~/.cache/subsystem-store/curlew": {"stilt", "curlew"}, + // Controls for the fail-closed checks: a git range is not a `..` component, and a `cd` + // somewhere else does not poison the read after it. + "git log main..HEAD; cat ~/.cache/subsystem-store/sanderling/x.md": {"sanderling"}, + "cd /work/repo && cat ~/.cache/subsystem-store/knot5/x.md": {"knot5"}, + // The name inside the scope's own path is not a second root. + "cat ~/.cache/subsystem-store/dunlin/subsystem-store-notes.md": {"dunlin"}, + } + for in, want := range cases { + if got := CacheScopes(in); !slices.Equal(got, want) { + t.Errorf("CacheScopes(%q) = %v, want %v", in, got, want) + } + } + // Through the Deriver: the scope reaches V and Declare, and F2 contributes no `*`. + d := NewDeriver() + d.ToolInput("sed -n 1,40p /home/zach/.cache/subsystem-store/ember_7/nix.md") + r := d.Result() + if r.F2 || !slices.Equal(r.V, []string{"ember_7"}) || !slices.Equal(r.Declare, []string{"ember_7"}) { + t.Fatalf("F2=%v V=%v Declare=%v, want no F2 and [ember_7] in both", r.F2, r.V, r.Declare) + } + // It survives a capture run's Evidence round-trip. + d2 := NewDeriver() + d2.Restore(d.Evidence()) + if got := d2.Result().V; !slices.Equal(got, []string{"ember_7"}) { + t.Fatalf("after Restore: V = %v, want [ember_7]", got) + } +} + +// TestF2UnattributableCacheReadAddsStar: case 2 and 3 — a cache path that cannot be attributed to +// ONE default-instance scope still fails closed. +func TestF2UnattributableCacheReadAddsStar(t *testing.T) { + star := []string{Star} + cases := map[string][]string{ + "S=/home/zach/.cache/subsystem-store; for f in $S/*/x.md; do cat $f; done": star, + "ls ~/.cache/subsystem-store": star, + "ls ~/.cache/subsystem-store/": star, + `ls "$HOME/.cache/subsystem-store"`: star, + "cat ~/.cache/subsystem-store/*/index.md": star, + "ls ~/.cache/subsystem-store*": star, + "cat ~/.cache/subsystem-store/bad.name1/x.md": star, // fails ValidScope + "cat ~/.cache/subsystem-store/$SC1/x.md": star, + "cat ~/.cache/subsystem-store/{alder1,birch1}/x.md": star, + `cat ~/.cache/subsystem-store/dev"rc1"/x.md`: star, // the shell reads devrc1, not dev + "cat ~/.cache/subsystem-store//x.md": star, + "cat ~/.cache/subsystem-store/.sync-stamp": star, + "cat ~/.cache/subsystem-store/lark1/../finch1/x.md": star, + "cd ~/.cache/subsystem-store/lark2 && cat x.md": star, + "cd ~/.cache && cat subsystem-store/lark3/x.md": star, // relative: cwd unknown + "cat ./subsystem-store/lark4/x.md": star, + "ls ~/.cache/subsystem-store.new-abc/lark5": star, // a sync staging sibling + "C=~/.cache; cat $C/subsystem-store/lark6/x.md": star, // an unrecognised spelling + `cat "$C"/subsystem-store`: star, + // Case 3: ANOTHER instance's cache root. Derived scopes carry no instance, so a named read + // there cannot be attributed — `*`, never its scope. + "S=/home/zach/.cache/subsystem-store-civitai/datapacket-x1; for f in $S/*; do :; done": star, + "cat ~/.cache/subsystem-store-civitai/pipit/x.md": star, + } + for in, want := range cases { + if got := CacheScopes(in); !slices.Equal(got, want) { + t.Errorf("CacheScopes(%q) = %v, want %v", in, got, want) + } + } + d := NewDeriver() + d.ToolInput("S=/home/zach/.cache/subsystem-store; grep -l x $S/*/y.md") + if r := d.Result(); !r.F2 || !slices.Equal(r.V, star) || !slices.Equal(r.Declare, star) { + t.Fatalf("bare root: F2=%v V=%v Declare=%v, want F2 and [*] in both", r.F2, r.V, r.Declare) + } +} + +// TestF2NonCachePathsAddNothing: case 4 — `subsystem-store` that is not a cache path. +func TestF2NonCachePathsAddNothing(t *testing.T) { + for _, in := range []string{ + "kubectl -n subsystem-store exec deploy/subsystem-store -- ls /data", + "kubectl --namespace=subsystem-store get pods", + "bash scripts/test-check-subsystem-store-phase1.sh", + "cat clusters/homelab/apps/subsystem-store/ui-deployment.yaml", + "cat ~/.config/subsystem-store/env", + "ls /home/zach/.config/subsystem-store/instances/", + "ls -la ~/.cache/subsystem-store.lock ~/.cache/subsystem-store-civitai.lock", + "docker pull ghcr.io/zacxdev/subsystem-stores:v1", + "git log main..HEAD -- internal/subsystem-store/x.go", + } { + if got := CacheScopes(in); len(got) != 0 { + t.Errorf("CacheScopes(%q) = %v, want nothing", in, got) + } + d := NewDeriver() + d.ToolInput(in) + if r := d.Result(); r.F2 || len(r.V) != 0 { + t.Errorf("%q: F2=%v V=%v, want neither", in, r.F2, r.V) + } + } +} + +// TestCacheScopesMatchesTheClientsCacheRoot: the root F2 parses is the root the client resolves, +// for the default instance and for another one, so moving either turns this red. +func TestCacheScopesMatchesTheClientsCacheRoot(t *testing.T) { + t.Setenv("HOME", "/home/u9") + def, err := client.CacheRootFor(client.DefaultAlias) + if err != nil { + t.Fatal(err) + } + if got := CacheScopes(filepath.Join(def, "sandpiper", "a.md")); !slices.Equal(got, []string{"sandpiper"}) { + t.Fatalf("a read under the client's default root %s: %v, want [sandpiper]", def, got) + } + other, err := client.CacheRootFor("civitai") + if err != nil { + t.Fatal(err) + } + if got := CacheScopes(filepath.Join(other, "sandpiper", "a.md")); !slices.Equal(got, []string{Star}) { + t.Fatalf("a read under the client's civitai root %s: %v, want [*]", other, got) + } +} + +// TestCacheScopesIsLinear: the pod runs F2 over every tool input it stores, so it is held to +// linear growth the way [TestHeaderScopesIsLinearOnARunOfMarkers] holds the header scan, on the +// shapes that would make a per-occurrence rescan quadratic: a run of alias suffixes (one `-`-joined +// word, so a rescan from each occurrence reads to its end), a run of cache roots, and a run of +// quoted relative roots. Same bound and method: best of five at two sizes, growth ratio under 24×. +func TestCacheScopesIsLinear(t *testing.T) { + const small, large = 256 << 10, 2 << 20 + for _, tc := range []struct { + name, unit string + want []string + }{ + {"alias run", CacheRootName + "-", nil}, + {"cache roots", "/.cache/" + CacheRootName, []string{Star}}, + {"quoted relative roots", `"` + CacheRootName + "/", []string{Star}}, + } { + t.Run(tc.name, func(t *testing.T) { + best := func(size int) time.Duration { + in := strings.Repeat(tc.unit, size/len(tc.unit)) + lower := asciiLower(in) + var min time.Duration + for run := 0; run < 5; run++ { + seen := map[string]bool{} + start := time.Now() + eachCacheRead(in, lower, func(v string) { seen[v] = true }) + took := time.Since(start) + if took > 5*time.Second { + t.Fatalf("one %d-byte input of %q took %v", size, tc.unit, took) + } + var got []string + for v := range seen { + got = append(got, v) + } + if !slices.Equal(asSet(got), asSet(tc.want)) { + t.Fatalf("a run of %q answered %v, want %v", tc.unit, asSet(got), tc.want) + } + if run == 0 || took < min { + min = took + } + } + return min + } + s, l := best(small), best(large) + ratio := float64(l) / float64(max(s, time.Microsecond)) + t.Logf("%q: %d B best %v, %d B best %v, growth %.1f× for 8× the input", tc.unit, small, s, large, l, ratio) + if ratio > 24 { + t.Fatalf("growth %.1f× for 8× the input (linear ~8×, quadratic ~64×): %v at %d B, %v at %d B", + ratio, s, small, l, large) + } + }) + } +} diff --git a/internal/transcript/scopeuse/scopeuse.go b/internal/transcript/scopeuse/scopeuse.go index ad324279..d1f05407 100644 --- a/internal/transcript/scopeuse/scopeuse.go +++ b/internal/transcript/scopeuse/scopeuse.go @@ -5,7 +5,8 @@ // 🔴 ONE FUNCTION, TWO CALLERS, THE SAME ANSWER. `cmd/cairn-capture` computes it for ROUTING // (decision 16) and `cairn-ui` will re-derive it over the STORED records (S3), so an old or lying // agent cannot shrink `V`. Neither caller resolves a working directory or parses a shell line: a -// command line is read for exactly two substrings (F1, F2), never decomposed. +// command line is read for one substring (F1) and for cache-root PATHS (F2) — never decomposed +// into commands, and never resolved against a working directory or a variable. // // 🔴 EVERYTHING HERE ONLY ADDS. A header quoted in prose, a spurious ledger record, an // over-matching F1 or F2 — each adds a scope or `*`, which hides the session from MORE people. The @@ -26,13 +27,30 @@ // or names an invalid scope, contributes `*`. // - F1: a tool INPUT names `cairn` or `subsystem-recall` (case-insensitive) AND the ledger holds // ZERO records → `*`. It asks "is the ledger empty", never "which record is this call's". -// - F2: a tool input names `subsystem-store` (the client cache root's directory name) → `*`, -// because a file read from the cache never passes through the client and is never ledgered. +// - F2 (named scopes folded into R_header): a tool input naming a path INTO the client cache +// (`<…cache…>/subsystem-store//…`) adds that scope, because a file read from the cache +// never passes through the client and is never ledgered, so the path is the only record of it. +// A cache path it cannot attribute to ONE default-instance scope adds `*`: the bare root +// (`S=~/.cache/subsystem-store;`, `ls ~/.cache/subsystem-store`), a component that is not a +// valid scope (a glob, `$VAR`, `{a,b}`, `.sync-stamp`), ANOTHER instance's root +// (`subsystem-store-` — derived scopes carry no instance), a sync staging sibling +// (`subsystem-store.new-…`), a relative `subsystem-store/…`, a root whose parent component is +// a spelling this cannot read (`$C/subsystem-store/…`), and any input that also holds a +// `..` component or `cd`s into the cache. `subsystem-store` that is NOT a cache path — a +// namespace (`-n subsystem-store`), a repo path (`apps/subsystem-store/…`), the config dir +// (`~/.config/subsystem-store/`), a file name (`check-subsystem-store.sh`), the `.lock` +// sibling — adds nothing ([eachCacheRead] has the exact rule). // // ⚠ WHAT IT CANNOT SEE (threat T3): a session mixing a ledger-writing client with one that writes // nothing (non-empty ledger, so F1 is silent); a file read of a store copy whose path lacks -// `subsystem-store`; a read that bypasses the client entirely; a memo shown by any path that does -// not print the renderer's block (a memo's text quoted without its fence, or the browser tab). +// `subsystem-store`, or lacks a `cache`-named parent component; a read through a variable or a +// working directory set in an EARLIER call (`$S/devrc/x.md` after `S=~/.cache/subsystem-store`, +// or a relative path after `cd ~/.cache/subsystem-store/devrc`) — the call that SETS a bare root +// or `cd`s into the cache is itself `*`, so such a session is still owner-only, but one that sets +// `S=~/.cache/subsystem-store/devrc` adds only `devrc`, and a later `$S/../alpha/x.md` is unseen; a bare relative `subsystem-store` with no `/` after it (indistinguishable from the +// namespace); a symlink into the cache; a read that bypasses the client entirely; a memo shown by +// any path that does not print the renderer's block (a memo's text quoted without its fence, or +// the browser tab). package scopeuse import ( @@ -405,13 +423,241 @@ func eachJSONString(t string, emit func(string)) { // Inputs are content too, so the header scan runs on them as well. func (d *Deriver) ToolInput(s string) { d.Content(s) - lower := strings.ToLower(s) + lower := asciiLower(s) if strings.Contains(lower, "cairn") || strings.Contains(lower, "subsystem-recall") { d.namesProgram = true } - if strings.Contains(lower, "subsystem-store") { - d.namesCache = true + eachCacheRead(s, lower, func(sc string) { + if sc == Star { + d.namesCache = true + } else { + d.addHeader(sc) + } + }) +} + +// CacheRootName is the default instance's cache directory name (`client.DefaultCacheRoot`: +// `$HOME/.cache/subsystem-store`; another instance's is the sibling `subsystem-store-`, +// `client.CacheRootFor`). Spelled here, not imported, for the same reason as [MemoBlockOpen]: +// `internal/client` would pull the whole client into every capture binary. +// `TestCacheScopesMatchesTheClientsCacheRoot` holds it to the client's resolution, so a moved +// root turns that test red instead of silently making F2 blind. +const CacheRootName = "subsystem-store" + +// lockSuffix is the client's sync lock beside a cache root (`client/snapshot.go`): a sibling FILE, +// not a store, so naming it is not a read. +const lockSuffix = ".lock" + +// CacheScopes returns what F2 adds for one tool input: the scope of every cache-root READ it names, +// `*` for one it cannot attribute to a single default-instance scope. See [eachCacheRead]. +func CacheScopes(s string) []string { + var out []string + eachCacheRead(s, asciiLower(s), func(v string) { out = append(out, v) }) + return out +} + +// eachCacheRead is F2. A file read from the client cache never passes through the client and is +// never ledgered, so the PATH is the only evidence of what was read. It finds every +// `subsystem-store` (case-insensitive) in s and classifies it — a NAME, not a substring: +// +// - NOT A CACHE PATH, adds nothing: the name is part of a longer word (`test-check-subsystem- +// store-phase1.sh`, `subsystem-stores`); it is a path component whose parent is a plain +// literal word not containing `cache` (`clusters/…/apps/subsystem-store/…`, +// `~/.config/subsystem-store/`, `deploy/subsystem-store`); it is a bare word with no `/` after it (`kubectl -n +// subsystem-store`); or it is the sync lock `subsystem-store[-alias].lock` and nothing more. +// - A CACHE ROOT: the parent component contains `cache` — `~/.cache`, `/home//.cache`, +// `$HOME/.cache`, `"${HOME}/.cache"`, `$XDG_CACHE_HOME`, `${XDG_CACHE_HOME:-~/.cache}`, and any +// other spelling that ends in a component naming a cache (the client resolves only +// `$HOME/.cache`, so the XDG spellings are caught to fail closed, not because they are real). +// A RELATIVE `subsystem-store/…` (preceded by whitespace, punctuation, `./` or `../`) is `*`: +// the working directory is unknown. So is one whose parent component is neither a cache nor a +// plain literal word (`$C/subsystem-store`, `"$C"/subsystem-store/…`, `~/subsystem-store`): +// an unrecognised spelling of the root is `*`, never "not a cache" ([rootContext]). +// - A cache root adds `*` unless EVERYTHING below holds, and then adds the scope: +// it is the default instance (no `-` suffix: derived scopes carry no instance, so a +// scope read from ANOTHER instance's cache cannot be attributed — routing would send it by name +// to whatever instance the table says); a `/` follows it; the next component, up to `/` or a +// shell separator, passes [ValidScope] (a bare root, `*`, `$S`, `{a,b}`, a quoted or empty +// component all fail); the input holds no `..` path component ([hasParentComponent]); and the input does not `cd`/`pushd` +// into a path naming the cache (the working directory then persists into calls this cannot +// connect to it). Anything else after the root name — `-*`, `.new-…`, `_old` — is `*`. +// +// LINEAR: every occurrence looks back over its parent component only (disjoint per occurrence) +// and forward over its scope component; the `..` and `cd` checks are one pass each per input. +// +// lower is asciiLower(s), passed in so the one copy [Deriver.ToolInput] makes serves F1 and F2. +func eachCacheRead(s, lower string, emit func(string)) { + if !strings.Contains(lower, CacheRootName) { + return + } + poisoned := -1 // lazily: 1 if the input holds `..` or a cd into the cache, else 0 + isPoisoned := func() bool { + if poisoned < 0 { + poisoned = 0 + if hasParentComponent(s) || cdsIntoCache(lower) { + poisoned = 1 + } + } + return poisoned == 1 + } + for off := 0; ; { + j := strings.Index(lower[off:], CacheRootName) + if j < 0 { + return + } + i := off + j + end := i + len(CacheRootName) + // The alias suffix, `client.ValidAlias`'s `-[a-z0-9][a-z0-9-]*`. + alias := false + if end+1 < len(lower) && lower[end] == '-' && isAlnum(lower[end+1]) { + alias = true + end++ + for end < len(lower) && (isAlnum(lower[end]) || lower[end] == '-') { + end++ + } + } + // 🔴 THE NEXT SEARCH STARTS PAST THE ALIAS, NOT PAST THE NAME: an occurrence inside it is the + // same word (preceded by `-`, never a root), and starting inside it re-read the alias to its + // end from every occurrence — quadratic, 52 s on a 2 MiB `subsystem-store-` run + // (`TestCacheScopesIsLinear`). + off = end + var next byte // 0 = end of input + if end < len(lower) { + next = lower[end] + } + if isAlnum(next) { + continue // a longer word + } + if strings.HasPrefix(lower[end:], lockSuffix) { + after := end + len(lockSuffix) + if after == len(lower) || !isPathByte(lower[after]) { + continue // the sync lock, a file + } + } + switch kind := rootContext(lower, i); { + case kind == notRoot: + continue + case kind == relativeRoot && next != '/': + continue // a bare word: a namespace, a service name + case kind == relativeRoot, kind == unknownRoot: + emit(Star) + continue + } + if alias || next != '/' || isPoisoned() { + emit(Star) + continue + } + start := end + 1 + stop := start + for stop < len(s) && s[stop] != '/' && !isShellSeparator(s[stop]) { + stop++ + } + if sc := s[start:stop]; ValidScope(sc) { + emit(sc) + } else { + emit(Star) + } + } +} + +type rootKind int + +const ( + notRoot rootKind = iota + cacheRoot + relativeRoot + unknownRoot +) + +// rootContext classifies the occurrence of [CacheRootName] at i by what precedes it. +// +// A parent component is a cache (`cacheRoot`) when it contains `cache`; NOT one (`notRoot`) only +// when it is a plain LITERAL word — `[a-z0-9._-]+`, as a repo directory, `.config` or a kubectl +// `deploy/` is. A parent this cannot read as either — empty (`/subsystem-store`), or holding a +// shell expansion (`$C/…`, `"$C"/…`, `~/…`, `*/…`) — is `unknownRoot`, which is `*`: a spelling of +// the cache this does not recognise must never fall silently into "not a cache". +func rootContext(lower string, i int) rootKind { + if i == 0 { + return relativeRoot + } + switch c := lower[i-1]; { + case c == '/': + p := i - 1 + for p > 0 && lower[p-1] != '/' && !isShellSeparator(lower[p-1]) { + p-- + } + parent := lower[p : i-1] + switch { + case strings.Contains(parent, "cache"): + return cacheRoot + case parent == "." || parent == "..": + return relativeRoot + case parent != "" && strings.Trim(parent, "abcdefghijklmnopqrstuvwxyz0123456789._-") == "": + return notRoot + } + return unknownRoot + case isAlnum(c) || c == '-' || c == '_' || c == '.': + return notRoot // inside a longer word + } + return relativeRoot // after whitespace, a quote, `=`, `(` … +} + +var cdIntoCache = regexp.MustCompile(`(?:^|[\s;&|(])(?:cd|pushd)(?:\s+-\S*)*\s+\S*` + CacheRootName) + +// hasParentComponent reports whether s holds a `..` path component: `..` with a path boundary on +// both sides (`/`, a shell separator, a quote, `{`, `,`, `=` or the end), so `a/../b`, `$S/..` +// and `".."` count and a git range `main..HEAD` does not. +func hasParentComponent(s string) bool { + boundary := func(c byte) bool { return c == '/' || isShellSeparator(c) || strings.IndexByte(`"'{},=`, c) >= 0 } + for off := 0; ; { + j := strings.Index(s[off:], "..") + if j < 0 { + return false + } + i := off + j + off = i + 1 + if (i == 0 || boundary(s[i-1])) && (i+2 == len(s) || boundary(s[i+2])) { + return true + } + } +} + +// cdsIntoCache reports whether the (lowered) input changes directory to a path naming the cache. +func cdsIntoCache(lower string) bool { return cdIntoCache.MatchString(lower) } + +// isShellSeparator ends a path token: whitespace and the shell's control and redirection bytes. +// Quotes, `$`, `{`, `*` and `\` are NOT separators, so a component holding them fails +// [ValidScope] instead of being cut short into a valid-looking prefix (`dev"rc"` is `devrc` to +// the shell, and must not read as `dev`). +func isShellSeparator(c byte) bool { + return strings.IndexByte(" \t\n\r\f\v;&|<>()`", c) >= 0 +} + +// isPathByte is a byte that continues a file name. +func isPathByte(c byte) bool { + return isAlnum(c) || c == '.' || c == '-' || c == '_' || c == '/' +} + +func isAlnum(c byte) bool { + return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' +} + +// asciiLower lowers ASCII only, so every index into it is an index into s (`strings.ToLower` can +// change a string's length). F1's names and F2's are ASCII, so it finds what ToLower found. +// Like ToLower it returns s itself, allocating nothing, when s holds no upper-case byte — the +// common case, and the pod runs this over every tool input it stores. +func asciiLower(s string) string { + first := strings.IndexFunc(s, func(r rune) bool { return r >= 'A' && r <= 'Z' }) + if first < 0 { + return s + } + b := []byte(s) + for i := first; i < len(b); i++ { + if c := b[i]; c >= 'A' && c <= 'Z' { + b[i] = c + 'a' - 'A' + } } + return string(b) } // Ledger folds one session's read-ledger file (JSON Lines, decision 3a). An absent file and an @@ -475,9 +721,10 @@ func (d *Deriver) Restore(e Evidence) { // Result is what one session's evidence adds to its visibility set. type Result struct { - Headers []string // R_header + Headers []string // R_header, with R_memo and F2's named scopes folded in Ledger []string // L - F1, F2 bool + // F1 and F2 report whether each contributed `*` (F2's named scopes are in Headers). + F1, F2 bool // V is R_header ∪ L ∪ F, sorted, with `*` present when any part contributed it. V []string // Declare is V WITHOUT F1's `*`: R_header ∪ L ∪ (F2 ? `*`). It is what an agent DECLARES to the diff --git a/internal/transcript/scopeuse/scopeuse_test.go b/internal/transcript/scopeuse/scopeuse_test.go index cb83ec49..3639ccc5 100644 --- a/internal/transcript/scopeuse/scopeuse_test.go +++ b/internal/transcript/scopeuse/scopeuse_test.go @@ -193,13 +193,14 @@ func TestF1EmptyLedgerAddsStar(t *testing.T) { } } -// TestF2CacheReadAddsStar: a file-tool read of the client cache root (mutant -// scopeuse-cache-path-read-ignored). -func TestF2CacheReadAddsStar(t *testing.T) { +// TestF2CacheReadAddsItsScope: a file-tool read of one scope's file in the client cache root +// (`/home/dev/.cache/subsystem-store/alpha-notes/…`) is a NAMED read of that scope (mutant +// scopeuse-cache-path-read-ignored). It was `*` until F2 was narrowed to the cache-root path. +func TestF2CacheReadAddsItsScope(t *testing.T) { w := loadWorld(t) r := derive(t, w, "cc-f2-cache-read", false) - if !r.F2 || !slices.Equal(r.V, []string{"*"}) { - t.Fatalf("F2=%v V=%v, want F2 and [*]", r.F2, r.V) + if r.F2 || !slices.Equal(r.V, []string{"alpha-notes"}) { + t.Fatalf("F2=%v V=%v, want no F2 and [alpha-notes]", r.F2, r.V) } } diff --git a/tests/control_mutants.py b/tests/control_mutants.py index 048b507f..8f48c58f 100644 --- a/tests/control_mutants.py +++ b/tests/control_mutants.py @@ -5248,13 +5248,71 @@ def __post_init__(self) -> None: name="scopeuse-cache-path-read-ignored", pkgs=PKGS + ("./internal/transcript/scopeuse/",), path="internal/transcript/scopeuse/scopeuse.go", - old="\tif strings.Contains(lower, \"subsystem-store\") {", - new="\tif false && strings.Contains(lower, \"subsystem-store\") {", - killer="TestF2CacheReadAddsStar", + old="\teachCacheRead(s, lower, func(sc string) {", + new="\teachCacheRead(s, \"\", func(sc string) {", + killer="TestF2CacheReadAddsItsScope", + extra_killers=("TestF2NamedCacheReadAddsThatScope", "TestF2UnattributableCacheReadAddsStar"), why="a file-tool read of the cache never passes through the client, so it is never ledgered; " "dropping F2 because \"the ledger covers reads now\" is the plausible simplification, and it " "makes every cache read invisible.", ), + # F2 narrowed from the bare substring `subsystem-store` to the cache-root PATH: three guards + # of the narrowing, each of which a plausible edit removes. + Mutant( + name="scopeuse-f2-bare-substring", + pkgs=PKGS + ("./internal/transcript/scopeuse/",), + path="internal/transcript/scopeuse/scopeuse.go", + old="\teachCacheRead(s, lower, func(sc string) {\n\t\tif sc == Star {", + new="\tif strings.Contains(lower, CacheRootName) {\n\t\td.namesCache = true\n\t}\n" + "\teachCacheRead(s, lower, func(sc string) {\n\t\tif sc == Star {", + killer="TestF2NamedCacheReadAddsThatScope", + extra_killers=("TestF2CacheReadAddsItsScope", "TestF2NonCachePathsAddNothing"), + why="\"any mention of the store is `*`\" is the rule this replaced, and it reads as the safer " + "one — it made every named cache read owner-only (13 of 13 `*` sessions in the 2026-11-11 " + "census came from it).", + ), + Mutant( + name="scopeuse-f2-bare-root-not-star", + pkgs=PKGS + ("./internal/transcript/scopeuse/",), + path="internal/transcript/scopeuse/scopeuse.go", + old="\t\tif alias || next != '/' || isPoisoned() {\n\t\t\temit(Star)\n", + new="\t\tif alias || next != '/' || isPoisoned() {\n\t\t\tif next == '/' {\n\t\t\t\temit(Star)\n\t\t\t}\n", + killer="TestF2UnattributableCacheReadAddsStar", + why="a bare root names no scope, and \"no scope component, nothing to add\" reads as tidy — " + "but `S=~/.cache/subsystem-store` is how a later `$S//…` read, which this cannot " + "see, gets its path.", + ), + Mutant( + name="scopeuse-f2-component-not-validated", + pkgs=PKGS + ("./internal/transcript/scopeuse/",), + path="internal/transcript/scopeuse/scopeuse.go", + old="\t\tif sc := s[start:stop]; ValidScope(sc) {", + new="\t\tif sc := s[start:stop]; sc != \"\" {", + killer="TestF2UnattributableCacheReadAddsStar", + why="the component after the root LOOKS like the scope, so taking it as-is is the obvious " + "parse — and a glob, `$VAR` or `{a,b}` then reads as one scope it never was.", + ), + Mutant( + name="scopeuse-f2-other-instance-scope-trusted", + pkgs=PKGS + ("./internal/transcript/scopeuse/",), + path="internal/transcript/scopeuse/scopeuse.go", + old="\t\tif alias || next != '/' || isPoisoned() {", + new="\t\tif _ = alias; next != '/' || isPoisoned() {", + killer="TestF2UnattributableCacheReadAddsStar", + why="`subsystem-store-civitai//…` is laid out exactly like the default cache, so " + "parsing it the same way is natural — but derived scopes carry no instance, and routing " + "would send that scope by NAME to whatever instance the table says.", + ), + Mutant( + name="scopeuse-f2-unknown-parent-not-a-cache", + pkgs=PKGS + ("./internal/transcript/scopeuse/",), + path="internal/transcript/scopeuse/scopeuse.go", + old="\t\treturn unknownRoot\n", + new="\t\treturn notRoot\n", + killer="TestF2UnattributableCacheReadAddsStar", + why="\"a parent that does not say `cache` is not the cache\" is one line shorter, and " + "`C=~/.cache; cat $C/subsystem-store/…` then falls silently into \"not a cache path\".", + ), # S2 review round 1 (F3): four guards that each SURVIVED a mutation with no test reaching them. Mutant( name="scopeuse-restore-ignored", From 8f7196b2c148378a06033f1e00052c4ba3fde62f Mon Sep 17 00:00:00 2001 From: Zachary Lowden Date: Wed, 11 Nov 2026 11:45:49 -0600 Subject: [PATCH 3/3] test(scopeuse): use synthetic names in the F2 fixtures and comments leakscan refused 8 denied identifiers (real project, cluster and host names) in the new F2 tests and doc comment. Replaced with synthetic ones; no behaviour change. Co-Authored-By: Claude Opus 5.5 (1M context) --- internal/transcript/scopeuse/f2_test.go | 60 ++++++++++++------------ internal/transcript/scopeuse/scopeuse.go | 11 +++-- tests/control_mutants.py | 2 +- 3 files changed, 37 insertions(+), 36 deletions(-) diff --git a/internal/transcript/scopeuse/f2_test.go b/internal/transcript/scopeuse/f2_test.go index aa6ae57a..d453204e 100644 --- a/internal/transcript/scopeuse/f2_test.go +++ b/internal/transcript/scopeuse/f2_test.go @@ -19,8 +19,8 @@ import ( func TestF2NamedCacheReadAddsThatScope(t *testing.T) { cases := map[string][]string{ "grep -n rate ~/.cache/subsystem-store/quartz-lantern/prom-s.md": {"quartz-lantern"}, - "sed -n 1,40p /home/zach/.cache/subsystem-store/ember_7/nix.md": {"ember_7"}, - `F=/home/zach/.cache/subsystem-store/Velvet-Fox/civ-dp.md; cat "$F"`: {"Velvet-Fox"}, + "sed -n 1,40p /home/u1/.cache/subsystem-store/ember_7/nix.md": {"ember_7"}, + `F=/home/u1/.cache/subsystem-store/Velvet-Fox/civ-dp.md; cat "$F"`: {"Velvet-Fox"}, "cat $HOME/.cache/subsystem-store/oak9/x.md": {"oak9"}, `cat "${HOME}/.cache/subsystem-store/moss-ridge/a.md"`: {"moss-ridge"}, "cat ${XDG_CACHE_HOME:-$HOME/.cache}/subsystem-store/tern-a/b.md": {"tern-a"}, @@ -45,7 +45,7 @@ func TestF2NamedCacheReadAddsThatScope(t *testing.T) { } // Through the Deriver: the scope reaches V and Declare, and F2 contributes no `*`. d := NewDeriver() - d.ToolInput("sed -n 1,40p /home/zach/.cache/subsystem-store/ember_7/nix.md") + d.ToolInput("sed -n 1,40p /home/u1/.cache/subsystem-store/ember_7/nix.md") r := d.Result() if r.F2 || !slices.Equal(r.V, []string{"ember_7"}) || !slices.Equal(r.Declare, []string{"ember_7"}) { t.Fatalf("F2=%v V=%v Declare=%v, want no F2 and [ember_7] in both", r.F2, r.V, r.Declare) @@ -63,29 +63,29 @@ func TestF2NamedCacheReadAddsThatScope(t *testing.T) { func TestF2UnattributableCacheReadAddsStar(t *testing.T) { star := []string{Star} cases := map[string][]string{ - "S=/home/zach/.cache/subsystem-store; for f in $S/*/x.md; do cat $f; done": star, - "ls ~/.cache/subsystem-store": star, - "ls ~/.cache/subsystem-store/": star, - `ls "$HOME/.cache/subsystem-store"`: star, - "cat ~/.cache/subsystem-store/*/index.md": star, - "ls ~/.cache/subsystem-store*": star, - "cat ~/.cache/subsystem-store/bad.name1/x.md": star, // fails ValidScope - "cat ~/.cache/subsystem-store/$SC1/x.md": star, - "cat ~/.cache/subsystem-store/{alder1,birch1}/x.md": star, - `cat ~/.cache/subsystem-store/dev"rc1"/x.md`: star, // the shell reads devrc1, not dev - "cat ~/.cache/subsystem-store//x.md": star, - "cat ~/.cache/subsystem-store/.sync-stamp": star, - "cat ~/.cache/subsystem-store/lark1/../finch1/x.md": star, - "cd ~/.cache/subsystem-store/lark2 && cat x.md": star, - "cd ~/.cache && cat subsystem-store/lark3/x.md": star, // relative: cwd unknown - "cat ./subsystem-store/lark4/x.md": star, - "ls ~/.cache/subsystem-store.new-abc/lark5": star, // a sync staging sibling - "C=~/.cache; cat $C/subsystem-store/lark6/x.md": star, // an unrecognised spelling - `cat "$C"/subsystem-store`: star, + "S=/home/u1/.cache/subsystem-store; for f in $S/*/x.md; do cat $f; done": star, + "ls ~/.cache/subsystem-store": star, + "ls ~/.cache/subsystem-store/": star, + `ls "$HOME/.cache/subsystem-store"`: star, + "cat ~/.cache/subsystem-store/*/index.md": star, + "ls ~/.cache/subsystem-store*": star, + "cat ~/.cache/subsystem-store/bad.name1/x.md": star, // fails ValidScope + "cat ~/.cache/subsystem-store/$SC1/x.md": star, + "cat ~/.cache/subsystem-store/{alder1,birch1}/x.md": star, + `cat ~/.cache/subsystem-store/no"tes1"/x.md`: star, // the shell reads notes1, not no + "cat ~/.cache/subsystem-store//x.md": star, + "cat ~/.cache/subsystem-store/.sync-stamp": star, + "cat ~/.cache/subsystem-store/lark1/../finch1/x.md": star, + "cd ~/.cache/subsystem-store/lark2 && cat x.md": star, + "cd ~/.cache && cat subsystem-store/lark3/x.md": star, // relative: cwd unknown + "cat ./subsystem-store/lark4/x.md": star, + "ls ~/.cache/subsystem-store.new-abc/lark5": star, // a sync staging sibling + "C=~/.cache; cat $C/subsystem-store/lark6/x.md": star, // an unrecognised spelling + `cat "$C"/subsystem-store`: star, // Case 3: ANOTHER instance's cache root. Derived scopes carry no instance, so a named read // there cannot be attributed — `*`, never its scope. - "S=/home/zach/.cache/subsystem-store-civitai/datapacket-x1; for f in $S/*; do :; done": star, - "cat ~/.cache/subsystem-store-civitai/pipit/x.md": star, + "S=/home/u1/.cache/subsystem-store-client/ridge-x1; for f in $S/*; do :; done": star, + "cat ~/.cache/subsystem-store-client/pipit/x.md": star, } for in, want := range cases { if got := CacheScopes(in); !slices.Equal(got, want) { @@ -93,7 +93,7 @@ func TestF2UnattributableCacheReadAddsStar(t *testing.T) { } } d := NewDeriver() - d.ToolInput("S=/home/zach/.cache/subsystem-store; grep -l x $S/*/y.md") + d.ToolInput("S=/home/u1/.cache/subsystem-store; grep -l x $S/*/y.md") if r := d.Result(); !r.F2 || !slices.Equal(r.V, star) || !slices.Equal(r.Declare, star) { t.Fatalf("bare root: F2=%v V=%v Declare=%v, want F2 and [*] in both", r.F2, r.V, r.Declare) } @@ -105,10 +105,10 @@ func TestF2NonCachePathsAddNothing(t *testing.T) { "kubectl -n subsystem-store exec deploy/subsystem-store -- ls /data", "kubectl --namespace=subsystem-store get pods", "bash scripts/test-check-subsystem-store-phase1.sh", - "cat clusters/homelab/apps/subsystem-store/ui-deployment.yaml", + "cat clusters/lab1/apps/subsystem-store/ui-deployment.yaml", "cat ~/.config/subsystem-store/env", - "ls /home/zach/.config/subsystem-store/instances/", - "ls -la ~/.cache/subsystem-store.lock ~/.cache/subsystem-store-civitai.lock", + "ls /home/u1/.config/subsystem-store/instances/", + "ls -la ~/.cache/subsystem-store.lock ~/.cache/subsystem-store-client.lock", "docker pull ghcr.io/zacxdev/subsystem-stores:v1", "git log main..HEAD -- internal/subsystem-store/x.go", } { @@ -134,12 +134,12 @@ func TestCacheScopesMatchesTheClientsCacheRoot(t *testing.T) { if got := CacheScopes(filepath.Join(def, "sandpiper", "a.md")); !slices.Equal(got, []string{"sandpiper"}) { t.Fatalf("a read under the client's default root %s: %v, want [sandpiper]", def, got) } - other, err := client.CacheRootFor("civitai") + other, err := client.CacheRootFor("client") if err != nil { t.Fatal(err) } if got := CacheScopes(filepath.Join(other, "sandpiper", "a.md")); !slices.Equal(got, []string{Star}) { - t.Fatalf("a read under the client's civitai root %s: %v, want [*]", other, got) + t.Fatalf("a read under the client instance's root %s: %v, want [*]", other, got) } } diff --git a/internal/transcript/scopeuse/scopeuse.go b/internal/transcript/scopeuse/scopeuse.go index d1f05407..ac345952 100644 --- a/internal/transcript/scopeuse/scopeuse.go +++ b/internal/transcript/scopeuse/scopeuse.go @@ -44,10 +44,11 @@ // ⚠ WHAT IT CANNOT SEE (threat T3): a session mixing a ledger-writing client with one that writes // nothing (non-empty ledger, so F1 is silent); a file read of a store copy whose path lacks // `subsystem-store`, or lacks a `cache`-named parent component; a read through a variable or a -// working directory set in an EARLIER call (`$S/devrc/x.md` after `S=~/.cache/subsystem-store`, -// or a relative path after `cd ~/.cache/subsystem-store/devrc`) — the call that SETS a bare root +// working directory set in an EARLIER call (`$S/notes1/x.md` after `S=~/.cache/subsystem-store`, +// or a relative path after `cd ~/.cache/subsystem-store/notes1`) — the call that SETS a bare root // or `cd`s into the cache is itself `*`, so such a session is still owner-only, but one that sets -// `S=~/.cache/subsystem-store/devrc` adds only `devrc`, and a later `$S/../alpha/x.md` is unseen; a bare relative `subsystem-store` with no `/` after it (indistinguishable from the +// `S=~/.cache/subsystem-store/notes1` adds only `notes1`, and a later `$S/../alpha/x.md` is +// unseen; a bare relative `subsystem-store` with no `/` after it (indistinguishable from the // namespace); a symlink into the cache; a read that bypasses the client entirely; a memo shown by // any path that does not print the renderer's block (a memo's text quoted without its fence, or // the browser tab). @@ -627,8 +628,8 @@ func cdsIntoCache(lower string) bool { return cdIntoCache.MatchString(lower) } // isShellSeparator ends a path token: whitespace and the shell's control and redirection bytes. // Quotes, `$`, `{`, `*` and `\` are NOT separators, so a component holding them fails -// [ValidScope] instead of being cut short into a valid-looking prefix (`dev"rc"` is `devrc` to -// the shell, and must not read as `dev`). +// [ValidScope] instead of being cut short into a valid-looking prefix (`al"pha"` is `alpha` to +// the shell, and must not read as `al`). func isShellSeparator(c byte) bool { return strings.IndexByte(" \t\n\r\f\v;&|<>()`", c) >= 0 } diff --git a/tests/control_mutants.py b/tests/control_mutants.py index 8f48c58f..ef41f204 100644 --- a/tests/control_mutants.py +++ b/tests/control_mutants.py @@ -5299,7 +5299,7 @@ def __post_init__(self) -> None: old="\t\tif alias || next != '/' || isPoisoned() {", new="\t\tif _ = alias; next != '/' || isPoisoned() {", killer="TestF2UnattributableCacheReadAddsStar", - why="`subsystem-store-civitai//…` is laid out exactly like the default cache, so " + why="`subsystem-store-//…` is laid out exactly like the default cache, so " "parsing it the same way is natural — but derived scopes carry no instance, and routing " "would send that scope by NAME to whatever instance the table says.", ),