From 90fabff749ea5d5398dc2ec68b27d8dae37d3e2c Mon Sep 17 00:00:00 2001 From: Zachary Lowden Date: Thu, 3 Dec 2026 22:52:43 -0600 Subject: [PATCH 1/4] feat(capture): place an unnamed scope owner-only on the default; add --reevaluate-held MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Operator decision 2026-12-03 (changes plan decision 16): a scope the routing table does not name at all is treated like `*` on a multi-instance host — the session ships to the DEFAULT instance owner-only (`*` declared, new cause OwnerOnlyUnnamedScope) instead of being HELD. Holding was final and withdrew an already-shipped prefix, while scopeuse reads header-shaped text anywhere in a transcript as a read, so fixture names in test output froze and withdrew whole sessions (measured: 15 such holds on one host, 14 on fixture names). The only routing hold left is a scope the table EXPLICITLY routes to an instance this host does not configure; its held_reason now says exactly that. `cairn-capture --reevaluate-held [-apply]` recovers the holds the old rule made: it selects legacy "scope X routes to no configured instance" holds, re-decides each over V, and (given -host/-worker/-capture-token-file) probes the destination. -apply refuses to run without probes, clears only holds the destination answered with a position (re-checked at the write), and reports a 410 as needs-server-restore, leaving it held so the next pass neither re-holds nor loops on it. "routed back to …, which deleted" holds are excluded by name. Red/green: the routing tests fail at origin/main 7dc510c (held / withdrawn) and pass here; route.go mutants (main's condition restored, the condition widened, the explicit hold removed, the unnamed owner-only case dropped) each fail named tests. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 1 + claudedocs/plan-cairn-plugins.md | 17 +- cmd/cairn-capture/main.go | 118 +++++++++- cmd/cairn-capture/reeval_test.go | 186 +++++++++++++++ internal/capture/README.md | 47 +++- internal/capture/clearable_test.go | 2 +- internal/capture/reevaluate.go | 196 ++++++++++++++++ internal/capture/route.go | 49 +++- internal/capture/unnamed_test.go | 358 +++++++++++++++++++++++++++++ 9 files changed, 957 insertions(+), 17 deletions(-) create mode 100644 cmd/cairn-capture/reeval_test.go create mode 100644 internal/capture/reevaluate.go create mode 100644 internal/capture/unnamed_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 74b9b98e..cde44207 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,7 @@ claim to cover them; `git log` and the PR history are the record for those. | change | anchor | what you may have to do | why it was taken | |---|---|---|---| +| **`cairn-capture` no longer HOLDS a session for a scope the routing table does not name** (on a host with more than one instance): it ships to the DEFAULT instance OWNER-ONLY (`*` declared), as a `*` session does, and an already-shipped session is no longer withdrawn for it. A scope the table EXPLICITLY routes to an instance this host does not configure is still held — the only routing hold left — and its `held_reason` now says so (`scope X is routed by the table to instance Y, which this host does not configure`). New mode **`--reevaluate-held [-apply]`** recovers the holds the old rule made | [#PRNUM](https://github.com/ZacxDev/cairn/pull/PRNUM) → `` | ⚠ **Sessions previously held stay held** until you run `--reevaluate-held` (read-only listing), then, with `-host`/`-worker`/`-capture-token-file`, `-apply`: it clears only holds whose destination answered the position probe; a 410 is listed `needs-server-restore` and left held — restore it by the server journal. The `routed back to …, which deleted this session's transcript` holds are never touched. ⚠ **If you match `held_reason` text**, the unconfigured-alias hold's wording changed. [`internal/capture/README.md`](internal/capture/README.md) step 3 and § *`--reevaluate-held`* | `scopeuse` reads header-shaped text anywhere in a transcript (test output, a source read, assistant prose) as a scope read, so a fixture name in a grep result held — and withdrew — whole sessions: measured on a two-instance host, 15 held this way, 14 on fixture names. An unnamed scope is a claim about no instance, so there is no leak to stop: [`internal/capture/route.go`](internal/capture/route.go)'s `Decide` | | **`cairn-capture --clear-held` no longer clears a hold whose session was ever bound or WITHDRAWN, nor any empty-`instance` hold in a state written by an earlier agent.** The state keeps a per-session shipping history (`bound_ever`, `withdrawn_from`, `history_kept`); `--list-held` prints a sixth field, why a `permanent` hold is kept, and `--clear-held` prints it per kept hold. EVERY first binding is now position-probed (one request per new session; a 410 there holds the session), a withdrawal is recorded before it is sent, and a 410 on an instance the session was withdrawn from HOLDS it instead of marking it `deleted`. The hold reason is neutral (`410: withdrawn or deleted there`): restore by the server journal's reason. | [#324](https://github.com/ZacxDev/cairn/pull/324) → `` | ⚠ **Existing empty-`instance` holds become `permanent`** (a legacy state cannot prove they never shipped). List them: `cairn-capture --list-held \| awk -F'\t' '$3 == "permanent"'`. ⚠ **If you parse `--list-held`**, one trailing field is added; the first five keep their positions. [`internal/capture/README.md`](internal/capture/README.md) § *`held=` is not the backlog* | DATA LOSS: an empty `instance` was read as "never shipped", but a withdrawal empties it too. `--clear-held` cleared withdrawn sessions, the next pass re-sent them unprobed, the instance answered 410 (a withdrawal is final for its uploader), and each was marked `deleted` for good — measured: 49 sessions on one host | | **`cairn-capture -foreign-root-base BASE -foreign-claude-root [OWNER=]DIR`** (repeatable, `--run`/`--dry-run`; BASE absolute and required, DIR strictly beneath it; Linux only): more Claude Code projects roots whose sessions ran on another filesystem (a container's volume). They ship like `-claude-root`'s, but their recorded `cwd` is never resolved on this host: one that recorded no scope is placed by OWNER as an `origin` owner (`-route-origin-owner`), else the default instance; each is resolved from BASE with no symlink followed in any component (openat2, or an O_NOFOLLOW walk) and held open for the run; an unreadable one is one `refused=`, an absent one is logged; an id already found under an earlier root is skipped. **Every root, `-claude-root` included, now refuses (logs, `refused=`) a session file or project directory that is a symlink, and never reads a file through one** | `` | If you keep session files under `-claude-root` as SYMLINKS, they are no longer captured: `find -type l` first. Otherwise nothing unless you pass the flag | Capturing agents that run in containers from the host, without a client or network path in the container: [`internal/capture/README.md`](internal/capture/README.md) § *A session that recorded no scope* | | **`cairn-capture`: a session already BOUND to an instance is DEFERRED while F1 is live, for at most 1 hour** (on a host with more than one instance): nothing of it is shipped and nothing withdrawn, counted on a NEW run-line field **`deferred=`** (not `refused=`), logged once when the window starts. The window's start is saved per session as `f1_since` in the state and cleared whenever F1 is false; once it expires with F1 still live, the session is routed exactly as before (F1's `*` forces the default instance, with the usual withdrawal), logged once. A NEW session is still placed on the default instance by F1. **`--dry-run` routes F1 as `--run` does**, reading `f1_since` read-only: `decision=deferred` inside the window, the base rule's answer after it | [#317](https://github.com/ZacxDev/cairn/pull/317) → `` | ⚠ **If you parse the run line**, `deferred=` is INSERTED after `export-skipped=`, inside the `cairn-capture: run …` line, so the four fields `--run` prints after the summary — `omitted=`, `recheck-omitted=`, `requests=`, `held-backlog=` — each shift one position right: a parser keyed on field NAMES is unaffected, a POSITIONAL one must update. ⚠ **A bound session's capture can lag by up to an hour** while F1 holds. ⚠ **Two residuals remain**: a session whose F1 stays live past the window is moved by the base rule and can still be held by a later move back (410); and once any ledger record lands, earlier output that had no ledger record of its own ships under that later scope, deferred or not (pre-existing T3). ⚠ **It recovers nothing already held**, and one an older build moved but has not yet held will be held when its ledger line lands — no supported operation un-deletes a root on an instance. [`internal/capture/README.md`](internal/capture/README.md) step 3 and § *A session deleted on its instance (410)* | Claude Code writes a `cairn` call's tool input before the client appends its ledger line, so a pass in between saw F1 and moved a repo-placed session to the default; the next pass's move back answered 410 and held it for good. Bounded because F1's evidence is sticky, so an unbounded deferral stopped some sessions' capture for good: [`internal/capture/f1move_test.go`](internal/capture/f1move_test.go), [`internal/capture/route.go`](internal/capture/route.go)'s `DecideRun` | diff --git a/claudedocs/plan-cairn-plugins.md b/claudedocs/plan-cairn-plugins.md index e3ade1bb..e6a9ddd2 100644 --- a/claudedocs/plan-cairn-plugins.md +++ b/claudedocs/plan-cairn-plugins.md @@ -1429,8 +1429,23 @@ script that prints only counts. wrote `alpha-notes` (personal) and read `beta-notes` (client) in its first turn → held, 0 requests to either; - `V` holds `*` or an unroutable name with more than one instance configured → held; + *🔴 Changed by operator decisions — the code (`internal/capture/route.go`, `Decide`) is the + authority, and this bullet and the two-instance one above are SUPERSEDED: `*` and a session + whose scopes route to two instances are placed on the DEFAULT instance, OWNER-ONLY (`*` + declared), not held; and (**2026-12-03**) so is a scope the routing table does NOT NAME at all. + Reason for the 2026-12-03 change: `scopeuse` reads header-shaped text anywhere in a transcript + (grep and test output, a source read, assistant prose) as a scope read, so a fixture name in a + test's output held a session for good — and holding an already-shipped session WITHDREW it + first. Measured on a two-instance host: 15 sessions held this way, 14 on fixture names + (`alpha-notes`, `a`, `b`, `checkout-service`), one on a real scope registered later, and one + live session withdrawn from the default instance. An unnamed scope is a claim about no + instance, so there is no cross-instance leak to stop — only a reader to narrow, which + owner-only does. Existing holds are recovered by `cairn-capture --reevaluate-held` + (`internal/capture/README.md`).* - a scope the routing table EXPLICITLY sends to an alias this host has no config for → held, at - any instance count: the table says the scope lives elsewhere (S2 review round 1); + any instance count: the table says the scope lives elsewhere (S2 review round 1). *Since + 2026-12-03 this is the ONLY routing hold left; its reason reads `scope X is routed by the table + to instance Y, which this host does not configure`.* - `V` empty (O10) → the DEFAULT instance, where decision 4 makes it owner-only. - 🔴 **Capture is incremental (60 s), so a prefix may ALREADY be on an instance when the rule changes its answer.** When a run computes an answer other than the instance holding the diff --git a/cmd/cairn-capture/main.go b/cmd/cairn-capture/main.go index d6469cd6..f73c9bb2 100644 --- a/cmd/cairn-capture/main.go +++ b/cmd/cairn-capture/main.go @@ -31,6 +31,12 @@ // [-host-key FILE] [-allow-plaintext-host [ALIAS=]HOST]... [the --dry-run reading flags] // cairn-capture --list-held [-state FILE] // cairn-capture --clear-held [-state FILE] +// cairn-capture --reevaluate-held [-state FILE] [-claude-root DIR] [-host LABEL -worker [ALIAS=]URL -capture-token-file [ALIAS=]FILE]... [-apply] +// +// `--reevaluate-held` is the one-off recovery of the holds the pre-2026-12-03 rule made for a scope +// the routing table does not name (`capture.Agent.ReevaluateHeld`): read-only unless `-apply`, and +// `-apply` clears only a hold whose destination answered the position probe — a 410 is reported +// `needs-server-restore` and left held. // // 🔴 `held` IS FINAL, SO `--list-held` AND `--clear-held` EXIST: the run line's `held=` counts the // holds ONE PASS MADE, and a held session is skipped before routing on every later pass, so a @@ -129,6 +135,11 @@ func run(args []string, stdout, stderr io.Writer, getenv func(string) string) in "owner were OWNER (-route-origin-owner), else on the default instance. No file beneath it is read through a "+ "symlink, and a root whose own path runs through one is refused; an unreadable root refuses only itself, an "+ "absent one is logged (repeatable; no default)") + reeval := fs.Bool("reevaluate-held", false, "list the holds the pre-2026-12-03 rule made for a scope the routing table "+ + "does not name, re-decided under the current rule (and, given -host/-worker/-capture-token-file, probed at their "+ + "destination); writes nothing without -apply") + apply := fs.Bool("apply", false, "--reevaluate-held only: clear the holds whose destination answered the probe with a "+ + "position (needs -host, -worker and -capture-token-file; under the run lock)") fs.Var(&ocDirs, "opencode-project", "an opencode project directory to enumerate (repeatable; `session list` lists ONE project's roots)") fs.Var(&workers, "worker", "--run: [ALIAS=]URL of an instance's worker listener (repeatable; no alias is the default instance)") fs.Var(&tokenFiles, "capture-token-file", "--run: [ALIAS=]FILE holding that instance's capture token, mode 0600 (repeatable)") @@ -149,14 +160,17 @@ func run(args []string, stdout, stderr io.Writer, getenv func(string) string) in return exitUsage } modes := 0 - for _, on := range []bool{*selfTest, *dryRun, *runOnce, *listHeld, *clearHeld} { + for _, on := range []bool{*selfTest, *dryRun, *runOnce, *listHeld, *clearHeld, *reeval} { if on { modes++ } } switch { case modes != 1: - fmt.Fprintln(stderr, "cairn-capture: name exactly one of --run, --dry-run, --list-held, --clear-held or --self-test") + fmt.Fprintln(stderr, "cairn-capture: name exactly one of --run, --dry-run, --list-held, --clear-held, --reevaluate-held or --self-test") + return exitUsage + case *apply && !*reeval: + fmt.Fprintln(stderr, "cairn-capture: -apply is for --reevaluate-held only") return exitUsage case *selfTest: return redact.SelfTest(stdout, *seed) @@ -180,6 +194,10 @@ func run(args []string, stdout, stderr io.Writer, getenv func(string) string) in if *clearHeld { return clearHeldSessions(*statePath, stateHome, stdout, stderr) } + if *reeval { + return reevaluateHeld(runConfig{host: *host, state: *statePath, maxRequest: *maxRequest, workers: workers, + tokenFiles: tokenFiles, plaintext: plaintext, stateHome: stateHome, claudeRoot: *claudeRoot}, *apply, stdout, stderr, getenv) + } // 🔴 --dry-run WRITES NOTHING, THE HOST KEY INCLUDED. It prints counts by rule, never a tag, so // an ephemeral in-memory key is all it needs; creating the persistent key file as a side effect // of a read-only mode was a review finding (round 1). @@ -556,6 +574,102 @@ func clearHeldSessions(path, stateHome string, stdout, stderr io.Writer) int { return exitOK } +// reevaluateHeld is `--reevaluate-held`: one line per held session, tab-separated +// ` `, +// then the counts on stderr. Without `-apply` it writes NOTHING — the state is opened read-only, no +// lock is taken — and probes only when given `-worker`s (a probe stores nothing on the instance). +// +// 🔴 `-apply` PROBES EVERY CANDIDATE FIRST, AND REFUSES TO RUN WITHOUT THE ENDPOINTS TO DO SO. Every +// hold this mode exists for was legacy — no record of whether it was withdrawn — so the state cannot +// prove a clear safe; only the destination's answer can. A 410 is NOT cleared: cleared, the next pass +// would probe, be answered 410 and hold it again, silently, as `410: withdrawn or deleted there`. +func reevaluateHeld(c runConfig, apply bool, stdout, stderr io.Writer, getenv func(string) string) int { + routing, err := client.Discover(getenv) + if err != nil { + fmt.Fprintf(stderr, "cairn-capture: %v\n", err) + return exitError + } + p := captureStatePath(c.state, c.stateHome) + var sink capture.Sink + var up map[string]bool + if len(c.workers) > 0 || len(c.tokenFiles) > 0 { + if c.host == "" || strings.ContainsAny(c.host, " \t\r\n/") { + fmt.Fprintln(stderr, "cairn-capture: probing needs -host, the label this host's capture token was minted for") + return exitUsage + } + eps, _, _, err := endpoints(c, routing) + if err != nil { + fmt.Fprintf(stderr, "cairn-capture: %v\n", err) + return exitUsage + } + sink, up = &capture.HTTPSink{Host: c.host, Endpoints: eps, MaxRequest: c.maxRequest, Log: stderr}, uploadable(eps) + } + if apply && sink == nil { + fmt.Fprintln(stderr, "cairn-capture: --reevaluate-held -apply needs -host, -worker and -capture-token-file: "+ + "no hold is cleared without its destination's answer (a legacy hold may have been withdrawn there)") + return exitUsage + } + if apply { + release, err := capture.LockState(p) + if errors.Is(err, capture.ErrRunning) { + fmt.Fprintln(stderr, "cairn-capture: another run holds the lock; nothing cleared") + return exitError + } + if err != nil { + fmt.Fprintf(stderr, "cairn-capture: %v\n", err) + return exitError + } + defer release() + } + state, err := capture.LoadState(p) + if err != nil { + fmt.Fprintf(stderr, "cairn-capture: %v\n", err) + return exitError + } + agent := &capture.Agent{State: state, ClaudeRoot: c.claudeRoot, Routing: routing, Uploadable: up, Sink: sink, Log: stderr} + rs := agent.ReevaluateHeld() + counts := map[string]int{} + for _, r := range rs { + counts[r.Outcome]++ + hist, target, owner, size := "legacy", "-", "-", "-" + if r.HistoryKept { + hist = "history-kept" + } + if r.Target != "" { + target = r.Target + } + if r.OwnerOnly { + owner = "owner-only" + } + if r.Bytes >= 0 { + size = fmt.Sprint(r.Bytes) + } + fmt.Fprintf(stdout, "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n", r.Outcome, r.Root, r.Runtime, hist, target, owner, size, r.Reason, r.Detail) + } + line := fmt.Sprintf("held=%d", len(rs)) + for _, o := range []string{capture.ReevalShip, capture.ReevalUnprobed, capture.ReevalNeedsRestore, capture.ReevalProbeFailed, + capture.ReevalStillHeld, capture.ReevalExcluded} { + line += fmt.Sprintf(" %s=%d", o, counts[o]) + } + if !apply { + fmt.Fprintf(stderr, "cairn-capture: %s — dry run: nothing was changed (-apply clears the `ship` ones)\n", line) + return exitOK + } + cleared := state.ApplyReevaluation(rs) + if len(cleared) > 0 { + if err := state.Save(p); err != nil { + fmt.Fprintf(stderr, "cairn-capture: %v\n", err) + return exitError + } + } + for _, r := range cleared { + fmt.Fprintf(stdout, "cleared\t%s\t%s\t%s\n", r.Root, r.Runtime, r.Target) + } + fmt.Fprintf(stderr, "cairn-capture: %s cleared=%d — the next pass reads the cleared sessions again; "+ + "a needs-server-restore one is left held\n", line, len(cleared)) + return exitOK +} + // runPass is `--run` itself: one pass, under the run lock, saving as it goes. func runPass(c runConfig, stderr io.Writer, getenv func(string) string) int { fail := func(err error) int { diff --git a/cmd/cairn-capture/reeval_test.go b/cmd/cairn-capture/reeval_test.go new file mode 100644 index 00000000..38d88846 --- /dev/null +++ b/cmd/cairn-capture/reeval_test.go @@ -0,0 +1,186 @@ +package main + +// `--reevaluate-held`, end to end through run() against real in-process worker pods: the one-off +// recovery of the holds the pre-2026-12-03 rule made for a scope the routing table does not name. + +import ( + "bytes" + "crypto/sha256" + "os" + "path/filepath" + "slices" + "strconv" + "strings" + "testing" + + "github.com/ZacxDev/cairn/internal/capture" +) + +const legacyGammaHold = "scope gamma-notes routes to no configured instance" + +// legacyHeldWorld is a two-instance world (personal, client; the table names only alpha-notes) whose +// one session s-0001 the state records as the OLD rule left it: held for the unnamed `gamma-notes`, a +// legacy history (no history_kept), unbound, nothing shipped — plus an operator-frozen +// "routed back to …, which deleted" hold that must never be touched. +func legacyHeldWorld(t *testing.T) repoWorld { + t.Helper() + w := repoRoutedWorld(t, `{"alpha-notes":"personal"}`) + if err := os.MkdirAll(filepath.Dir(w.statePath()), 0o700); err != nil { + t.Fatal(err) + } + state := `{"schema":1,"sessions":{` + + `"s-0001":{"runtime":"claude","held":true,"held_reason":"` + legacyGammaHold + `","v":["gamma-notes"],"declared":["gamma-notes"],"evidence":{}},` + + `"s-frozen":{"runtime":"claude","held":true,"instance":"personal","held_reason":"routed back to client, which deleted this session's transcript: kept on personal","v":["gamma-notes"],"evidence":{}}}}` + if err := os.WriteFile(w.statePath(), []byte(state), 0o600); err != nil { + t.Fatal(err) + } + return w +} + +func stateSum(t *testing.T, w repoWorld) [32]byte { + t.Helper() + raw, err := os.ReadFile(w.statePath()) + if err != nil { + t.Fatal(err) + } + return sha256.Sum256(raw) +} + +func reevalRun(t *testing.T, w repoWorld, args ...string) (int, string, string) { + t.Helper() + var out, errb bytes.Buffer + code := run(append([]string{"--reevaluate-held"}, args...), &out, &errb, w.env) + return code, out.String(), errb.String() +} + +func lineFor(out, root string) string { + for _, l := range strings.Split(out, "\n") { + if f := strings.Split(l, "\t"); len(f) > 1 && f[1] == root { + return l + } + } + return "" +} + +// TestReevaluateHeldDryRunListsAndWritesNothing: no -worker, no -apply — a listing, with the session +// id, runtime, history, destination, owner-only and bytes on disk, and a byte-identical state. +func TestReevaluateHeldDryRunListsAndWritesNothing(t *testing.T) { + w := legacyHeldWorld(t) + before := stateSum(t, w) + code, out, errb := reevalRun(t, w) + if code != exitOK { + t.Fatalf("exit %d\n%s", code, errb) + } + info, err := os.Stat(w.session()) + if err != nil { + t.Fatal(err) + } + want := "unprobed\ts-0001\tclaude\tlegacy\tpersonal\towner-only\t" + itoa(info.Size()) + "\t" + legacyGammaHold + "\t" + if l := lineFor(out, "s-0001"); !strings.HasPrefix(l, want) { + t.Fatalf("s-0001's line is\n%q\nwant prefix\n%q", l, want) + } + if l := lineFor(out, "s-frozen"); !strings.HasPrefix(l, "excluded\ts-frozen\t") || !strings.Contains(l, "frozen by operator decision") { + t.Fatalf("the frozen hold's line is %q", l) + } + if !strings.Contains(errb, "held=2 ship=0 unprobed=1 needs-server-restore=0 probe-failed=0 still-held=0 excluded=1 — dry run") { + t.Fatalf("summary:\n%s", errb) + } + if stateSum(t, w) != before { + t.Fatal("a dry run changed the state file") + } + if _, err := os.Stat(w.statePath() + ".lock"); err == nil { + t.Fatal("a dry run created the run lock") + } +} + +// TestReevaluateHeldApplyRefusesWithoutAProbe: every hold it exists for is legacy, so nothing is +// cleared without the destination's answer. +func TestReevaluateHeldApplyRefusesWithoutAProbe(t *testing.T) { + w := legacyHeldWorld(t) + before := stateSum(t, w) + if code, _, errb := reevalRun(t, w, "-apply"); code != exitUsage || !strings.Contains(errb, "needs -host, -worker and -capture-token-file") { + t.Fatalf("exit %d\n%s", code, errb) + } + var errb bytes.Buffer + if code := run([]string{"--list-held", "-apply"}, &bytes.Buffer{}, &errb, w.env); code != exitUsage { + t.Fatalf("-apply outside --reevaluate-held: exit %d", code) + } + if stateSum(t, w) != before { + t.Fatal("a refused apply changed the state") + } +} + +// TestReevaluateHeldApplyClearsAndTheNextPassShipsOwnerOnly: the destination answers the probe, the +// hold is cleared, the frozen one is not, and the next --run ships s-0001 to personal with `*`. +func TestReevaluateHeldApplyClearsAndTheNextPassShipsOwnerOnly(t *testing.T) { + personal, other := newRunPod(t, true), newRunPod(t, true) + w := legacyHeldWorld(t) + workers := []string{"-host", "host-a", "-worker", personal.url, "-capture-token-file", w.tokenFile, + "-worker", "client=" + other.url, "-capture-token-file", "client=" + w.tokenFile} + code, out, errb := reevalRun(t, w, append(workers, "-apply")...) + if code != exitOK || !strings.HasPrefix(lineFor(out, "s-0001"), "ship\ts-0001\t") || + !strings.Contains(out, "cleared\ts-0001\tclaude\tpersonal\n") || strings.Contains(out, "cleared\ts-frozen") { + t.Fatalf("exit %d\n%s\n%s", code, out, errb) + } + if m, _ := personal.arc.ReadMeta("s-0001"); m != nil { + t.Fatal("the re-evaluation itself stored the session; only the next pass may") + } + st := readState(t, w) + if frozen := st["sessions"].(map[string]any)["s-frozen"].(map[string]any); frozen["held"] != true { + t.Fatal("the operator-frozen hold was cleared") + } + mustRunPass(t, w, append([]string{"--run"}, workers...)) + ss := sessionOf(t, readState(t, w)) + if ss["held"] == true || ss["instance"] != "personal" { + t.Fatalf("after the pass: %v", ss) + } + m, err := personal.arc.ReadMeta("s-0001") + if err != nil || m == nil || !slices.Contains(m.Declared, "*") { + t.Fatalf("personal holds %+v (%v) — want s-0001 declared owner-only", m, err) + } +} + +// TestReevaluateHeldReportsAWithdrawnSessionAsNeedsRestore is 69d10fb7's shape: shipped to personal +// by an older binary, WITHDRAWN there (a final deletion for this uploader), then held with a legacy +// state that recorded no withdrawal. The probe answers 410: it is reported, NOT cleared — and the next +// pass neither re-holds it under a new reason nor sends anything. +func TestReevaluateHeldReportsAWithdrawnSessionAsNeedsRestore(t *testing.T) { + personal, other := newRunPod(t, true), newRunPod(t, true) + w := legacyHeldWorld(t) + workers := []string{"-host", "host-a", "-worker", personal.url, "-capture-token-file", w.tokenFile, + "-worker", "client=" + other.url, "-capture-token-file", "client=" + w.tokenFile} + tok, err := capture.ReadTokenFile(w.tokenFile) + if err != nil { + t.Fatal(err) + } + sink := &capture.HTTPSink{Host: "host-a", MaxRequest: capture.DefaultMaxRequest, + Endpoints: map[string]capture.Endpoint{"personal": {URL: personal.url, Token: tok}}} + // Land something of s-0001 on personal, then withdraw it — as the older binary did. + if _, err := sink.Records(capture.Upload{Instance: "personal", Root: "s-0001", Runtime: "claude", Declared: []string{"gamma-notes"}}, + "main", []capture.Record{{Src: "0", Rec: []byte(w.line(0)[:len(w.line(0))-1]), End: itoa(int64(len(w.line(0))))}}); err != nil { + t.Fatalf("CONTROL: the prefix did not land: %v", err) + } + if deleted, err := sink.Withdraw("personal", "s-0001"); err != nil || !deleted { + t.Fatalf("CONTROL: the withdrawal: deleted=%v %v", deleted, err) + } + before := stateSum(t, w) + code, out, errb := reevalRun(t, w, append(workers, "-apply")...) + if code != exitOK || !strings.HasPrefix(lineFor(out, "s-0001"), "needs-server-restore\ts-0001\tclaude\tlegacy\tpersonal\t") || + strings.Contains(out, "cleared\t") || !strings.Contains(errb, "needs-server-restore=1") { + t.Fatalf("exit %d\n%s\n%s", code, out, errb) + } + if stateSum(t, w) != before { + t.Fatal("a needs-restore hold changed the state") + } + before = stateSum(t, w) + log := mustRunPass(t, w, append([]string{"--run"}, workers...)) + ss := sessionOf(t, readState(t, w)) + if ss["held"] != true || ss["held_reason"] != legacyGammaHold || ss["deleted"] != nil { + t.Fatalf("after a pass: %v\n%s", ss, log) + } + if stateSum(t, w) != before { + t.Fatalf("the pass touched the held session's state\n%s", log) + } +} + +func itoa(n int64) string { return strconv.FormatInt(n, 10) } diff --git a/internal/capture/README.md b/internal/capture/README.md index ee65c596..05c34627 100644 --- a/internal/capture/README.md +++ b/internal/capture/README.md @@ -40,10 +40,17 @@ operator's act. session carries when its evidence says a tool input names the program (#312 — so the pod has it even when the stream holding that tool input failed to upload). A session whose scopes name TWO instances is placed on the default instance OWNER-ONLY for the same reason — the trade the operator accepted on - and the reason a cross-instance session is no longer held. A scope the routing table - explicitly sends to an unconfigured alias is still HELD at any instance count: the table says it - lives on an instance this host does not run, and shipping its records to the one it does is the - cross-instance leak decision 16 exists to stop. A session + and the reason a cross-instance session is no longer held. 🔴 **A scope the routing table does + NOT NAME at all is placed exactly like `*`** (operator decision 2026-12-03, `OwnerOnlyUnnamedScope`): + on a host with more than one instance the session goes to the DEFAULT instance, OWNER-ONLY, with + `*` declared — it is not held, and an already-shipped session is not withdrawn for it. It used to + HOLD the session, and `scopeuse` takes header-shaped text anywhere in a transcript (test output, + a source read, assistant prose) as a read, so a fixture name froze and withdrew whole sessions. + (With one instance an unnamed scope routes to the sole instance, as before.) A scope the routing + table EXPLICITLY sends to an unconfigured alias is still HELD at any instance count — the ONLY + routing hold left, reason `scope X is routed by the table to instance Y, which this host does not + configure`: the table says it lives on an instance this host does not run, and shipping its + records to the one it does is the cross-instance leak decision 16 exists to stop. A session whose `V` is **empty** is placed by the repository it ran in — § *A session that recorded no scope* below. @@ -504,6 +511,38 @@ A routing-only hold this agent recorded (never bound, never withdrawn) is cleare next pass reads the session and routes it under whatever the rules now say. 🔴 **A RULE CHANGE ALONE RECOVERS NOTHING**: `held` is final, so fixing a routing rule that held sessions leaves every one of them held until an operator clears it (`--clear-held`). +## `--reevaluate-held`: recovering the holds the old unnamed-scope rule made + +Before 2026-12-03 a scope the routing table does not name HELD the session on a multi-instance host, +with the reason `scope X routes to no configured instance` (the same text then also covered a scope +the table routes to an unconfigured alias). The rule change recovers none of them — `held` is final — +and `--clear-held` cannot either: such holds are LEGACY (`history_kept` false), and a legacy hold may +have been WITHDRAWN without a record. `--reevaluate-held` is the one-off path: + +```sh +cairn-capture --reevaluate-held # read-only: no lock, no write, no probe +cairn-capture --reevaluate-held -host H -worker URL -capture-token-file F [-worker client=URL …] # + probes (store nothing) +cairn-capture --reevaluate-held -host H -worker … -capture-token-file … -apply # clears the `ship` ones, under the run lock +``` + +One tab-separated line per held session: ` + `, then the counts on stderr. It selects +holds with the OLD text, re-decides each over its `V` under the CURRENT rule, and — given workers — +sends the destination the same position probe every first binding gets: + +| outcome | meaning | `-apply` | +|---|---|---| +| `ship` | the current rule places it, the destination answered with a position | clears `held`/`held_reason` (re-checked at the write); the next pass binds (probing again) and ships it owner-only | +| `unprobed` | placeable, no `-worker` given | — (`-apply` refuses to run without workers) | +| `needs-server-restore` | the destination answered **410**: it holds a final deletion of this root | **left held, untouched** — cleared, the next pass would probe, get 410 and re-hold it as `410: withdrawn or deleted there`. Restore by the section below, going by the SERVER journal's `reason` | +| `probe-failed` | no usable answer | left; ask again | +| `still-held` | a scope in `V` the table routes to an unconfigured alias | left | +| `excluded` | any other hold — 🔴 including, explicitly, the operator-frozen `routed back to , which deleted this session's transcript` holds | never touched | + +`bytes` is the size of a Claude Code session's files under `-claude-root` (`-` for opencode, whose +transcript lives in opencode's database). `history-kept|legacy` is `history_kept`; for a legacy hold +an empty `withdrawn_from` proves nothing — which is why the probe, not the state, decides. + ## Restoring sessions a capture bug deleted When the server's deletion journal shows a root deleted with `reason: withdrawn` by THIS host's diff --git a/internal/capture/clearable_test.go b/internal/capture/clearable_test.go index 03b50178..7a40debd 100644 --- a/internal/capture/clearable_test.go +++ b/internal/capture/clearable_test.go @@ -19,7 +19,7 @@ import ( // `gamma-notes` the table first routes to an instance this host does not configure. // gammaRoutes is twoInstances plus `gamma-notes` → `gamma`, an alias no instance carries: a session -// that reads it is HELD ("routes to no configured instance"). +// that reads it is HELD ("is routed by the table to instance gamma, which this host does not configure"). var gammaRoutes = client.Routing{ Instances: twoInstances.Instances, Routes: map[string]string{"alpha-notes": "personal", "beta-notes": "client", "gamma-notes": "gamma"}, diff --git a/internal/capture/reevaluate.go b/internal/capture/reevaluate.go new file mode 100644 index 00000000..591870d1 --- /dev/null +++ b/internal/capture/reevaluate.go @@ -0,0 +1,196 @@ +package capture + +import ( + "errors" + "slices" + "sort" + "strings" +) + +// The one-off re-evaluation of EXISTING holds after the 2026-12-03 operator decision ([Decide]): a +// scope the routing table does not name is placed like `*` now, but `held` is FINAL in the state, so +// the sessions the old rule held stay held until an operator clears them. `--clear-held` cannot: every +// such hold on the measured host was LEGACY ([SessionState.HistoryKept] false), and a legacy hold is +// never clearable, because nothing in a legacy state proves the session was not WITHDRAWN — and a +// withdrawn session re-sent to the instance it was withdrawn from is refused 410 for good. +// +// So this mode does not decide from the state alone. It selects the holds the OLD rule made for an +// unnamed scope, re-decides each under the CURRENT rule, and asks the destination — the same position +// probe every first binding is sent, which stores nothing — whether it would take the session: +// +// - a position: the destination has no deletion of this root, so clearing the hold is safe; the +// next pass binds it (probing again) and ships it. +// - 410: the destination holds a FINAL deletion of it — this agent's own earlier withdrawal, an +// owner delete or retention, which only the SERVER's journal can tell apart. It is NOT cleared: +// cleared, the next pass's first-binding probe would answer 410 and hold it again, silently. It is +// reported `needs-server-restore` (internal/capture/README.md § *Restoring sessions a capture bug +// deleted*). +// - no answer: not cleared, reported, asked again on the next invocation. +// +// 🔴 THE `routed back to …, which deleted this session's transcript` HOLDS ARE EXCLUDED BY NAME +// (operator decision: those stay frozen), before anything else is looked at — even though their reason +// would never match the unnamed-scope text, the exclusion is stated, not incidental. + +// Reevaluation outcomes. +const ( + // ReevalShip: the current rule places it, and the destination answered the probe with a position + // — an apply clears the hold. + ReevalShip = "ship" + // ReevalUnprobed: the current rule places it, and no probe was made (no sink: a dry run given no + // `-worker`). An apply always probes first. + ReevalUnprobed = "unprobed" + // ReevalNeedsRestore: the destination answered 410. Never cleared here. + ReevalNeedsRestore = "needs-server-restore" + // ReevalProbeFailed: the destination gave no usable answer. Not cleared; ask again. + ReevalProbeFailed = "probe-failed" + // ReevalStillHeld: the current rule still holds it (a scope in V the table routes to an + // instance this host does not configure). + ReevalStillHeld = "still-held" + // ReevalExcluded: not an unnamed-scope routing hold, or one this mode must not touch. + ReevalExcluded = "excluded" +) + +// Reevaluation is one held session as the re-evaluation sees it: no transcript content. +type Reevaluation struct { + HeldEntry + // Outcome is one of the Reeval* constants; Detail says why. + Outcome, Detail string + // Target is the instance the current rule ships it to ("" when it does not), OwnerOnly whether + // it would be owner-only there. + Target string + OwnerOnly bool + // Bytes is the size of the session's transcript files under the Claude Code root, -1 when + // unknown (an opencode session, whose transcript lives in opencode's database, or a Claude Code + // one not found under the root). + Bytes int64 +} + +// legacyUnnamedHold reports whether `reason` is the hold text the PRE-2026-12-03 rule wrote for a +// scope it could not route: "scope X routes to no configured instance". That text was written for an +// UNNAMED scope on a multi-instance host AND for a scope named for an unconfigured alias, so matching +// it only SELECTS a candidate — [Decide] over the session's V says which it was. +func legacyUnnamedHold(reason string) bool { + return strings.HasPrefix(reason, "scope ") && strings.HasSuffix(reason, " routes to no configured instance") +} + +// frozenDeletedHold reports a hold the operator froze: the session was routed back to an instance +// that deleted its transcript ([Agent.route]'s probe on a move). +func frozenDeletedHold(reason string) bool { + return strings.HasPrefix(reason, "routed back to ") && strings.Contains(reason, "which deleted this session's transcript") +} + +// ReevaluateHeld classifies every held session (sorted by root). It probes the destination of each +// candidate through [Agent.Sink] when one is set and [Agent.Uploadable] admits the destination; with +// no Sink it probes nothing. It WRITES NOTHING: neither the state nor the instance (a probe stores +// nothing). +func (a *Agent) ReevaluateHeld() []Reevaluation { + held := a.State.Held() + bytesByRoot := a.claudeBytes() + out := make([]Reevaluation, 0, len(held)) + for _, e := range held { + r := Reevaluation{HeldEntry: e, Bytes: -1} + if n, ok := bytesByRoot[e.Root]; ok { + r.Bytes = n + } + ss := a.State.Sessions[e.Root] + switch { + case frozenDeletedHold(e.Reason): + r.Outcome, r.Detail = ReevalExcluded, "frozen by operator decision: routed back to an instance that deleted it" + case !legacyUnnamedHold(e.Reason): + r.Outcome, r.Detail = ReevalExcluded, "not an unnamed-scope routing hold" + case e.Deleted != "": + r.Outcome, r.Detail = ReevalExcluded, "instance "+e.Deleted+" answered that its transcript was deleted there" + case e.Instance != "": + r.Outcome, r.Detail = ReevalExcluded, "its prefix is bound to instance "+e.Instance + default: + a.reevaluate(&r, ss) + } + out = append(out, r) + } + sort.Slice(out, func(i, j int) bool { return out[i].Root < out[j].Root }) + return out +} + +func (a *Agent) reevaluate(r *Reevaluation, ss *SessionState) { + // Not bound (checked by the caller), and f1 false: F1 defers only a BOUND session, and its `*` is + // a fact about a run this mode is not. + dec := Decide(ss.V, Repo{}, a.Routing, RepoRules{Uploadable: a.Uploadable}) + switch { + case dec.Held: + r.Outcome, r.Detail = ReevalStillHeld, dec.Reason + return + case dec.Deferred || dec.Instance == "": + r.Outcome, r.Detail = ReevalStillHeld, "the current rule places it nowhere this run: "+dec.Reason + return + } + r.Target, r.OwnerOnly = dec.Instance, dec.OwnerOnly + hint := "" + switch { + case slices.Contains(r.WithdrawnFrom, dec.Instance): + hint = "; the state records a withdrawal from " + dec.Instance + ", so expect 410" + case !r.HistoryKept: + hint = "; legacy state: a withdrawal may be unrecorded" + } + if a.Sink == nil || !a.uploadable(dec.Instance) { + r.Outcome, r.Detail = ReevalUnprobed, dec.Reason+" (destination not probed"+hint+")" + return + } + _, err := a.Sink.Position(Upload{Instance: dec.Instance, Root: r.Root, Runtime: probeRuntime(ss), Declared: ss.Declared}, "main") + switch { + case errors.Is(err, ErrDeleted): + r.Outcome, r.Detail = ReevalNeedsRestore, "instance "+dec.Instance+" answered 410 (withdrawn or deleted there): "+ + "the server's deletion journal decides whether it may be restored; not cleared" + case err != nil: + r.Outcome, r.Detail = ReevalProbeFailed, "instance "+dec.Instance+" could not be asked: "+err.Error() + default: + r.Outcome, r.Detail = ReevalShip, dec.Reason + } +} + +func (a *Agent) uploadable(alias string) bool { return a.Uploadable == nil || a.Uploadable[alias] } + +// ApplyReevaluation clears the hold of every [ReevalShip] entry in `rs` whose state is STILL the hold +// that was evaluated (held, same reason, unbound, not deleted) — re-read here, at the moment of the +// write, not trusted from the evaluation. Only `held` and `held_reason` move, as [State.ClearHeld]'s. +// It does not save: the caller does, under the run lock. +func (s *State) ApplyReevaluation(rs []Reevaluation) (cleared []Reevaluation) { + for _, r := range rs { + if r.Outcome != ReevalShip { + continue + } + ss := s.Sessions[r.Root] + if ss == nil || !ss.Held || ss.HeldReason != r.Reason || ss.Instance != "" || ss.Deleted != "" || + !legacyUnnamedHold(ss.HeldReason) { + continue + } + ss.Held, ss.HeldReason = false, "" + cleared = append(cleared, r) + } + return cleared +} + +// claudeBytes is the size on disk of every Claude Code session under [Agent.ClaudeRoot] — its main +// JSONL, subagent streams and blobs — by root. Read-only; a root it cannot read answers nothing. +func (a *Agent) claudeBytes() map[string]int64 { + out := map[string]int64{} + sessions, _, closeAll, err := a.claudeSessions() + defer closeAll() + if err != nil { + return out + } + for _, cs := range sessions { + var n int64 + for _, p := range cs.Streams { + if info, err := statIn(cs.In, p); err == nil { + n += info.Size() + } + } + for _, p := range cs.Blobs { + if info, err := statIn(cs.In, p); err == nil { + n += info.Size() + } + } + out[cs.Root] = n + } + return out +} diff --git a/internal/capture/route.go b/internal/capture/route.go index 78b3153d..4b4880f5 100644 --- a/internal/capture/route.go +++ b/internal/capture/route.go @@ -53,6 +53,11 @@ const ( // it is the only thing keeping the other instance's bytes from a reader who could not see them // there. OwnerOnlyCrossInstance + // OwnerOnlyUnnamedScope: a recorded scope the routing table does not name at all, on a host with + // more than one instance (operator decision 2026-12-03). Declared, exactly as `*` is: the scope + // says nothing about where the session belongs, so it is placed on the default instance and + // nobody but the owner may read it there. + OwnerOnlyUnnamedScope ) // DeclaresStar is whether this decision's owner-only statement must be written into the session's @@ -70,9 +75,13 @@ func (d Decision) DeclaresStar() bool { // - `*` with MORE than one instance configured → the DEFAULT instance, OWNER-ONLY (OwnerOnly). // `*` forces the default however V is ordered, and however few other scopes it carries: it is // the conservative direction, and an order-dependent answer is not a policy. -// - a scope the routing names but this host does not configure → HELD (unchanged): the table says -// that scope lives on ANOTHER instance, and shipping its records to the one this host runs is -// the cross-instance leak decision 16 exists to stop. +// - a scope the routing table does NOT NAME, with more than one instance configured → the DEFAULT +// instance, OWNER-ONLY, exactly as `*` (operator decision 2026-12-03; it used to HOLD). With one +// instance such a scope routes to the sole instance and is not owner-only, as before. +// - a scope the routing table NAMES for an alias this host does not configure → HELD, at any +// instance count: the table says that scope lives on ANOTHER instance, and shipping its records +// to the one this host runs is the cross-instance leak decision 16 exists to stop. This is the +// ONLY routing hold left. // // 🔴 `*` IS A VISIBILITY STATEMENT, NOT AN UNPLACEABLE SCOPE — and it used to HOLD the session for // good, which was measured to be the largest capture gap on a two-instance host: the client records @@ -187,7 +196,7 @@ func decideRun(v []string, f1 bool, repo Repo, routing client.Routing, rules Rep } multi := routing.MultiInstance() target := "" - recordedStar, cross, crossWhy := false, false, "" + recordedStar, cross, crossWhy, unnamed := false, false, "", "" for _, scope := range v { if scope == scopeuse.Star { recordedStar = true @@ -200,11 +209,24 @@ func decideRun(v []string, f1 bool, repo Repo, routing client.Routing, rules Rep // table says NOTHING about; a table naming an alias this host has no config for is a // statement that the scope lives on ANOTHER instance, and shipping it to the sole one // is the cross-instance leak decision 16 exists to stop (review round 1). Unchanged by - // the owner-only decision above: THAT one places a session whose scopes this host DOES - // serve, and says so with `*`; this one would move records to an instance the table - // says nothing about. - if _, named := routing.Routes[scope]; multi || named { - return Decision{Held: true, Reason: "scope " + scope + " routes to no configured instance"} + // the owner-only decisions above and below: THEY place a session on an instance this + // host DOES run, and say so with `*`; this one would move records the table says live + // elsewhere onto it. + if to, named := routing.Routes[scope]; named { + return Decision{Held: true, Reason: UnconfiguredHoldReason(scope, to)} + } + // 🔴 A SCOPE THE TABLE DOES NOT NAME AT ALL IS TREATED LIKE `*` (operator decision, + // 2026-12-03): it forces the DEFAULT instance, owner-only. It used to HOLD the session on a + // multi-instance host, and a hold is final and withdraws an already-shipped prefix — while + // the scope reader (`scopeuse`) takes header-shaped text in ANY transcript (test output, a + // source read, assistant prose) as a read, so one fixture name in a grep result froze and + // withdrew a whole session (measured: 14 of 15 such holds on one host were fixture names). + // An unnamed scope says nothing about where the session belongs; the table never claimed it + // for another instance, so there is no leak to stop — only a reader to narrow, which is + // what owner-only does. Only a host with more than one instance reaches here: on one, + // `AliasFor` answers the sole instance for an unnamed scope. + if unnamed == "" { + unnamed = scope } continue } @@ -227,6 +249,9 @@ func decideRun(v []string, f1 bool, repo Repo, routing client.Routing, rules Rep // (`{*, beta-notes}` → personal, `{beta-notes, *}` → client), and the conservative direction // is the one that keeps content that may belong to either instance off the non-default one. why, by = "an unknown scope (*)", OwnerOnlyStar + case unnamed != "": + // `multi` holds: see the branch above. Placed exactly as `*` is, for the same reason. + why, by = "scope "+unnamed+" is not in the routing table (treated as *)", OwnerOnlyUnnamedScope case multi && f1: why, by = "its inputs name the program and its read ledger is empty (F1's *, not declared)", OwnerOnlyUnledgered } @@ -331,3 +356,9 @@ func decideByRepo(repo Repo, routing client.Routing, rules RepoRules) Decision { } return Decision{Instance: client.DefaultAlias, Reason: "no recorded scope: the default instance, owner-only"} } + +// UnconfiguredHoldReason is the hold reason for the one routing hold left ([Decide]): the table NAMES +// `scope` for `alias`, which this host does not configure. +func UnconfiguredHoldReason(scope, alias string) string { + return "scope " + scope + " is routed by the table to instance " + alias + ", which this host does not configure" +} diff --git a/internal/capture/unnamed_test.go b/internal/capture/unnamed_test.go new file mode 100644 index 00000000..df23c7db --- /dev/null +++ b/internal/capture/unnamed_test.go @@ -0,0 +1,358 @@ +package capture + +// The 2026-12-03 operator decision: a scope the routing table does NOT NAME is placed like `*` — the +// session ships to the default instance OWNER-ONLY — instead of HOLDING the session. The hold is +// kept only for a scope the table explicitly routes to an instance this host does not configure. +// +// Why it mattered: `scopeuse` takes header-shaped text anywhere in a transcript (grep output, a +// source read, assistant prose) as a read, so a fixture name like `alpha-notes` in a test's output +// froze a whole session for good — and holding an already-shipped session WITHDREW it first. +// Measured on a two-instance host: 14 of 15 such holds were fixture names. +// +// Synthetic throughout: `twoInstances` (personal, client) names `alpha-notes` and `beta-notes`, so +// `gamma-notes` is a scope the table does not name. + +import ( + "bytes" + "encoding/json" + "errors" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/ZacxDev/cairn/internal/client" +) + +// unnamedRead is a recorded read of `gamma-notes`, a scope `twoInstances`' table does not name. +var unnamedRead = strings.Replace(betaRead, "beta-notes", "gamma-notes", 1) + +// TestAnUnnamedScopeIsPlacedOwnerOnlyOnTheDefault is the routing rule itself. Red at origin/main: +// every case was `Held: true` ("scope gamma-notes routes to no configured instance"). +func TestAnUnnamedScopeIsPlacedOwnerOnlyOnTheDefault(t *testing.T) { + for _, tc := range []struct { + name string + v []string + }{ + {"alone", []string{"gamma-notes"}}, + {"beside a default-instance scope", []string{"alpha-notes", "gamma-notes"}}, + // The other instance's scope does not win: an unnamed scope forces the default, as `*` does, + // in either order. + {"beside the other instance's scope", []string{"beta-notes", "gamma-notes"}}, + {"before the other instance's scope", []string{"gamma-notes", "beta-notes"}}, + } { + t.Run(tc.name, func(t *testing.T) { + d := Decide(tc.v, Repo{}, twoInstances, RepoRules{}) + if d.Held || d.Deferred { + t.Fatalf("V=%v → held/deferred (%s); an unnamed scope must be placed", tc.v, d.Reason) + } + if d.Instance != "personal" || !d.OwnerOnly || !d.DeclaresStar() { + t.Fatalf("V=%v → %+v, want personal, owner-only, declared", tc.v, d) + } + }) + } + if d := Decide([]string{"gamma-notes"}, Repo{}, twoInstances, RepoRules{}); d.OwnerOnlyBy != OwnerOnlyUnnamedScope || + d.Reason != "scope gamma-notes is not in the routing table (treated as *): shipped to personal, owner-only" { + t.Fatalf("an unnamed scope alone → cause %v, reason %q", d.OwnerOnlyBy, d.Reason) + } + // With NO table at all on a two-instance host every scope is unnamed: placed the same way. + noTable := client.Routing{Instances: twoInstances.Instances} + if d := Decide([]string{"alpha-notes"}, Repo{}, noTable, RepoRules{}); d.Held || d.Instance != "personal" || !d.OwnerOnly { + t.Fatalf("two instances, no table → %+v, want personal owner-only", d) + } +} + +// TestAnUnnamedScopeShipsOwnerOnlyAndIsNeitherHeldNorWithdrawn drives the agent: a NEW session that +// read an unnamed scope ships to the default instance with `*` declared. Red at origin/main: held, +// nothing shipped. +func TestAnUnnamedScopeShipsOwnerOnlyAndIsNeitherHeldNorWithdrawn(t *testing.T) { + w := loadWorld(t) + e := materialize(t, w, "cc-plain") + s := w.Sessions["cc-plain"] + appendTo(t, filepath.Join(e.claude, s.Project, s.ID+".jsonl"), unnamedRead) + a := newAgent(t, e, twoInstances, &fakeRunner{}, &bytes.Buffer{}) + sum := mustRun(t, a) + ss := a.State.Sessions[s.ID] + if sum.Held != 0 || ss.Held || sum.Withdrawn != 0 { + t.Fatalf("%+v held=%v (%s) — want shipped, not held", sum, ss.Held, ss.HeldReason) + } + if !slices.Contains(ss.V, "gamma-notes") { + t.Fatalf("CONTROL: the session did not record the unnamed scope: V=%v", ss.V) + } + if ss.Instance != "personal" || !e.sink.has("personal", s.ID) || e.sink.has("client", s.ID) { + t.Fatalf("bound to %q; on personal=%v client=%v — want personal only", ss.Instance, + e.sink.has("personal", s.ID), e.sink.has("client", s.ID)) + } + if !slices.Contains(e.sink.declared["personal/"+s.ID], "*") || !slices.Contains(ss.Declared, "*") { + t.Fatalf("not declared owner-only: sink %v, state %v", e.sink.declared["personal/"+s.ID], ss.Declared) + } +} + +// TestAShippedSessionThatReadsAnUnnamedScopeIsNotWithdrawn is the measured damage: a session already +// on the default instance gains an unnamed scope. Red at origin/main: it was WITHDRAWN from personal +// and held. Now it stays, its new record ships there, and `*` is declared from then on. +func TestAShippedSessionThatReadsAnUnnamedScopeIsNotWithdrawn(t *testing.T) { + w := loadWorld(t) + e := materialize(t, w, "cc-plain") + s := w.Sessions["cc-plain"] + path := filepath.Join(e.claude, s.Project, s.ID+".jsonl") + a := newAgent(t, e, twoInstances, &fakeRunner{}, &bytes.Buffer{}) + mustRun(t, a) + shipped := len(spooled(t, e, "personal", s.ID, "main")) + if shipped == 0 || a.State.Sessions[s.ID].Instance != "personal" { + t.Fatal("CONTROL: run 1 did not ship the session to personal") + } + appendTo(t, path, unnamedRead) + sum := mustRun(t, a) + ss := a.State.Sessions[s.ID] + if sum.Withdrawn != 0 || len(e.sink.withdrawn["personal"]) != 0 || len(ss.WithdrawnFrom) != 0 { + t.Fatalf("the session was WITHDRAWN: %+v withdrawn=%v", sum, e.sink.withdrawn) + } + if sum.Held != 0 || ss.Held || ss.Instance != "personal" { + t.Fatalf("run 2: %+v held=%v (%s) bound=%q — want still shipping to personal", sum, ss.Held, ss.HeldReason, ss.Instance) + } + if got := len(spooled(t, e, "personal", s.ID, "main")); got != shipped+1 { + t.Fatalf("the record that read the unnamed scope did not ship (%d → %d)", shipped, got) + } + if !slices.Contains(e.sink.declared["personal/"+s.ID], "*") { + t.Fatalf("not declared owner-only after the unnamed read: %v", e.sink.declared["personal/"+s.ID]) + } +} + +// TestAScopeRoutedToAnUnconfiguredAliasIsStillHeldAndSaysWhy: the one routing hold left, with a reason +// that says what it is. The hold itself is an INVARIANT GUARD (green at origin/main too); the reason +// text is new (red there: "routes to no configured instance", which also described unnamed scopes). +func TestAScopeRoutedToAnUnconfiguredAliasIsStillHeldAndSaysWhy(t *testing.T) { + r := client.Routing{Instances: twoInstances.Instances, RoutesSource: "the test's table", + Routes: map[string]string{"alpha-notes": "personal", "delta-notes": "elsewhere"}} + for _, v := range [][]string{{"delta-notes"}, {"alpha-notes", "delta-notes"}, {"gamma-notes", "delta-notes"}, {"*", "delta-notes"}} { + d := Decide(v, Repo{}, r, RepoRules{}) + if !d.Held || d.Reason != "scope delta-notes is routed by the table to instance elsewhere, which this host does not configure" { + t.Fatalf("V=%v → %+v, want HELD naming the unconfigured alias", v, d) + } + } +} + +// TestStarIsUnchanged: `*` keeps its own cause and placement (INVARIANT GUARD — green at origin/main). +func TestStarIsUnchanged(t *testing.T) { + d := Decide([]string{"*", "beta-notes"}, Repo{}, twoInstances, RepoRules{}) + if d.Held || d.Instance != "personal" || d.OwnerOnlyBy != OwnerOnlyStar { + t.Fatalf("`*` → %+v, want personal, OwnerOnlyStar", d) + } + if d := Decide([]string{"*"}, Repo{}, oneInstance, RepoRules{}); d.Held || d.OwnerOnly { + t.Fatalf("one-instance `*` → %+v", d) + } +} + +// --- the re-evaluation of EXISTING holds ------------------------------------------------------------- + +const legacyGamma = "scope gamma-notes routes to no configured instance" + +// reevalRouting is twoInstances plus `delta-notes` explicitly routed to an alias this host lacks. +var reevalRouting = client.Routing{Instances: twoInstances.Instances, RoutesSource: "the test's table", + Routes: map[string]string{"alpha-notes": "personal", "beta-notes": "client", "delta-notes": "elsewhere"}} + +func reevalState() *State { + return &State{Schema: 1, Sessions: map[string]*SessionState{ + // eligible: an unnamed scope, legacy history. + "r-ship": {Runtime: "claude", Held: true, HeldReason: legacyGamma, V: []string{"gamma-notes"}}, + // eligible: unnamed beside the other instance's scope → personal, owner-only. + "r-cross": {Runtime: "opencode", Held: true, HeldReason: legacyGamma, V: []string{"beta-notes", "gamma-notes"}, HistoryKept: true}, + // the old text, but the scope IS named — for an unconfigured alias: still held. + "r-unconfigured": {Runtime: "claude", Held: true, HeldReason: "scope delta-notes routes to no configured instance", + V: []string{"delta-notes"}}, + // eligible under the rule, but WITHDRAWN on the server: the probe answers 410. + "r-withdrawn": {Runtime: "claude", Held: true, HeldReason: legacyGamma, V: []string{"gamma-notes"}}, + // operator-frozen; one bound, one not — the unbound one would otherwise look placeable. + "r-frozen": {Runtime: "claude", Held: true, Instance: "personal", V: []string{"beta-notes"}, + HeldReason: "routed back to client, which deleted this session's transcript: kept on personal"}, + "r-frozen-unbound": {Runtime: "claude", Held: true, V: []string{"gamma-notes"}, + HeldReason: "routed back to client, which deleted this session's transcript: kept on personal"}, + "r-other": {Runtime: "claude", Held: true, HeldReason: "prefix not withdrawn: not held by this owner and host on client", V: []string{"gamma-notes"}}, + "r-notheld": {Runtime: "claude", V: []string{"gamma-notes"}}, + }} +} + +func reevalAgent(t *testing.T, withSink bool) (*Agent, *memSink) { + t.Helper() + a := &Agent{State: reevalState(), ClaudeRoot: t.TempDir(), Routing: reevalRouting, Log: &bytes.Buffer{}} + sink := newMemSink() + sink.deletedOn = map[string]bool{"personal/r-withdrawn": true} + if withSink { + a.Sink = sink + } + return a, sink +} + +func outcomes(rs []Reevaluation) map[string]string { + out := map[string]string{} + for _, r := range rs { + out[r.Root] = r.Outcome + } + return out +} + +func stateJSON(t *testing.T, s *State) string { + t.Helper() + b, err := json.Marshal(s) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +func wantOutcomes(t *testing.T, got map[string]string, want map[string]string) { + t.Helper() + if len(got) != len(want) { + t.Fatalf("outcomes %v, want %v", got, want) + } + for k, v := range want { + if got[k] != v { + t.Fatalf("%s: outcome %q, want %q (all: %v)", k, got[k], v, got) + } + } +} + +// TestReevaluateDryRunListsTheRightSetAndChangesNothing: no sink, so nothing is probed; the state is +// byte-identical afterwards. +func TestReevaluateDryRunListsTheRightSetAndChangesNothing(t *testing.T) { + a, sink := reevalAgent(t, false) + before := stateJSON(t, a.State) + rs := a.ReevaluateHeld() + wantOutcomes(t, outcomes(rs), map[string]string{ + "r-ship": ReevalUnprobed, "r-cross": ReevalUnprobed, "r-withdrawn": ReevalUnprobed, + "r-unconfigured": ReevalStillHeld, "r-frozen": ReevalExcluded, "r-frozen-unbound": ReevalExcluded, "r-other": ReevalExcluded, + }) + for _, r := range rs { + if r.Outcome == ReevalUnprobed && (r.Target != "personal" || !r.OwnerOnly) { + t.Fatalf("%s → target %q owner-only=%v, want personal owner-only", r.Root, r.Target, r.OwnerOnly) + } + if strings.HasPrefix(r.Root, "r-frozen") && !strings.Contains(r.Detail, "frozen by operator decision") { + t.Fatalf("%s was excluded, but not as operator-frozen: %q", r.Root, r.Detail) + } + } + if after := stateJSON(t, a.State); after != before { + t.Fatalf("a dry run changed the state:\n%s\n%s", before, after) + } + if len(sink.probes) != 0 { + t.Fatalf("a dry run with no sink probed: %v", sink.probes) + } +} + +// TestReevaluateProbesAndApplyClearsOnlyTheEligible: with a sink every candidate's destination is +// probed (and nothing else is sent); apply clears exactly the `ship` ones; the 410 one is reported +// needs-server-restore and left held with its ORIGINAL reason. +func TestReevaluateProbesAndApplyClearsOnlyTheEligible(t *testing.T) { + a, sink := reevalAgent(t, true) + before := stateJSON(t, a.State) + rs := a.ReevaluateHeld() + wantOutcomes(t, outcomes(rs), map[string]string{ + "r-ship": ReevalShip, "r-cross": ReevalShip, "r-withdrawn": ReevalNeedsRestore, + "r-unconfigured": ReevalStillHeld, "r-frozen": ReevalExcluded, "r-frozen-unbound": ReevalExcluded, "r-other": ReevalExcluded, + }) + slices.Sort(sink.probes) + if want := []string{"personal/r-cross/main", "personal/r-ship/main", "personal/r-withdrawn/main"}; !slices.Equal(sink.probes, want) { + t.Fatalf("probed %v, want %v", sink.probes, want) + } + if len(sink.records) != 0 || len(sink.blobs) != 0 || len(sink.withdrawn) != 0 { + t.Fatal("the re-evaluation sent something other than a probe") + } + if stateJSON(t, a.State) != before { + t.Fatal("evaluating changed the state; only an apply may") + } + cleared := a.State.ApplyReevaluation(rs) + var roots []string + for _, r := range cleared { + roots = append(roots, r.Root) + } + slices.Sort(roots) + if !slices.Equal(roots, []string{"r-cross", "r-ship"}) { + t.Fatalf("cleared %v, want r-cross and r-ship", roots) + } + for _, root := range []string{"r-ship", "r-cross"} { + if ss := a.State.Sessions[root]; ss.Held || ss.HeldReason != "" { + t.Fatalf("%s still held", root) + } + } + for root, ss := range reevalState().Sessions { + if root == "r-ship" || root == "r-cross" { + continue + } + if got := a.State.Sessions[root]; got.Held != ss.Held || got.HeldReason != ss.HeldReason { + t.Fatalf("%s changed: held=%v %q", root, got.Held, got.HeldReason) + } + } +} + +// TestApplyRechecksTheStateAtTheWrite: an evaluation is a snapshot; a hold whose state moved since +// (here: its reason) is not cleared on the strength of it. +func TestApplyRechecksTheStateAtTheWrite(t *testing.T) { + a, _ := reevalAgent(t, true) + rs := a.ReevaluateHeld() + // Another legacy unnamed-scope text, so ONLY the "same reason as evaluated" check can refuse it. + a.State.Sessions["r-ship"].HeldReason = "scope zeta-notes routes to no configured instance" + cleared := a.State.ApplyReevaluation(rs) + for _, r := range cleared { + if r.Root == "r-ship" { + t.Fatal("a hold whose reason changed after the evaluation was cleared") + } + } + if !a.State.Sessions["r-ship"].Held { + t.Fatal("r-ship was un-held") + } +} + +// TestReevaluateProbeFailureIsNotCleared: no answer is not a yes. +func TestReevaluateProbeFailureIsNotCleared(t *testing.T) { + a, sink := reevalAgent(t, true) + sink.probeErr = errors.New("connection refused") + rs := a.ReevaluateHeld() + if o := outcomes(rs); o["r-ship"] != ReevalProbeFailed || o["r-withdrawn"] != ReevalProbeFailed { + t.Fatalf("outcomes %v", o) + } + if cleared := a.State.ApplyReevaluation(rs); len(cleared) != 0 { + t.Fatalf("cleared %d on failed probes", len(cleared)) + } +} + +// TestAReevaluatedSessionShipsOnTheNextPassAndAWithdrawnOneDoesNotLoop drives the whole sequence +// through the agent: a legacy unnamed-scope hold the destination will take is cleared and ships +// owner-only on the next pass; one the destination answers 410 for is left held — with its original +// reason, so the next pass skips it before routing, sends nothing and re-holds nothing. +func TestAReevaluatedSessionShipsOnTheNextPassAndAWithdrawnOneDoesNotLoop(t *testing.T) { + w := loadWorld(t) + e := materialize(t, w, "cc-plain", "cc-hook-recall") + plain, other := w.Sessions["cc-plain"].ID, w.Sessions["cc-hook-recall"].ID + a := newAgent(t, e, twoInstances, &fakeRunner{}, &bytes.Buffer{}) + a.State.Sessions[plain] = &SessionState{Runtime: "claude", Held: true, HeldReason: legacyGamma, V: []string{"gamma-notes"}} + a.State.Sessions[other] = &SessionState{Runtime: "claude", Held: true, HeldReason: legacyGamma, V: []string{"gamma-notes"}} + e.sink.deletedOn = map[string]bool{"personal/" + other: true} + + rs := a.ReevaluateHeld() + if o := outcomes(rs); o[plain] != ReevalShip || o[other] != ReevalNeedsRestore { + t.Fatalf("outcomes %v", o) + } + for _, r := range rs { + if r.Bytes <= 0 { + t.Fatalf("%s: bytes on disk %d, want the transcript's size", r.Root, r.Bytes) + } + } + a.State.ApplyReevaluation(rs) + probes := len(e.sink.probes) + sum := mustRun(t, a) + ps := a.State.Sessions[plain] + if ps.Held || ps.Instance != "personal" || !e.sink.has("personal", plain) || !slices.Contains(e.sink.declared["personal/"+plain], "*") { + t.Fatalf("the cleared session: held=%v bound=%q shipped=%v declared=%v", ps.Held, ps.Instance, + e.sink.has("personal", plain), e.sink.declared["personal/"+plain]) + } + ws := a.State.Sessions[other] + if !ws.Held || ws.HeldReason != legacyGamma || e.sink.has("personal", other) || sum.Held != 0 { + t.Fatalf("the withdrawn session: held=%v %q shipped=%v run-held=%d — want untouched", ws.Held, ws.HeldReason, + e.sink.has("personal", other), sum.Held) + } + for _, p := range e.sink.probes[probes:] { + if strings.Contains(p, other) { + t.Fatalf("the pass probed the needs-restore session again: %v", e.sink.probes[probes:]) + } + } +} From 64d07143aae28d41f81c5eb315a2524b1b34bbbc Mon Sep 17 00:00:00 2001 From: Zachary Lowden Date: Thu, 3 Dec 2026 22:53:06 -0600 Subject: [PATCH 2/4] docs(changelog): anchor the unnamed-scope entry to #330 Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cde44207..0939405a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,7 +29,7 @@ claim to cover them; `git log` and the PR history are the record for those. | change | anchor | what you may have to do | why it was taken | |---|---|---|---| -| **`cairn-capture` no longer HOLDS a session for a scope the routing table does not name** (on a host with more than one instance): it ships to the DEFAULT instance OWNER-ONLY (`*` declared), as a `*` session does, and an already-shipped session is no longer withdrawn for it. A scope the table EXPLICITLY routes to an instance this host does not configure is still held — the only routing hold left — and its `held_reason` now says so (`scope X is routed by the table to instance Y, which this host does not configure`). New mode **`--reevaluate-held [-apply]`** recovers the holds the old rule made | [#PRNUM](https://github.com/ZacxDev/cairn/pull/PRNUM) → `` | ⚠ **Sessions previously held stay held** until you run `--reevaluate-held` (read-only listing), then, with `-host`/`-worker`/`-capture-token-file`, `-apply`: it clears only holds whose destination answered the position probe; a 410 is listed `needs-server-restore` and left held — restore it by the server journal. The `routed back to …, which deleted this session's transcript` holds are never touched. ⚠ **If you match `held_reason` text**, the unconfigured-alias hold's wording changed. [`internal/capture/README.md`](internal/capture/README.md) step 3 and § *`--reevaluate-held`* | `scopeuse` reads header-shaped text anywhere in a transcript (test output, a source read, assistant prose) as a scope read, so a fixture name in a grep result held — and withdrew — whole sessions: measured on a two-instance host, 15 held this way, 14 on fixture names. An unnamed scope is a claim about no instance, so there is no leak to stop: [`internal/capture/route.go`](internal/capture/route.go)'s `Decide` | +| **`cairn-capture` no longer HOLDS a session for a scope the routing table does not name** (on a host with more than one instance): it ships to the DEFAULT instance OWNER-ONLY (`*` declared), as a `*` session does, and an already-shipped session is no longer withdrawn for it. A scope the table EXPLICITLY routes to an instance this host does not configure is still held — the only routing hold left — and its `held_reason` now says so (`scope X is routed by the table to instance Y, which this host does not configure`). New mode **`--reevaluate-held [-apply]`** recovers the holds the old rule made | [#330](https://github.com/ZacxDev/cairn/pull/330) → `` | ⚠ **Sessions previously held stay held** until you run `--reevaluate-held` (read-only listing), then, with `-host`/`-worker`/`-capture-token-file`, `-apply`: it clears only holds whose destination answered the position probe; a 410 is listed `needs-server-restore` and left held — restore it by the server journal. The `routed back to …, which deleted this session's transcript` holds are never touched. ⚠ **If you match `held_reason` text**, the unconfigured-alias hold's wording changed. [`internal/capture/README.md`](internal/capture/README.md) step 3 and § *`--reevaluate-held`* | `scopeuse` reads header-shaped text anywhere in a transcript (test output, a source read, assistant prose) as a scope read, so a fixture name in a grep result held — and withdrew — whole sessions: measured on a two-instance host, 15 held this way, 14 on fixture names. An unnamed scope is a claim about no instance, so there is no leak to stop: [`internal/capture/route.go`](internal/capture/route.go)'s `Decide` | | **`cairn-capture --clear-held` no longer clears a hold whose session was ever bound or WITHDRAWN, nor any empty-`instance` hold in a state written by an earlier agent.** The state keeps a per-session shipping history (`bound_ever`, `withdrawn_from`, `history_kept`); `--list-held` prints a sixth field, why a `permanent` hold is kept, and `--clear-held` prints it per kept hold. EVERY first binding is now position-probed (one request per new session; a 410 there holds the session), a withdrawal is recorded before it is sent, and a 410 on an instance the session was withdrawn from HOLDS it instead of marking it `deleted`. The hold reason is neutral (`410: withdrawn or deleted there`): restore by the server journal's reason. | [#324](https://github.com/ZacxDev/cairn/pull/324) → `` | ⚠ **Existing empty-`instance` holds become `permanent`** (a legacy state cannot prove they never shipped). List them: `cairn-capture --list-held \| awk -F'\t' '$3 == "permanent"'`. ⚠ **If you parse `--list-held`**, one trailing field is added; the first five keep their positions. [`internal/capture/README.md`](internal/capture/README.md) § *`held=` is not the backlog* | DATA LOSS: an empty `instance` was read as "never shipped", but a withdrawal empties it too. `--clear-held` cleared withdrawn sessions, the next pass re-sent them unprobed, the instance answered 410 (a withdrawal is final for its uploader), and each was marked `deleted` for good — measured: 49 sessions on one host | | **`cairn-capture -foreign-root-base BASE -foreign-claude-root [OWNER=]DIR`** (repeatable, `--run`/`--dry-run`; BASE absolute and required, DIR strictly beneath it; Linux only): more Claude Code projects roots whose sessions ran on another filesystem (a container's volume). They ship like `-claude-root`'s, but their recorded `cwd` is never resolved on this host: one that recorded no scope is placed by OWNER as an `origin` owner (`-route-origin-owner`), else the default instance; each is resolved from BASE with no symlink followed in any component (openat2, or an O_NOFOLLOW walk) and held open for the run; an unreadable one is one `refused=`, an absent one is logged; an id already found under an earlier root is skipped. **Every root, `-claude-root` included, now refuses (logs, `refused=`) a session file or project directory that is a symlink, and never reads a file through one** | `` | If you keep session files under `-claude-root` as SYMLINKS, they are no longer captured: `find -type l` first. Otherwise nothing unless you pass the flag | Capturing agents that run in containers from the host, without a client or network path in the container: [`internal/capture/README.md`](internal/capture/README.md) § *A session that recorded no scope* | | **`cairn-capture`: a session already BOUND to an instance is DEFERRED while F1 is live, for at most 1 hour** (on a host with more than one instance): nothing of it is shipped and nothing withdrawn, counted on a NEW run-line field **`deferred=`** (not `refused=`), logged once when the window starts. The window's start is saved per session as `f1_since` in the state and cleared whenever F1 is false; once it expires with F1 still live, the session is routed exactly as before (F1's `*` forces the default instance, with the usual withdrawal), logged once. A NEW session is still placed on the default instance by F1. **`--dry-run` routes F1 as `--run` does**, reading `f1_since` read-only: `decision=deferred` inside the window, the base rule's answer after it | [#317](https://github.com/ZacxDev/cairn/pull/317) → `` | ⚠ **If you parse the run line**, `deferred=` is INSERTED after `export-skipped=`, inside the `cairn-capture: run …` line, so the four fields `--run` prints after the summary — `omitted=`, `recheck-omitted=`, `requests=`, `held-backlog=` — each shift one position right: a parser keyed on field NAMES is unaffected, a POSITIONAL one must update. ⚠ **A bound session's capture can lag by up to an hour** while F1 holds. ⚠ **Two residuals remain**: a session whose F1 stays live past the window is moved by the base rule and can still be held by a later move back (410); and once any ledger record lands, earlier output that had no ledger record of its own ships under that later scope, deferred or not (pre-existing T3). ⚠ **It recovers nothing already held**, and one an older build moved but has not yet held will be held when its ledger line lands — no supported operation un-deletes a root on an instance. [`internal/capture/README.md`](internal/capture/README.md) step 3 and § *A session deleted on its instance (410)* | Claude Code writes a `cairn` call's tool input before the client appends its ledger line, so a pass in between saw F1 and moved a repo-placed session to the default; the next pass's move back answered 410 and held it for good. Bounded because F1's evidence is sticky, so an unbounded deferral stopped some sessions' capture for good: [`internal/capture/f1move_test.go`](internal/capture/f1move_test.go), [`internal/capture/route.go`](internal/capture/route.go)'s `DecideRun` | From 52cc25f28704d4e8f5e04b6fa00b25b932ef1f50 Mon Sep 17 00:00:00 2001 From: Zachary Lowden Date: Thu, 3 Dec 2026 23:03:56 -0600 Subject: [PATCH 3/4] chore(capture): drop dated stamps from Go comments (leakscan dated-incident) leakscan refused route.go's '2026-12-03' as a dated incident stamp; the operator decision is now cited by its PR (#330) in code. The plan, README and CHANGELOG keep the date, which leakscan does not flag there. Co-Authored-By: Claude Opus 5.5 (1M context) --- cmd/cairn-capture/main.go | 4 ++-- cmd/cairn-capture/reeval_test.go | 2 +- internal/capture/reevaluate.go | 4 ++-- internal/capture/route.go | 6 +++--- internal/capture/unnamed_test.go | 2 +- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/cmd/cairn-capture/main.go b/cmd/cairn-capture/main.go index f73c9bb2..615cea2f 100644 --- a/cmd/cairn-capture/main.go +++ b/cmd/cairn-capture/main.go @@ -33,7 +33,7 @@ // cairn-capture --clear-held [-state FILE] // cairn-capture --reevaluate-held [-state FILE] [-claude-root DIR] [-host LABEL -worker [ALIAS=]URL -capture-token-file [ALIAS=]FILE]... [-apply] // -// `--reevaluate-held` is the one-off recovery of the holds the pre-2026-12-03 rule made for a scope +// `--reevaluate-held` is the one-off recovery of the holds the pre-#330 rule made for a scope // the routing table does not name (`capture.Agent.ReevaluateHeld`): read-only unless `-apply`, and // `-apply` clears only a hold whose destination answered the position probe — a 410 is reported // `needs-server-restore` and left held. @@ -135,7 +135,7 @@ func run(args []string, stdout, stderr io.Writer, getenv func(string) string) in "owner were OWNER (-route-origin-owner), else on the default instance. No file beneath it is read through a "+ "symlink, and a root whose own path runs through one is refused; an unreadable root refuses only itself, an "+ "absent one is logged (repeatable; no default)") - reeval := fs.Bool("reevaluate-held", false, "list the holds the pre-2026-12-03 rule made for a scope the routing table "+ + reeval := fs.Bool("reevaluate-held", false, "list the holds the pre-#330 rule made for a scope the routing table "+ "does not name, re-decided under the current rule (and, given -host/-worker/-capture-token-file, probed at their "+ "destination); writes nothing without -apply") apply := fs.Bool("apply", false, "--reevaluate-held only: clear the holds whose destination answered the probe with a "+ diff --git a/cmd/cairn-capture/reeval_test.go b/cmd/cairn-capture/reeval_test.go index 38d88846..84e3fcc5 100644 --- a/cmd/cairn-capture/reeval_test.go +++ b/cmd/cairn-capture/reeval_test.go @@ -1,7 +1,7 @@ package main // `--reevaluate-held`, end to end through run() against real in-process worker pods: the one-off -// recovery of the holds the pre-2026-12-03 rule made for a scope the routing table does not name. +// recovery of the holds the pre-#330 rule made for a scope the routing table does not name. import ( "bytes" diff --git a/internal/capture/reevaluate.go b/internal/capture/reevaluate.go index 591870d1..0da9d5b3 100644 --- a/internal/capture/reevaluate.go +++ b/internal/capture/reevaluate.go @@ -7,7 +7,7 @@ import ( "strings" ) -// The one-off re-evaluation of EXISTING holds after the 2026-12-03 operator decision ([Decide]): a +// The one-off re-evaluation of EXISTING holds after the operator decision of #330 ([Decide]): a // scope the routing table does not name is placed like `*` now, but `held` is FINAL in the state, so // the sessions the old rule held stay held until an operator clears them. `--clear-held` cannot: every // such hold on the measured host was LEGACY ([SessionState.HistoryKept] false), and a legacy hold is @@ -65,7 +65,7 @@ type Reevaluation struct { Bytes int64 } -// legacyUnnamedHold reports whether `reason` is the hold text the PRE-2026-12-03 rule wrote for a +// legacyUnnamedHold reports whether `reason` is the hold text the PRE-#330 rule wrote for a // scope it could not route: "scope X routes to no configured instance". That text was written for an // UNNAMED scope on a multi-instance host AND for a scope named for an unconfigured alias, so matching // it only SELECTS a candidate — [Decide] over the session's V says which it was. diff --git a/internal/capture/route.go b/internal/capture/route.go index 4b4880f5..657f7595 100644 --- a/internal/capture/route.go +++ b/internal/capture/route.go @@ -54,7 +54,7 @@ const ( // there. OwnerOnlyCrossInstance // OwnerOnlyUnnamedScope: a recorded scope the routing table does not name at all, on a host with - // more than one instance (operator decision 2026-12-03). Declared, exactly as `*` is: the scope + // more than one instance (operator decision, #330). Declared, exactly as `*` is: the scope // says nothing about where the session belongs, so it is placed on the default instance and // nobody but the owner may read it there. OwnerOnlyUnnamedScope @@ -76,7 +76,7 @@ func (d Decision) DeclaresStar() bool { // `*` forces the default however V is ordered, and however few other scopes it carries: it is // the conservative direction, and an order-dependent answer is not a policy. // - a scope the routing table does NOT NAME, with more than one instance configured → the DEFAULT -// instance, OWNER-ONLY, exactly as `*` (operator decision 2026-12-03; it used to HOLD). With one +// instance, OWNER-ONLY, exactly as `*` (operator decision, #330; it used to HOLD). With one // instance such a scope routes to the sole instance and is not owner-only, as before. // - a scope the routing table NAMES for an alias this host does not configure → HELD, at any // instance count: the table says that scope lives on ANOTHER instance, and shipping its records @@ -216,7 +216,7 @@ func decideRun(v []string, f1 bool, repo Repo, routing client.Routing, rules Rep return Decision{Held: true, Reason: UnconfiguredHoldReason(scope, to)} } // 🔴 A SCOPE THE TABLE DOES NOT NAME AT ALL IS TREATED LIKE `*` (operator decision, - // 2026-12-03): it forces the DEFAULT instance, owner-only. It used to HOLD the session on a + // #330): it forces the DEFAULT instance, owner-only. It used to HOLD the session on a // multi-instance host, and a hold is final and withdraws an already-shipped prefix — while // the scope reader (`scopeuse`) takes header-shaped text in ANY transcript (test output, a // source read, assistant prose) as a read, so one fixture name in a grep result froze and diff --git a/internal/capture/unnamed_test.go b/internal/capture/unnamed_test.go index df23c7db..c6e58bc8 100644 --- a/internal/capture/unnamed_test.go +++ b/internal/capture/unnamed_test.go @@ -1,6 +1,6 @@ package capture -// The 2026-12-03 operator decision: a scope the routing table does NOT NAME is placed like `*` — the +// The operator decision of #330: a scope the routing table does NOT NAME is placed like `*` — the // session ships to the default instance OWNER-ONLY — instead of HOLDING the session. The hold is // kept only for a scope the table explicitly routes to an instance this host does not configure. // From 540caeb1ddf615f33fba4e38d8a238ce7a9c900e Mon Sep 17 00:00:00 2001 From: Zachary Lowden Date: Fri, 4 Dec 2026 07:46:39 -0600 Subject: [PATCH 4/4] docs(capture): an unnamed scope MOVES a non-default-bound session; pin that path Round 1 of #330's audit (0 red): the docs said an already-shipped session is no longer withdrawn for an unnamed scope, which holds only for a session bound to the DEFAULT instance. One bound to another instance moves as a `*` session does: withdrawn from there, rebound to the default, re-shipped whole from offset 0, owner-only (at main it was withdrawn and HELD). CHANGELOG and README now say so, and TestAClientBoundSessionThatReadsAnUnnamedScopeMovesOwnerOnlyToTheDefault pins the withdrawal from client and the owner-only rebinding on personal (mutants: main's hold condition, and the unnamed owner-only case dropped, each fail it). Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 2 +- internal/capture/README.md | 4 ++- internal/capture/unnamed_test.go | 42 ++++++++++++++++++++++++++++++++ 3 files changed, 46 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0939405a..073d30df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,7 +29,7 @@ claim to cover them; `git log` and the PR history are the record for those. | change | anchor | what you may have to do | why it was taken | |---|---|---|---| -| **`cairn-capture` no longer HOLDS a session for a scope the routing table does not name** (on a host with more than one instance): it ships to the DEFAULT instance OWNER-ONLY (`*` declared), as a `*` session does, and an already-shipped session is no longer withdrawn for it. A scope the table EXPLICITLY routes to an instance this host does not configure is still held — the only routing hold left — and its `held_reason` now says so (`scope X is routed by the table to instance Y, which this host does not configure`). New mode **`--reevaluate-held [-apply]`** recovers the holds the old rule made | [#330](https://github.com/ZacxDev/cairn/pull/330) → `` | ⚠ **Sessions previously held stay held** until you run `--reevaluate-held` (read-only listing), then, with `-host`/`-worker`/`-capture-token-file`, `-apply`: it clears only holds whose destination answered the position probe; a 410 is listed `needs-server-restore` and left held — restore it by the server journal. The `routed back to …, which deleted this session's transcript` holds are never touched. ⚠ **If you match `held_reason` text**, the unconfigured-alias hold's wording changed. [`internal/capture/README.md`](internal/capture/README.md) step 3 and § *`--reevaluate-held`* | `scopeuse` reads header-shaped text anywhere in a transcript (test output, a source read, assistant prose) as a scope read, so a fixture name in a grep result held — and withdrew — whole sessions: measured on a two-instance host, 15 held this way, 14 on fixture names. An unnamed scope is a claim about no instance, so there is no leak to stop: [`internal/capture/route.go`](internal/capture/route.go)'s `Decide` | +| **`cairn-capture` no longer HOLDS a session for a scope the routing table does not name** (on a host with more than one instance): it ships to the DEFAULT instance OWNER-ONLY (`*` declared), as a `*` session does. A session already bound to the DEFAULT instance is no longer withdrawn for it; one bound to ANOTHER instance is withdrawn from there and re-shipped whole to the default, owner-only — the `*` path (before, it was withdrawn and HELD). A scope the table EXPLICITLY routes to an instance this host does not configure is still held — the only routing hold left — and its `held_reason` now says so (`scope X is routed by the table to instance Y, which this host does not configure`). New mode **`--reevaluate-held [-apply]`** recovers the holds the old rule made | [#330](https://github.com/ZacxDev/cairn/pull/330) → `` | ⚠ **Sessions previously held stay held** until you run `--reevaluate-held` (read-only listing), then, with `-host`/`-worker`/`-capture-token-file`, `-apply`: it clears only holds whose destination answered the position probe; a 410 is listed `needs-server-restore` and left held — restore it by the server journal. The `routed back to …, which deleted this session's transcript` holds are never touched. ⚠ **If you match `held_reason` text**, the unconfigured-alias hold's wording changed. [`internal/capture/README.md`](internal/capture/README.md) step 3 and § *`--reevaluate-held`* | `scopeuse` reads header-shaped text anywhere in a transcript (test output, a source read, assistant prose) as a scope read, so a fixture name in a grep result held — and withdrew — whole sessions: measured on a two-instance host, 15 held this way, 14 on fixture names. An unnamed scope is a claim about no instance, so there is no leak to stop: [`internal/capture/route.go`](internal/capture/route.go)'s `Decide` | | **`cairn-capture --clear-held` no longer clears a hold whose session was ever bound or WITHDRAWN, nor any empty-`instance` hold in a state written by an earlier agent.** The state keeps a per-session shipping history (`bound_ever`, `withdrawn_from`, `history_kept`); `--list-held` prints a sixth field, why a `permanent` hold is kept, and `--clear-held` prints it per kept hold. EVERY first binding is now position-probed (one request per new session; a 410 there holds the session), a withdrawal is recorded before it is sent, and a 410 on an instance the session was withdrawn from HOLDS it instead of marking it `deleted`. The hold reason is neutral (`410: withdrawn or deleted there`): restore by the server journal's reason. | [#324](https://github.com/ZacxDev/cairn/pull/324) → `` | ⚠ **Existing empty-`instance` holds become `permanent`** (a legacy state cannot prove they never shipped). List them: `cairn-capture --list-held \| awk -F'\t' '$3 == "permanent"'`. ⚠ **If you parse `--list-held`**, one trailing field is added; the first five keep their positions. [`internal/capture/README.md`](internal/capture/README.md) § *`held=` is not the backlog* | DATA LOSS: an empty `instance` was read as "never shipped", but a withdrawal empties it too. `--clear-held` cleared withdrawn sessions, the next pass re-sent them unprobed, the instance answered 410 (a withdrawal is final for its uploader), and each was marked `deleted` for good — measured: 49 sessions on one host | | **`cairn-capture -foreign-root-base BASE -foreign-claude-root [OWNER=]DIR`** (repeatable, `--run`/`--dry-run`; BASE absolute and required, DIR strictly beneath it; Linux only): more Claude Code projects roots whose sessions ran on another filesystem (a container's volume). They ship like `-claude-root`'s, but their recorded `cwd` is never resolved on this host: one that recorded no scope is placed by OWNER as an `origin` owner (`-route-origin-owner`), else the default instance; each is resolved from BASE with no symlink followed in any component (openat2, or an O_NOFOLLOW walk) and held open for the run; an unreadable one is one `refused=`, an absent one is logged; an id already found under an earlier root is skipped. **Every root, `-claude-root` included, now refuses (logs, `refused=`) a session file or project directory that is a symlink, and never reads a file through one** | `` | If you keep session files under `-claude-root` as SYMLINKS, they are no longer captured: `find -type l` first. Otherwise nothing unless you pass the flag | Capturing agents that run in containers from the host, without a client or network path in the container: [`internal/capture/README.md`](internal/capture/README.md) § *A session that recorded no scope* | | **`cairn-capture`: a session already BOUND to an instance is DEFERRED while F1 is live, for at most 1 hour** (on a host with more than one instance): nothing of it is shipped and nothing withdrawn, counted on a NEW run-line field **`deferred=`** (not `refused=`), logged once when the window starts. The window's start is saved per session as `f1_since` in the state and cleared whenever F1 is false; once it expires with F1 still live, the session is routed exactly as before (F1's `*` forces the default instance, with the usual withdrawal), logged once. A NEW session is still placed on the default instance by F1. **`--dry-run` routes F1 as `--run` does**, reading `f1_since` read-only: `decision=deferred` inside the window, the base rule's answer after it | [#317](https://github.com/ZacxDev/cairn/pull/317) → `` | ⚠ **If you parse the run line**, `deferred=` is INSERTED after `export-skipped=`, inside the `cairn-capture: run …` line, so the four fields `--run` prints after the summary — `omitted=`, `recheck-omitted=`, `requests=`, `held-backlog=` — each shift one position right: a parser keyed on field NAMES is unaffected, a POSITIONAL one must update. ⚠ **A bound session's capture can lag by up to an hour** while F1 holds. ⚠ **Two residuals remain**: a session whose F1 stays live past the window is moved by the base rule and can still be held by a later move back (410); and once any ledger record lands, earlier output that had no ledger record of its own ships under that later scope, deferred or not (pre-existing T3). ⚠ **It recovers nothing already held**, and one an older build moved but has not yet held will be held when its ledger line lands — no supported operation un-deletes a root on an instance. [`internal/capture/README.md`](internal/capture/README.md) step 3 and § *A session deleted on its instance (410)* | Claude Code writes a `cairn` call's tool input before the client appends its ledger line, so a pass in between saw F1 and moved a repo-placed session to the default; the next pass's move back answered 410 and held it for good. Bounded because F1's evidence is sticky, so an unbounded deferral stopped some sessions' capture for good: [`internal/capture/f1move_test.go`](internal/capture/f1move_test.go), [`internal/capture/route.go`](internal/capture/route.go)'s `DecideRun` | diff --git a/internal/capture/README.md b/internal/capture/README.md index 05c34627..1ba184dd 100644 --- a/internal/capture/README.md +++ b/internal/capture/README.md @@ -43,7 +43,9 @@ operator's act. and the reason a cross-instance session is no longer held. 🔴 **A scope the routing table does NOT NAME at all is placed exactly like `*`** (operator decision 2026-12-03, `OwnerOnlyUnnamedScope`): on a host with more than one instance the session goes to the DEFAULT instance, OWNER-ONLY, with - `*` declared — it is not held, and an already-shipped session is not withdrawn for it. It used to + `*` declared — it is not held. A session already bound to the DEFAULT instance is not withdrawn + for it; one bound to ANOTHER instance moves exactly as a `*` session does — withdrawn from that + instance, rebound to the default and re-shipped whole from offset 0, owner-only. It used to HOLD the session, and `scopeuse` takes header-shaped text anywhere in a transcript (test output, a source read, assistant prose) as a read, so a fixture name froze and withdrew whole sessions. (With one instance an unnamed scope routes to the sole instance, as before.) A scope the routing diff --git a/internal/capture/unnamed_test.go b/internal/capture/unnamed_test.go index c6e58bc8..e505290d 100644 --- a/internal/capture/unnamed_test.go +++ b/internal/capture/unnamed_test.go @@ -16,6 +16,7 @@ import ( "bytes" "encoding/json" "errors" + "os" "path/filepath" "slices" "strings" @@ -356,3 +357,44 @@ func TestAReevaluatedSessionShipsOnTheNextPassAndAWithdrawnOneDoesNotLoop(t *tes } } } + +// TestAClientBoundSessionThatReadsAnUnnamedScopeMovesOwnerOnlyToTheDefault pins the path the operator's +// "treat it like `*`" decision implies for a session bound to a NON-default instance: it is WITHDRAWN +// from that instance, rebound to the default, and re-shipped WHOLE from offset 0 there, owner-only. +// Red at origin/main differently: withdrawn from client and HELD, nothing re-shipped. +func TestAClientBoundSessionThatReadsAnUnnamedScopeMovesOwnerOnlyToTheDefault(t *testing.T) { + w := loadWorld(t) + e := materialize(t, w, "cc-plain") + s := w.Sessions["cc-plain"] + path := filepath.Join(e.claude, s.Project, s.ID+".jsonl") + appendTo(t, path, betaRead) + a := newAgent(t, e, twoInstances, &fakeRunner{}, &bytes.Buffer{}) + mustRun(t, a) + if a.State.Sessions[s.ID].Instance != "client" || !e.sink.has("client", s.ID) || e.sink.has("personal", s.ID) { + t.Fatal("CONTROL: run 1 did not ship the beta-notes session to client only") + } + appendTo(t, path, unnamedRead) + sum := mustRun(t, a) + ss := a.State.Sessions[s.ID] + if sum.Withdrawn != 1 || !slices.Contains(e.sink.withdrawn["client"], s.ID) || !slices.Contains(ss.WithdrawnFrom, "client") { + t.Fatalf("not withdrawn from client: %+v sink=%v state=%v", sum, e.sink.withdrawn, ss.WithdrawnFrom) + } + // (memSink's withdrawal clears the stored POSITION, not the spooled records, so `has` cannot see it.) + if _, held := e.sink.pos["client/"+s.ID+"/main"]; held { + t.Fatal("client still holds the stream's position after the withdrawal") + } + if ss.Held || sum.Held != 0 || ss.Instance != "personal" || !slices.Contains(ss.BoundEver, "personal") { + t.Fatalf("held=%v (%s) bound=%q ever=%v — want rebound to personal, not held", ss.Held, ss.HeldReason, ss.Instance, ss.BoundEver) + } + full, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + got := spooled(t, e, "personal", s.ID, "main") + if len(got) != lineCount(full) || got[0].Src != "0" { + t.Fatalf("personal got %d records (want the whole %d-line session from offset 0)", len(got), lineCount(full)) + } + if !slices.Contains(e.sink.declared["personal/"+s.ID], "*") || !slices.Contains(ss.Declared, "*") { + t.Fatalf("not owner-only on personal: sink %v state %v", e.sink.declared["personal/"+s.ID], ss.Declared) + } +}