Skip to content

fix(scopeuse): narrow F2 from the bare substring to the cache-root path - #314

Closed
ZacxDev wants to merge 6 commits into
mainfrom
fix/f2-cache-root-path
Closed

ZacxDev wants to merge 6 commits into
mainfrom
fix/f2-cache-root-path

Conversation

@ZacxDev

@ZacxDev ZacxDev commented Nov 11, 2026

Copy link
Copy Markdown
Owner

Why

Re-census 2026-11-11: in the fresh handoff-writer cohort, all 13 * sessions got * from the derived set, none from the ledger. The inputs that set off F2 were mostly named reads of one cache file (sed -n … ~/.cache/subsystem-store/<scope>/x.md). The rest were not cache reads at all: a kubectl -n subsystem-store namespace flag, a script named …-subsystem-store-….sh, a repo path …/apps/subsystem-store/…, and ~/.config/subsystem-store/. The operator chose "narrow F2 to the cache-root path; stay fail-closed".

The rule (eachCacheRead in internal/transcript/scopeuse/scopeuse.go)

Each subsystem-store (case-insensitive) in a tool input is checked as a path name:

  • Named read: adds the scope. The parent component contains cache (~/.cache, /home/<u>/.cache, $HOME/.cache, "${HOME}/.cache", $XDG_CACHE_HOME, ${XDG_CACHE_HOME:-…}). There is no -<alias> suffix. A / follows the root. The next component (up to / or a shell separator) passes ValidScope. The input has no .. path component and no cd/pushd into the cache.
  • Adds * (fail-closed): every other cache root:
    • the bare root (S=~/.cache/subsystem-store;, ls ~/.cache/subsystem-store)
    • a glob, $VAR, {a,b}, quoted, empty or dotted component
    • another instance's subsystem-store-<alias>
    • .new-… staging siblings
    • a relative subsystem-store/…, ./subsystem-store/…
    • a root whose parent is neither a cache nor a plain literal word ($C/subsystem-store, "$C"/subsystem-store). An unrecognised spelling is * and never counts as "not a cache".
  • Adds nothing:
    • a longer word (check-subsystem-store-x.sh, subsystem-stores)
    • a parent that is a plain literal non-cache word (apps/, .config/, deploy/)
    • a bare word with no / after it (-n subsystem-store)
    • the subsystem-store[-alias].lock sibling

The named scopes are folded into R_header, as R_memo already is. The capture agent (Declare/V, Evidence round-trip) and the pod's re-derivation (archive.go, which unions res.Headers) therefore both carry them with no change at either call site. F2 now means "F2 contributed *".

Instances (requirement 3)

Derived scopes are bare names. capture.DecideRun routes each one by routing.AliasFor(scope), and nothing carries (instance, scope). So a named read under subsystem-store-<alias>/<scope>/ cannot be attributed: routing would send that scope by name to whichever instance the table names. Every non-default-instance cache path therefore fails closed to *. This is deliberate and pinned by test and mutant. The cross-instance * from #308 is unchanged.

Not seen (T3, in the package doc)

  • A variable or cwd set in an earlier call ($S/notes1/x.md). The call that sets a bare root or cds into the cache is itself *. A call that sets S=…/subsystem-store/notes1 adds only notes1, and a later $S/../alpha is not seen.
  • A bare relative subsystem-store with no / (it looks the same as the namespace).
  • A copy under a literal non-cache parent.
  • Symlinks.

The client does not honour XDG_CACHE_HOME for the store cache (client.DefaultCacheRoot is $HOME/.cache/subsystem-store; the Python oracle matches). The XDG spellings are caught only to fail closed. TestCacheScopesMatchesTheClientsCacheRoot checks the parser against client.CacheRootFor.

Existing data

names_cache evidence and V/Derived are grow-only, so sessions already marked * stay *. The fix applies to sessions derived from now on.

Tests

f2_test.go has literal tables for every case, with pairwise-distinct scope names. The F2 fixture test is now TestF2CacheReadAddsItsScope ([alpha-notes], was [*]).

Red at origin/main (d000023) / green at HEAD. For base, a test-only adapter maps CacheScopes(s) to base's F2 answer ([*] if ToolInput set F2, else none):

test base HEAD
TestF2NamedCacheReadAddsThatScope FAIL (17 assertions) ok
TestF2NonCachePathsAddNothing FAIL (18) ok
TestF2CacheReadAddsItsScope (fixture) FAIL ok
TestCacheScopesMatchesTheClientsCacheRoot FAIL ok
TestCacheScopesIsLinear FAIL (answer: alias run gave [*]) ok
TestF2UnattributableCacheReadAddsStar ok (invariant guard: base was already *) ok

TestCacheScopesIsLinear also caught a real quadratic in an intermediate version of this PR: 52.6 s on a 2 MiB subsystem-store- run. After the fix the same run takes 0.44 ms, about 8× growth for 8× the input.

Mutants. Rows are in tests/control_mutants.py. Each was run with --only and is KILLED, positive control GREEN:

  • scopeuse-cache-path-read-ignored (re-pointed): killed by TestF2CacheReadAddsItsScope (+ Named, Unattributable)
  • scopeuse-f2-bare-substring (a): Named (F2=true V=[* ember_7]), plus NonCache and the fixture test
  • scopeuse-f2-bare-root-not-star (b): Unattributable. The bare-root rows return [] and the Deriver assertion fails: bare root: F2=false V=[] Declare=[]
  • scopeuse-f2-component-not-validated (c): Unattributable (bad.name1, {alder1,birch1}, no"tes1", .sync-stamp, $SC1 were each taken as a scope)
  • scopeuse-f2-other-instance-scope-trusted: Unattributable (other-instance rows), plus ClientsCacheRoot
  • scopeuse-f2-unknown-parent-not-a-cache: Unattributable ($C/… rows)

Hand-run extras, not in the battery: turning off the .. check, turning off the cd check, or both, each turns Unattributable red. Widening .. to "anywhere" or cd to "any cd" turns Named red through the main..HEAD / cd /work/repo controls.

Run locally: go test + go vet on ./internal/transcript/scopeuse/... ./internal/capture/... ./internal/transcript/archive/..., all ok. Whole suite left to CI.

A second commit replaces real identifiers in the fixtures with synthetic names, after the first CI run's leakscan refused them. leakscan was run locally afterwards: 0 findings, controls PASS.

Also updated claudedocs/plan-cairn-plugins.md: a dated note under the F2 definition, superseding O18's "F2 is not narrowed".

🤖 Generated with Claude Code

Supersedes #313, which was closed because its history held content not meant for this public repo. This is the same final tree as one commit.

A tool input naming <cache-root>/<valid-scope>/... now derives THAT scope
instead of '*'. A bare or unattributable cache root (glob, variable, invalid
component, another instance's cache, '..', cd into the cache, relative path,
unreadable parent) still derives '*'. Mentions of the name that are not a
cache-root path (a namespace flag, a repo path, a config dir, a longer word,
the .lock sibling) derive nothing. Linear in input size.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@ZacxDev

ZacxDev commented Nov 11, 2026

Copy link
Copy Markdown
Owner Author

Audit round 0 (requirements & deletion): verdict requirement questioned — Q1. Ledger: round 0 · requirements: 7 (unattributed: 2) · deletion candidates: 1.

D1 — the alias-suffix parse in eachCacheRead (scopeuse.go): subsystem-store-<alias>/… already falls through to `*` without it (measured: only the `-<alias>.lock`→nothing row changes); drop it, plus mutant scopeuse-f2-other-instance-scope-trusted
Q1 — does "narrow to cache root, keep fail-closed for direct store access" include deriving the NAMED scope (not `*`) for a direct read of <cache>/subsystem-store/<scope>/…? · forcing: user

@ZacxDev

ZacxDev commented Nov 11, 2026

Copy link
Copy Markdown
Owner Author

Operator answers (2026-11-11):

Q1=answered: yes — a direct read attributable to exactly one scope derives that scope; anything not attributable to one scope stays `*`

D1 disposition: kept (small; avoids fail-closed friction on alias lock-file reads).

…oisoning

Round-1 audit of #314. F2's `..`/`cd` poisoning was decided per JSON
string, and both callers fed a tool input one string at a time, so an
opencode bash input {"command":"cat ../bb/x.md","workdir":".../aa"} (or a
Glob pattern `../bb/**` with path `.../aa`) derived [aa] where the base
gave [*].

The deriver now takes one tool input as a unit (ToolInputValue /
ToolInputStrings; ToolInput is the one-string unit; CacheScopes is
variadic). ClaudeRecord and OpencodePart, and through them the capture
agent, dry run and the pod's archive re-derivation, all feed it whole.

Within a unit, the named cache reads are replaced by `*` when ANY string
holds: a `..` component; a cd-family word (cd/pushd/popd/dirname/realpath/
readlink, with quotes, backslashes, `$`, braces and commas stripped, last
path component); an ancestor-of-the-cache argument (`/`, `~`, `$HOME`,
`/home/<u>`, `~/.cache`, `$XDG_CACHE_HOME`, any path-like word whose last
component names a cache); a cache path token holding `\ ' " { } $` a
backtick `[ ] ?` or `/.*` (a trailing run of closing quotes excepted); or
a string that is nothing but a scope directory (a workdir/path/cwd). Any
input with a `--cache` word is `*`. Direct reads of a store copy under a
non-cache parent are named in T3.

Red at f834848, green here: every row of TestF2DecidesOverTheWholeInput,
TestF2ScopeDirectoryStringAddsStar, TestF2ShellRewrittenPathAddsStar,
TestF2CdFamilyWordAddsStar (except the two labelled invariant rows),
TestF2AncestorArgumentAddsStar, TestF2CacheFlagAddsStar, and the moved
`cd /work/repo && cat .../knot6/x.md` row. Positive controls unchanged.
Seven new mutant rows (per-string, dir-only, spelled token, cd family,
ancestor, --cache, `..`) each killed by their named test; the five
existing F2 rows re-pointed at the new code and still killed.
TestCacheScopesIsLinear gains three named-read shapes, all ~8x for 8x.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@ZacxDev

ZacxDev commented Nov 11, 2026

Copy link
Copy Markdown
Owner Author

Audit round 1 (nine axes) on f834848: 1 🔴, 3 🟡, all addressed in b842b7e. Ledger: round 1 · payload lines changed THIS round: 424 (since round 1: 424). Payload = scopeuse.go; tests and tests/control_mutants.py are scaffolding (decided at round 1).

1. F2 poisoning (`..`, cd-family, scope-dir-only string) is decided once per WHOLE tool input, not per JSON string; both record callers feed whole inputs (multi-field `command`+`workdir` / Glob `pattern`+`path`)
2. a cache path whose post-root token contains `\ ' " { } $` backtick `[ ] ?` or `/.*` derives `*` (shell-rewritten `..`)
3. cd-family words (cd pushd popd dirname realpath readlink), normalised for quotes/escapes/builtin/command, poison named reads in the same input
4. an argument that is an ancestor of the cache root (`/`, `~`, `$HOME`, `/home/<u>`, a path whose last component contains `cache`) poisons named reads in the same input
5. any input with a `--cache`/`--cache=` token derives `*`; store copies under a non-cache parent are named in T3
6. doc comment "input" vs "string" wording updated to match the per-input unit

…mmar

Round-2 audit of #314. Two rounds each found shell spellings that slipped
past F2's denylist of poisoning shapes (`cat .''./.''./b/x.md` from a
workdir under the cache, `~/.cache/.`, `/home//u1`, `${HOME:-x}`, a
workdir ending `/.` or `//` ...). The operator chose an ALLOWLIST: a
named scope is derived only when it is provable from the text that the
tool input reads files of exactly those scopes; anything else that names
the cache is `*`.

The grammar (`provable`), over ONE tool input whole, each top-level string
by its key:
- a bash tool's `description` (Claude `Bash`, opencode `bash`) is skipped;
  it is still scanned for the cache name and as content;
- `workdir`/`path`/`cwd`/`dir`/`directory` must be a clean absolute path
  with no component naming `cache`, and not `/`, `/home`, `/home/<u>`,
  `/root`, `/Users`, `/Users/<u>` (`safeDir`);
- `file_path`/`filePath` must be one clean cache file path;
- every other string is a shell line (`shellLineProvable`): words split
  on space/tab; only `|`, `||`, `&&`, `;`, newline separate commands; any
  other metacharacter outside single quotes (`$` backtick `\ " { } * ? [
  ] ( ) < > & ~ ! # ^`, control bytes) fails, `~` only as the leading `~/`
  of a cache path; a single-quoted segment holding `/` or `..`, or an
  unterminated one, fails; each command's first word must be one of cat
  cut echo grep head ls nl printf tail tr uniq wc; every word holding `/`
  must be ONE unquoted `~/`, `/home/<u>/` or `/root/` +
  `.cache/subsystem-store/<valid scope>/<plain name>[/...]`
  (`cleanCachePath`); a word that is `.` or `..` once unquoted fails.

The command allowlist is beyond the brief's rules 1-5: without it
`echo <cache file> | sed s,a.x.md,, | xargs grep -r t` (the cache root),
`cat <cache file>; cd; grep -r t .cache` and `... | bash` all pass the
lexer. It replaces the cd-family word list.

Removed as subsumed: spelledToken, dirOnly, unitPoisoned, eachWord,
cdFamily/cdFamilyWord, ancestorWord, hasParentComponent. Kept: the cache
detection (rootContext, alias, lock, ValidScope) and the `--cache` rule.

Red at b842b7e, green here (TestF2AllowlistRejectsTheRoundTwoShapes, all
12 rows x both runtimes; and the regression rows of
TestF2GrammarRejects{Metacharacters,QuotedPaths,OtherPaths,DotWords,
Commands}, TestF2Workdir{MustBeOutsideTheCache,MustNotBeAnAncestor},
TestF2OnlyABashDescriptionIsFreeText). Rows already `*` at b842b7e are
marked as invariant rows in the tests. Positive controls
(TestF2AllowlistKeepsProvableReadsNamed) green at both.

Previously NAMED, now `*` (accepted over-poisoning; pinned in
TestF2UnprovableShapesAddStar):
- any `sed` (`sed -n 1,40p <file>`, `sed -n '/x/,$p' <file>`), `awk`,
  `git`, `find`, `xargs`, a shell, or any other command not on the list,
  anywhere in the same input (`git log main..HEAD; cat <file>`);
- the `$HOME`, `${HOME}`, `$XDG_CACHE_HOME` spellings; a variable set to
  a cache path (`F=<file>; cat "$F"`);
- a cache path in quotes (`cat '<file>'`, `"$HOME/..."`);
- a redirect (`> /tmp/out.txt`, `2>/dev/null`), `$(...)`, a glob in the
  file name (`<scope>/*.md`);
- a scope DIRECTORY as an argument (`ls <root>/<scope>`);
- a path that is the command itself, and a store under a non-home
  `.cache` (`/tmp/h1/.cache/subsystem-store/<scope>/x.md`);
- a different-case root (`~/.CACHE/SUBSYSTEM-STORE/...`);
- any non-cache path argument (`/work/repo`, `/tmp/out.txt`);
- a Claude Grep/Glob whose `path` is a cache file (dirRole rejects it);
  any pattern/glob string in an input naming the cache.

Mutants (tests/control_mutants.py): the dir-only, spelled-token,
cd-family, ancestor and parent-component rows are replaced by one row per
grammar rule (metachar, quoted path, other path, dot word, command,
workdir under cache, workdir ancestor, free text for every key, free text
for every tool); the per-string row is rewritten for the new entry point.
component-not-validated and other-instance-scope-trusted SURVIVED at
first: cleanCachePath re-checks both in every graded string, so the
detection checks only decide alone for a skipped bash `description`.
TestF2UnattributableCacheReadAddsStar now carries those two rows, and
both mutants die there.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@ZacxDev

ZacxDev commented Nov 11, 2026

Copy link
Copy Markdown
Owner Author

Audit round 2 (delta f834848..b842b7e): 2 🔴 (a shell-rewritten .. in a non-root string with a scope-dir workdir; ancestor-spelling misses), both fixed in ed3d8b3 by replacing the F2 denylist with an allowlist grammar (operator decision). Ledger: round 2 · payload lines changed THIS round: 561 (since round 1: 985).

1. F2 derives a named scope only if the WHOLE tool input passes a strict allowlist grammar (per-key: bash description skipped; workdir/path/cwd/dir clean absolute non-cache non-ancestor; file_path one clean cache file path; else a shell line); any failure derives `*`
2. shell lines: only `| || && ;` newline separators; listed metacharacters outside single quotes fail; single-quoted `/` or `..` fails; command first word must be in a fixed read-only allowlist
3. every `/`-word must be an unquoted clean `~/`|`/home/<u>/`|`/root/` cache file path of a valid scope; `.`/`..` words fail
4. the denylist helpers (spelledToken, dirOnly, cdFamily, ancestorWord, hasParentComponent, …) are deleted; package doc F2/T3 rewritten for the allowlist

ZacxDev and others added 3 commits November 11, 2026 14:38
…s grammar

#314 round 4. The allowlist let a word with no `/` through as an argument,
so `cat ~/.cache/subsystem-store/<scope>/x.md; grep -r x .cache` run from
the home directory derived `[<scope>]` while reading every scope. origin/main
(the bare-substring rule) gives `*` for it, so this was a fail-open regression.

Two rules in `shellLineProvable`:
- a word that, unquoted, holds `cache` or `subsystem-store` (any case) and is
  not a clean cache path fails (`.cache`, `subsystem-store`, `'.ca'che`; also
  `--cached`/`--no-cache`/`echo cached`, over-poisoned on purpose);
- a flag reading beyond the line's words fails (`readsBeyondItsWords`):
  grep `-r -R -d --recursive --dereference-recursive --directories` and any
  short cluster holding r/R/d; ls `-R --recursive` and clusters holding R;
  wc `--files0-from`. Long flags match by prefix (getopt abbreviations).
  Claude Code's Bash `grep` is a shell function running its embedded ugrep,
  where `-NUM` and `--depth` recurse (measured: `grep -n2 needle sub` found
  sub/deep/f.txt), so grep clusters holding a digit and `--depth` fail too.
  The other allowlisted commands (cat cut echo head nl printf tail tr uniq)
  have no recursive or name-list mode in their --help (coreutils 9.11).

T3 (package doc + plan) now says what remains: a relative NON-recursive file
word read from a working directory an earlier call moved into the cache via
bare relative `cd`s (Claude Code; for opencode, only its default directory).

Existing rows whose `-r` was incidental now use `-n`/`-c`, so the workdir,
dot-word and round-2 tests still decide on their own rule.

Red/green: the new f2_relative_test.go run on an ed3d8b3 export fails every
new `*` row except `grep -R x .` (already `*` there, a dot word: invariant);
all green at HEAD. Mutants scopeuse-f2-cache-word-accepted and
scopeuse-f2-recursive-flag-accepted each killed via --only by their named
test (10/10 and 24/24 rows red by hand); all 19 F2 mutant rows still killed;
scopeuse.go digest unchanged after each.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…outside the cache

Claude Code's Bash cwd persists between calls, so `cd ~/.cache`, `cd subsystem-store`,
`cd alder`, then `cat x.md` (or `cat <named birch path> x.md`) read alder while F2 derived
nothing / [birch]: no single call names a cache path, and the grammar only runs beside a named
read. origin/main's bare-substring F2 gave `*` for these, so this was a fail-open regression.

Rule (movesIntoUnseen, every input, named read or not): a shell-line string (not a bash
`description`) running `cd`/`pushd` — also after builtin/command/{/if/!/NAME=v prefixes, after
&& ; | & newline ( ) or a backtick — whose first argument, unquoted, names `cache` or
`subsystem-store` (any case), or is not a plain relative path / safeDir absolute path / clean
`~/…` path (so `$D`, "$D", -, ~, .., nothing, a glob, $(…), a flag, +N), adds `*`.
`cd /work/repo && make`, `cd src`, `pushd /tmp/build` add nothing. One linear pass.

Tests (claude tool_use + opencode): f2_cd_test.go — every `*` row RED at f029df8 except
`cd .cache/subsystem-store` (invariant: a scopeless cache root there), GREEN here; controls
green at both. TestCacheScopesIsLinear gains three lexer rows (growth ~8x for 8x input).
Mutant scopeuse-f2-directory-change-ignored: killed via --only by
TestF2DirectoryChangeAddsStar (also the chain and strings tests); tree digest restored.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…lowlist

Restructure F2 so it is never narrower than origin/main, by construction.
Main's predicate decides first, unchanged: a tool input none of whose
strings contains `subsystem-store` (any case) adds NOTHING; one that does
adds `*`, unless the whole input passes the allowlist grammar AND every
occurrence of the name lies inside a clean cache path the grammar accepted
(an occurrence count, provenScopes) - then exactly those scopes.

- Deleted: the "non-cache mentions add nothing" exceptions (namespace, repo
  path, ~/.config, longer word, .lock, alias roots: `*` again, as on main),
  the round-5 cd/pushd rule (cd lines that never name the cache add nothing
  again), the --cache flag rule, rootContext and the alias scanner.
- Every allowed command now has an explicit FLAG ALLOWLIST (commandFlags)
  replacing the recursive-flag denylist: grep allows -n -c -l -L -i -v -w
  -x -o -h -H -E -F -s -q (and clusters), -e PAT, -m/-A/-B/-C with a
  separate all-digit word, and sixteen long forms; ls has no -R, wc no
  --files0-from; an unknown flag fails.
- TestF2NeverNarrowerThanMain: property test against an inline copy of
  main's predicate over every F2 test row (corpus ledgered by
  TestF2PropertyCorpusIsEveryF2Test) plus 4000 seeded random inputs.
  At 18fb0a8 (with shims) it is red: 528 inputs main stars got nothing,
  105 inputs main leaves alone got `*`. Green at HEAD.
- New rows (f2_main_test.go) red at 18fb0a8, green here; invariant rows
  are marked in place.
- Mutants: removed the rows for deleted rules; added no-mention-adds-star,
  grammar-verdict-skipped, bare-word-mention-accepted, grep-index-allowed,
  attached-digit-accepted, ls-recursive-accepted, flag-not-allowlisted.
  All 27 scopeuse rows killed by their named test via --only.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@ZacxDev

ZacxDev commented Nov 11, 2026

Copy link
Copy Markdown
Owner Author

Closing unmerged (operator decision). After four audit rounds the sound form of the rule (main's substring rule, relaxed only for inputs a strict allowlist grammar proves, pinned by TestF2NeverNarrowerThanMain) was measured against 300 recent sessions: owner-only sessions 48 on main vs 48 at 36742c5 (identical set); only 2 tool inputs relaxed to a named scope, both in sessions already * for other inputs. The narrowing is safe but inert, so it is not worth carrying. The branch is kept for reference.

@ZacxDev ZacxDev closed this Nov 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant