interplane.Get Omega
Read in your language

aien-architecture-mv

Canonical architecture for the AIEN ecosystem: flows, boundaries, ADRs, and the map from design to implementation repositories.

Brought by drakestapleton

branch main Branches Tags History

aien-architecture-mv / docs / CRUMB_PROTOCOL_RFC_0002.md

198 lines · 39529 bytes Raw Blame History Rendered
1# Crumb Protocol RFC-0002: Common Coordination Plane and Continuation Crumbs
2
3**Status:** Proposed, 2026-10-04. Decided by the operator, Drake Stapleton, through his approved design of 2026-10-04 (pasted; the paste is the decision, no separate ratification). Source of record: `~/handoffs/rfc-0002/master-spec-drake-2026-10-04.md` on the Spark.
4**Extends:** RFC-0001 v1.0.0 (`aien-spark/crumb-spec` `SPEC.md`, `ROLES.md`, frozen at `10b8251`). RFC-0001 is not changed; this document adds a storage scope, a mutation discipline, two commands and one new object. Protocol version becomes **1.1.0**.
5**Related:** `docs/CRUMB_PROTOCOL.md` (how RFC-0001 is used here), ARCH-0029 (Verified Crumbs: untouched), ARCH-0028 (receipts).
6**Implementation:** `tools/crumb/crumb.c` (C11/POSIX, no dependencies), tests in `tools/crumb/test.sh`. Code is the truth; where this text and the code differ, the difference is a bug in one of them and is named, not papered over.
7
8## In plain words (read this first)
9
10Git remembers what happened. Crumbs explain what it meant. Today every checkout folder of a repository keeps its own private notebook of "who is working where" (`.crumb.local`), so two agents working in two folders of the same repository cannot see each other. RFC-0002 moves that notebook to the one place all those folders already share (the repository's common git directory), makes writing to it safe when two agents write at the same moment, and adds two things on top: a way to ask Crumb what an unfamiliar file is for (`crumb explain`), and a compact record of where a session stopped so a fresh agent can continue without the old conversation (a Continuation Crumb).
11
12## 0. Current-state audit (2026-10-04, against aien-architecture `origin/main` `0128197`)
13
14| Item | Finding |
15|---|---|
16| Standard | RFC-0001 v1.0.0 in archived `crumb-spec` (`SPEC.md`, `ROLES.md`, `schema/crumb.schema.json`, `schema/crumb-local.schema.json`). `ROLES.md` section 3 already defines a Subagent Handoff Protocol (whisper assignments, child registers scent, completion whisper, parent verifies). |
17| Live tool | `tools/crumb/crumb.c`, 941 lines, commands seed/backfill/create/claim/update/whisper/close/sniff/list/validate. Writes `.crumb.local` **next to each `.crumb`** (line ~311) with tmp + `rename()` (line ~259). No OS lock. Targets are stored as given (basenames or relative strings), not normalized to repository-relative paths. Scents carry agent id, focus, TTL; locks carry holder, target, intent, TTL. No worktree, branch or HEAD metadata. |
18| Scope bug | Linked worktrees do not share `.crumb.local`. Observed in this very lane: a claim made in `~/workspace/hive-worktrees/rfc-0002-docs/docs` is invisible from `~/workspace/aien-architecture/docs`. |
19| Tests | `tools/crumb/test.sh`: seed idempotence, gitignore, legacy `.crumb` untouched, validate, hand edits survive reseed, claim/second-claim-blocked (exit 2)/different target, in ONE scratch repo. No worktree, concurrency, TTL, normalization or legacy-import tests. |
20| Rust | `crumb-spec/src/{lib.rs,ledger.rs}` (archived) and the older `spark-crumbs` crate write a different shape; `docs/CRUMB_PROTOCOL.md` already rules that RFC-0001 wins and legacy files are left alone. Neither is on the agents' path; the C tool is. |
21| Handoff today | Free-form Markdown in `~/handoffs/`, plus (since 2026-10-04) the `checkpoint` skill with `cc.sh` writing `~/handoffs/checkpoints/<id>.json` and a crumb whisper pointer. Works, but lives outside the repository's coordination plane. |
22| Verified Crumbs | ARCH-0029 defines `VerifiedCrumbV1` for dependency resolution; nothing implemented. Not touched by this RFC. |
23
24Discrepancy named: `docs/CRUMB_PROTOCOL.md` says agents "coordinate through crumbs" as if that were repository-wide; the implementation is worktree-local. The implementation changes; the sentence then becomes true.
25
26## 1. Versioning decision
27
28A new RFC (RFC-0002) rather than editing RFC-0001, because RFC-0001 is frozen in an archived repository and other documents cite it by number. RFC-0002 is additive: every RFC-0001 field keeps its meaning; what changes is **where** `active_scents`, `locks`, `whispers` and `history` are stored and **how** they are written. A tool that implements RFC-0002 reports protocol version `1.1.0`. A directory's committed `.crumb` is unchanged and still validates against `crumb.schema.json` 1.0.0.
29
30## 2. Common Coordination Plane
31
32### 2.1 Coordination root resolution (deterministic)
331. `CRUMB_COORD_ROOT` environment variable, if set (escape hatch for unusual layouts and tests).
342. `git config crumb.coordinationRoot`, if set in the repository.
353. `git rev-parse --git-common-dir` + `/crumb/v1`.
364. Otherwise **fail clearly** for shared operations: `no repository context: run inside a git checkout or set CRUMB_COORD_ROOT`. The tool never invents global state under a home directory. (Transition only: a directory outside any git repository may keep today's `.crumb.local` behaviour; the sniff output must say `shared coordination: none`.)
37
38### 2.2 Layout (semantic requirement; physical shape may be simplified by the implementation)
39```
40<coordination root>/
41 dirs/<repository-relative directory>.json one record per directory, same fields as RFC-0001 .crumb.local
42 agents/<agent-id>.json presence and git context of each live agent
43 continuations/<continuation-id>.json Continuation Crumbs (section 5)
44 ledger/ append-only action vectors beyond the 20-entry rolling history
45 .lock transaction lock file (section 3)
46```
47The repository root directory is keyed `_root`.
48
49### 2.3 Repository-relative identity
50A resource is identified by **repository identity + repository-relative path**. `/wt-a/native/kernel/core/infer.c` and `/wt-b/native/kernel/core/infer.c` are one resource `native/kernel/core/infer.c`. The implementation normalizes every `dir` and `target` argument through `git rev-parse --show-toplevel` of the worktree it is invoked in, resolves `.`/`..`/symlinks, and stores the relative form. Branch, worktree path, HEAD and base commit are **holder metadata**, never part of the identity. There is no per-branch namespace; a future `--allow-parallel-branch` flag may relax this explicitly, the safe behaviour is the default.
51
52### 2.4 Lock semantics
53A lock on a repository-relative target is visible from every linked worktree. A second `claim` on a held, unexpired target returns exit code 2 and prints the holder, its worktree, branch and intent. Git permitting conflicting edits is not a reason to weaken this; surfacing that overlap is the point of Crumb.
54
55### 2.5 Holder metadata
56Scents and locks carry: `agent_id` (stable session id supplied by the caller; never a PID alone), `worktree`, `branch`, `head`, `base` when cheaply known (`merge-base` with `origin/main`), `focus`/`intent`, `acquired_at`/`updated_at`, `ttl_seconds`.
57
58### 2.6 Sniff output (shared view)
59```
60CRUMB <repo-relative dir>
61shared coordination: ACTIVE root: <coordination root>
62ACTIVE AGENTS id, branch, focus, heartbeat age
63LOCKS target, holder, branch, intent, expires in
64OTHER WORKTREES path, branch, agent if any, conflicts with this directory or none
65WHISPERS priority, from, to, age, text
66CONTINUATIONS newest continuation ids whose scope touches this directory (section 5)
67```
68followed by the RFC-0001 `.crumb` summary (purpose, invariants, exports, related).
69
70### 2.7 Repository namespaces (store layout 2; crumb924, aien-sovereign-core#924)
71Section 2.3 names a resource by **repository identity + repository-relative path**, but a layout-1 store has no repository identity: two different repositories pointed at one `CRUMB_COORD_ROOT` collide on equal relative paths, and independent clones of one repository can only share coordination by sharing a flat store. Layout 2 adds the identity.
72
73- **Repository id.** `CRUMB_REPO_ID` if set, else `git config crumb.repoId`, else the `origin` remote URL normalised to lowercase `<owner>/<repo>` (`git@github.com:o/r.git`, `ssh://git@host/o/r.git`, `https://github.com/o/r(.git)(/)`). It is **never** derived from a filesystem path: a local-path or `file://` origin yields no id. Pattern `^[A-Za-z0-9][A-Za-z0-9._-]*(/[A-Za-z0-9][A-Za-z0-9._-]*)?$`, at most 200 characters; the second component may not be `dirs`, `agents`, `continuations` or `ledger` (namespace `x/dirs` would otherwise nest inside namespace `x`). An explicit id is used verbatim (write it lowercase so it matches the derived form). A bad explicit id is `REPO_ID_INVALID`, a missing one on a layout-2 root `REPO_ID_MISSING` (both exit 3).
74- **Layout.** `<root>/STORE_ID` (unchanged, section 3.1), `<root>/LAYOUT` holding exactly `crumb-coord-layout/2\n`, `<root>/.lock` (one transaction lock for the whole root), records under `<root>/repos/<repo-id>/{dirs,agents,continuations,ledger}` with the section 2.2 shapes. A `LAYOUT` with any other content is `STORE_LAYOUT_UNSUPPORTED` (exit 3, never rewritten). In layout 2 agent ids are validated (section 2.8) and used verbatim as `agents/<id>.json` (no `_` aliases), and `.crumb.local` is never imported (a present one is named on stderr).
75- **Creation is deliberate.** Only `crumb store-init [dir]` makes a root layout 2: under the root lock it creates or verifies `STORE_ID` (registered: must match, never created), then, in every mode (enforcement on or off), proves `dirs/`, `agents/` and `continuations/` empty before anything else changes: each must be absent or a real directory whose whole tree, walked with `lstat`, holds only real empty subdirectories. A layout-1 record (`*.json`) is `STORE_LAYOUT_V1_DATA`; a symbolic link, any other file, or a failure to stat, open, read or remove an entry is `STORE_LAYOUT_V1_UNPROVEN` (both exit 1, `LAYOUT` not written, nothing removed): an inspection that could not see everything is never taken for an empty store. Only after all three are proved are their empty trees removed (a failed removal also refuses), then `LAYOUT` is published once (`link(2)`, never replaced) and `repos/` created. It is idempotent on a layout-2 root. No other command creates or changes `LAYOUT`; every mutation and `check` re-reads it under the lock (`STORE_LAYOUT_CHANGED` if it changed meanwhile).
76- **Layout 1 keeps working as before** (compatibility mode, the default for every existing store, including `<git-common-dir>/crumb/v1`): same records, same paths, same output, with these deliberate changes that apply to layout 1 too: the lease generation (section 2.8), the overlap rule of section 2.8 (`claim` now also refuses when another agent holds a valid lease on an ancestor or descendant key, not only on the same key), a ttl above 315360000 seconds is refused (`bad ttl`), a renewal never lowers the `generations` counter, and `crumb check` on a used store (marker or record directories present) without `.lock` is exit 1. It is never silently reinterpreted as layout 2. A layout-2 root on which an older tool wrote flat `dirs/` or `agents/` records is `STORE_LAYOUT_MIXED`: a warning normally, exit 3 in enforcement mode.
77- **Directory record names (layout 2).** The record for key directory `d` is `dirs/<d>.json`, the repository root (`.`) is `dirs/_root.json`, and a first component that starts with `_` is stored with one more `_` (`_root/a.c` lives in `dirs/__root.json`, `_x/y/z.c` in `dirs/__x/y.json`), so a repository directory named `_root` never shares the root's record and every record name maps back to exactly one key directory. A record name no key maps to (a single leading `_` other than `_root.json`, or anything under `dirs/_root/`; an earlier layout-2 build could write such names) is `MALFORMED_RECORD` in enforcement mode (exit 1) and a stderr warning otherwise; it is never reinterpreted. Layout 1 keeps its historical mapping, where `_root/` shares `dirs/_root.json` with the root.
78- **Sharing one authority.** Independent clones of one repository (and their linked worktrees) share one lock table by pointing `CRUMB_COORD_ROOT` or `git config crumb.coordinationRoot` at the same **absolute** directory: their repository id makes them contend; different repositories with identical relative paths never collide. A relative override is anchored at the worktree top-level (not the process cwd) and canonicalised, so the cwd never changes the store; use an absolute path to share a root across clones. An absolute root is used exactly as given unless it has a `..` component, which is canonicalised the same way (realpath of the part that exists, the rest lexically), so no store path ever carries `..`.
79- **Migration rule.** A layout-1 store is never converted in place. To move a repository to a shared namespaced root: (1) pick a new, empty absolute directory; (2) in one clone: `git config crumb.coordinationRoot <dir>`, `crumb store-init .`, `git config crumb.storeId "$(crumb store-id .)"`; (3) in every other clone of every participating repository set the same `crumb.coordinationRoot` and `crumb.storeId` (and `crumb.repoId` where the origin URL is not `host/<owner>/<repo>`); (4) re-claim live work in the new root (old leases stay in the old store and are not carried over: close them there); (5) turn on enforcement (section 2.8). Reusing an old root in place requires closing every lease and moving its `dirs/`, `agents/`, `continuations/` aside first; `store-init` refuses otherwise.
80
81### 2.8 `crumb check`, lease generations and enforcement mode (crumb924)
82- **Lease generation (fencing token).** Every lease carries `generation` (u64 >= 1). Per key it strictly increases on each new acquisition (first claim, re-acquire after expiry, takeover after release); a renewal by the current valid holder keeps it. The highest generation ever issued for a key is kept in the directory record's `generations` map, which outlives the lease and never decreases (a renewal keeps a larger counter; after 2^64-1 the key is exhausted, exit 1, never wrapped). In enforcement mode a lease whose generation differs from its key's counter is `MALFORMED_LEASE` (the tool always writes them equal). `claim` prints `... generation <N>` at the end of its `CLAIMED` line.
83- **Overlap.** `claim` refuses (exit 2, the usual `BLOCKED <key> held by ...` line, suffixed `[overlapping lease on <other-key>]`) when another agent holds a valid lease on the same key, an ancestor (`src` covers `src/a.c`; `.` is the whole repository) or a descendant. An agent may nest leases inside its own. This applies in every layout, layout 1 included (section 2.7).
84- **ttl.** `claim` and `update` take a ttl of decimal seconds, at most 315360000 (3650 days; no sign, no overflow), in every mode; enforcement mode also refuses 0. It is refused before anything is written, and it is exactly the range the strict reader accepts, so a ttl the tool writes can never make its own records malformed.
85- **`crumb check <agent> <dir> <target> [--generation N] [--key K]`.** The pre-write guard (the session bridge calls it before every write into an enforced repository). Read-only: a shared `fcntl` lock on an existing `<root>/.lock` (never created) for a consistent read; nothing is created, swept or pruned. A store that is in use (layout 2, enforcement mode, or a layout-1 root holding `STORE_ID`, `dirs/` or `agents/`; every mutation creates `.lock` before any of them) but has no `.lock` is `STORE_LOCK_MISSING` (exit 1), never a HELD read without the lock; only a never-used compatibility root without `.lock` is plain absence (`REFUSED absent`). `<target>` is a file or directory relative to the repository root (`.` = all of it), resolved like `claim`. Exit 0 only when a valid lease on the target or an ancestor key is held by exactly `<agent>`, no other agent holds a valid lease on the target or an ancestor, and, with `--generation N` and `--key K`, the nearest such lease has generation N and key K: stdout `HELD <target> by <agent> key <key> generation <N> expires <ISO8601Z>`. Exit 2 otherwise, stdout `REFUSED <reason> <target> ...` with reason `absent`, `expired`, `held-by <holder>`, `key <have>!=<want>` or `generation <have>!=<want>`. Exit 1 for I/O, usage, a malformed record or lease (also outside enforcement mode), 3 store identity / layout / repository id, 4 hostile store file. A lease is valid while `now - acquired_at <= ttl_seconds` (equality is still valid; it expires at `acquired_at + ttl_seconds`). The generation lets a writer re-check, right before or after it writes, that the lease it was granted is still the current one. Generations are counted per key, so a bare number is ambiguous when the covering lease changes key (an ancestor lease can later carry the same number; found by the Lean model of this protocol): a writer re-presents the whole token, `--key K --generation N` exactly as printed on the HELD line.
86- **Enforcement mode** (`--enforce`, `CRUMB_ENFORCE=1`, or `git config crumb.enforce true`; none of them can turn it off once another turned it on). `crumb.enforce` is read with git's own boolean conversion (`git config --bool`: a valueless `enforce` key, `yes`, `on`, `1` are true); a value git refuses as a boolean, or a failed read, is an error (exit 1), never "absent". Implies strict store identity (section 3.1) and adds: layout 2 and a repository id are required (`STORE_LAYOUT_V1`, `REPO_ID_MISSING`, exit 3); no `.crumb.local` fallback outside a repository (`ENFORCE_NO_REPOSITORY`, exit 1); every directory walk, read or parse failure is an error (`STORE_UNREADABLE`, exit 1; outside enforcement the same failure is a stderr warning, never silent); a symbolic link anywhere in the record tree is refused (`REFUSED_RECORD`, exit 4), never followed and never skipped (outside enforcement an unwalked link is a stderr warning); the strict lease schema (`holder` and `session` non-empty strings, `acquired_at` exactly `YYYY-MM-DDTHH:MM:SSZ`, `ttl_seconds` an integer in 1..315360000, `generation` an integer >= 1 equal to its key's `generations` counter, a normalised key stored in its own directory record, `generations` an object of integers) is checked before anything is swept, so a malformed lease is `MALFORMED_LEASE` (exit 1) and is never pruned or taken over; agent ids must match `^[A-Za-z0-9][A-Za-z0-9_.@-]{0,159}$` and are used verbatim (`AGENT_ID_INVALID`, exit 1); an agent id names one live session: `claim`, `update` or `close` presenting the id from another session (`CRUMB_SESSION`, else `<agent>@<host>`) while that id has a live heartbeat from that session, or a live lease whose recorded `session` is that session, is refused (`BLOCKED agent <id> is live in session ...`, exit 2): an expired heartbeat never hands a live lease to another session, and only the lease's own session renews or closes it; an existing agent record must have `agent` and `session` non-empty strings, `updated_at` exactly `YYYY-MM-DDTHH:MM:SSZ` and `ttl_seconds` in 1..315360000, else `MALFORMED_RECORD` (exit 1; malformed session metadata is never treated as absent); `claim` and `update` need a positive ttl.
87- **Repository discovery fails closed** (every mode, crumb924 review B7). Whether a directory is outside git is decided only from positive evidence: `git rev-parse --show-toplevel` (C locale) exits 128, `GIT_DIR` is unset, and its whole stderr is exactly git's end-of-search diagnostic (`fatal: not a git repository (or any of the parent directories): .git`, or the mount-point form followed by the filesystem-boundary line); a substring match is not enough, because other git diagnostics name files whose names could contain those words (this includes a search stopped by `GIT_CEILING_DIRECTORIES` or a filesystem boundary), or, with `GIT_DIR` unset, git does not succeed and no `.git` entry exists in the directory or any ancestor. Only then does a command take the RFC-0001 `.crumb.local` path (section 4), or, in enforcement mode, refuse with `ENFORCE_NO_REPOSITORY`. Any other discovery failure (a malformed or unreadable `.git/config`, a `.git` file or `GIT_DIR` that names no repository, dubious ownership, a directory inside `.git` with no work tree, git not runnable inside a repository, a reported top level that cannot be resolved or does not contain the directory) is `GIT_DISCOVERY_FAILED` (exit 1) for every coordination command, before anything is read from or written to the store or `.crumb.local`: such a repository may enable enforcement through its own `.git/config`, which git could not read, so neither enforcement nor its absence can be assumed and the legacy fallback would create a second authority beside the shared store.
88- **Test clock.** `CRUMB_TEST_NOW=<epoch seconds>` replaces the wall clock for every timestamp and expiry decision. It exists only so the test suite can hit the expiry boundary exactly; never set it in production.
89- **Still advisory at the filesystem.** Crumb cannot stop a process that writes without asking; enforcement means the agent runtimes' write gate (the swarm bridge) asks `crumb check` and blocks on anything but exit 0.
90
91## 3. Mutation discipline (transaction safety)
92
93tmp + `rename()` prevents torn files but not lost updates (A and B both read version 10, both write version 11, one lock vanishes). Every mutation of the shared store runs:
94```
95acquire fcntl(F_SETLKW, F_WRLCK) on <root>/.lock
96read current record(s) -> prune expired scents and locks -> validate -> apply mutation
97write temporary file -> fsync(tmp) -> rename(tmp, final) -> fsync(directory) -> release the lock
98```
99The **transaction lock** is an OS lock held for milliseconds and protects the database. The **Crumb resource lock** is the advisory claim in `locks[]`, held for minutes or hours and meaning "an agent owns this target". They are different things and are never confused in code or output.
100
101### 3.1 Store identity and hostile store files (synapse-coord compatibility, [#234](https://github.com/aien-spark/aien-architecture/issues/234))
102Two agents pointed at two different coordination roots each believe they hold the same lock; nothing in section 2.1 stops that. A coordination root therefore carries a **store identity**, byte-compatible with the Rust `synapse-coord` crate ([synapse#15](https://github.com/aien-spark/synapse/issues/15)), and every reader refuses store files it cannot read safely ([synapse#58](https://github.com/aien-spark/synapse/issues/58)).
103
104- **Marker.** `<coordination root>/STORE_ID` holds exactly `crumb-coord-store-id/1 <32 lowercase hex>\n` (56 bytes), drawn from `/dev/urandom` and written under the transaction lock (tmp, `fsync`, `link(2)`, directory `fsync`), so two first writers cannot both win. Either tool may create it; both read it the same way, and neither rewrites an existing marker.
105- **Registration.** The expected id is `CRUMB_EXPECT_STORE_ID` when set and non-empty, else `git config crumb.storeId` (one value for every linked worktree of the repository). `crumb store-id [dir]` prints the store's id and is the onboarding step: `git config crumb.storeId "$(crumb store-id .)"`. The Rust side takes the same id as `--expect-store-id`.
106- **Three modes.**
107 1. *Unregistered (compatibility, the default).* No expected id. Every command works as before; the first mutation creates the marker, and while a marker exists but no id is registered each coordination command prints one stderr line, `STORE_UNREGISTERED (dry run): ... register it: git config crumb.storeId <id>`. Standard output and every `dirs/` and `agents/` record are byte-identical to the pre-#234 tool (apart from the lease generation added by section 2.8: the ` generation <N>` suffix of `CLAIMED`, each lease's `generation`, the record's `generations` map; and apart from the further deliberate behaviour changes listed under "Layout 1 keeps working as before" in section 2.7 and the repository-discovery rule of section 2.8, which change exit codes and refusals, not the record format).
108 2. *Registered.* An expected id is set. Before any read or write, and again under the transaction lock before a mutation, the root's marker must match. It never creates a marker.
109 3. *Strict.* `crumb --strict <command>` or `CRUMB_STRICT_STORE_ID=1` additionally refuses an unregistered root before creating anything (`store-id` stays allowed, for onboarding).
110- **Migration.** Run unregistered and watch for the dry-run line; register each repository with `git config crumb.storeId`; turn on strict mode for onboarded swarm agents so a misconfigured root fails closed. The legacy `.crumb.local` path outside a repository (section 4) is unaffected.
111- **Exit codes.** `2` is unchanged (held by another agent). `3` is a store identity refusal, named `STORE_ID_MISMATCH` (the root is another store: split coordination roots), `STORE_ID_MISSING` (an id is expected but the root has no marker), `STORE_ID_UNREADABLE`, `STORE_ID_CONFIG_INVALID` (the configured id is not 32 lowercase hex) or `STORE_UNREGISTERED` (strict mode). `4` is `REFUSED_RECORD`: a store file is a FIFO, socket, device, directory or symbolic link, sits under a symlinked directory, or is larger than the cap. The message names the file and says to fix or move it aside; the file is never replaced.
112- **Reads and caps.** Every store file `crumb` reads (records, continuations, `STORE_ID`; `.lock` is opened the same way but never read) is opened `O_NOFOLLOW | O_NONBLOCK` after an `lstat`, checked again with `fstat`, and read up to a cap: 1 MiB (1048576 bytes) for a record, 4096 bytes for the marker. A record over 1 MiB is refused on write too, so the tool never writes what it would refuse to read. Record walks do not descend into symlinked directories. Every file `crumb` opens goes through one opener (`crumb_open`): an empty path or one with a `..` component is refused before the open (`PATH_REFUSED`, exit 1; configured roots, `HOME` and git's paths are canonicalised where they are resolved, so this is a backstop), `O_CLOEXEC` is always set, and `O_NOFOLLOW` too, except for the working tree's own files (`.crumb`, `.gitignore`, `.crumbignore`, git's `info/exclude`, `docs/crumbs/BACKFILL.md`), lane reports, `/dev/urandom` and a directory opened only to `fsync` it. The RFC-0001 `.crumb.local` is read like a store record (`O_NOFOLLOW | O_NONBLOCK`, `lstat` and `fstat`, a 64 MiB cap): a symbolic link, FIFO or other special file there is `REFUSED_RECORD` (exit 4), never read through.
113- **Independence from the mission board.** These ids name one repository's coordination store. A swarm mission board ([synapse#83](https://github.com/aien-spark/synapse/issues/83)) has its own root and is not one of these stores; registering a repository never registers, joins or reads a board, and a board never satisfies `crumb.storeId`.
114
115## 4. Legacy `.crumb.local` (RFC-0001 physical form)
116
117- New writes go only to the shared store (inside a repository).
118- `.crumb.local` is written only for a directory positively established to be outside any repository; a repository-discovery error is `GIT_DISCOVERY_FAILED` (exit 1), never a fallback (section 2.8).
119- Reads merge: shared store first, then any `.crumb.local` present in the invoking worktree; an unexpired legacy scent or lock is shown with `legacy:` and an `imported_from: <worktree path>` provenance. Legacy state never overrides a newer shared record for the same key.
120- `crumb seed` / first shared write in a directory imports an existing `.crumb.local` once (provenance kept) and leaves the file on disk; nothing is deleted.
121- `.gitignore` handling for `.crumb.local` stays, for the transition and for non-repository directories.
122- Scope: `.crumb.local` and the shared store are single-machine scratch state, not a coordination channel between agents; cross-agent claims go through the issue tracker and draft pull requests (see Scope in `docs/CRUMB_PROTOCOL.md`).
123
124## 5. Continuation Crumb (`ContinuationCrumbV1`)
125
126Purpose: checkpoint the meaningful **state of work** when a session ends so another agent, in any worktree, can continue. It is not a transcript, not a summary of the chat, and not an oracle. Schema: `docs/crumbs/continuation-crumb.schema.json`. Reference implementation today: the `checkpoint` skill (`cc.sh`), whose record is this schema's `acr_version: 1` precursor; it moves into `<root>/continuations/` as `crumb checkpoint` / `crumb resume` (section 7).
127
128### 5.1 Shape (smallest stable set)
129```
130identity id, version, created_at, created_by (agent id), reason, supersedes
131repository remote, branch, base, head, worktree (one entry per repository in scope)
132mission objective, milestone, definition_of_done[] (verbatim; may not be softened at checkpoint time)
133state[] {tag: PROVEN|PARTIAL|BLOCKED|ASSUMED|OPEN, claim, evidence[], blocker, note}
134evidence commits[], prs[], tests[] {name, command, result, where}, receipts[], golden_values[] {name, value, source}
135execution current, next[] {id, task, depends_on[], gate}, backlog[]
136coordination scope[] (.crumb paths this record is about), owned[], other_owned[] {who, paths}, do_not_touch[]
137operator approval_required[], hardware_rules[], destructive_rules[], standing_preferences[]
138resume validate_first[], first_action, bootstrap (<= 700 chars)
139revalidation status UNVERIFIED|NEEDS_REVIEW|VERIFIED, checked_at, checked_by, findings[] {field, result: CONFIRMED|STALE|SUPERSEDED|UNKNOWN, note}
140```
141Rules enforced by the tool, not by goodwill: a `PROVEN` item without at least one evidence reference is rejected; a `BLOCKED` item without a named blocker is rejected; `definition_of_done` must be non-empty; the record is rejected above a size budget (~4000 tokens of JSON) because size means history crept in.
142
143### 5.2 Referential, not duplicative
144Evidence entries are references the next agent follows: `commit:<sha>`, `pr:<repo>#<n>`, `receipt:<path>`, `test:<name>`, `crumb:<dir>/.crumb`. Nothing Git already knows (diffs, authorship, chronology) is copied in. The `scope[]` list names the committed `.crumb` files that describe the code involved; `crumb explain` and `crumb sniff` surface a continuation whenever its scope touches the directory being asked about.
145
146### 5.3 Epistemic boundary
147`PROVEN` means "a receipt exists at this reference against this commit", not "the previous agent was confident". Where a receipt is an `EvidenceReceiptV1` (ARCH-0028) or, in future, a `VerifiedCrumbV1` (ARCH-0029), the reference points at it; this RFC does not redefine either object.
148
149## 6. Lifecycle additions
150
151Normal work (RFC-0001): SNIFF -> LEASE -> EXECUTE -> WHISPER.
152Session end: SNIFF -> **QUIESCE** (no new branches, decisions or workers) -> **CHECKPOINT** (write the record from the machine state, not from memory) -> **VERIFY** (`check` passes) -> **WHISPER** (high-priority pointer `Session continuing at <id>` in the root and each scope directory) -> **RELEASE** (close every held lock).
153Fresh session: SNIFF -> **RESOLVE CONTINUATION** (newest id from the whisper or `continuations/LATEST`) -> **REVALIDATE** (section 6.1) -> LEASE (re-claim `owned[]`; exit 2 means someone else holds it: stop) -> RESUME (`first_action`).
154
155### 6.1 Revalidation (mandatory)
156The tool compares each recorded repository entry with the live repository: fetch; HEAD moved? pinned commit still an ancestor of `origin/main` (else SUPERSEDED)? evidence commits present? receipt files present? who holds locks now? It writes machine findings into `revalidation.findings`. The agent then does what the tool cannot: re-check the top blocker at its implementation site, re-read the cheapest critical receipt, and record a verdict per stale field. Nothing in the record is presented as current until this has run.
157
158## 7. Commands (CLI stays small)
159
160Existing: `sniff`, `claim`, `update`, `whisper`, `close`, `list`, `seed`, `backfill`, `create`, `validate` (now operating on the shared store).
161New:
162- `crumb explain <file-or-dir>`: assembles, in this order and nothing more: nearest `.crumb` (purpose, layer, invariants, exports, related); inherited invariants from parent `.crumb` files up to the root; shared coordination for that directory (agents, locks, whispers); the last 10 commits touching the path (`git log --oneline -- <path>`) plus any commit the `.crumb` or a continuation names as significant; evidence references found in `.crumb` `extensions` and in continuations whose scope touches the path; the newest continuation touching the path with its `state` lines. Output is plain text sections of bounded size (defaults: 10 commits, 5 whispers, 1 continuation) so an LLM can read it without a large payload. Answers: what is this, why, what rules, how did it get here, what is proven, who is here now, where did prior work stop.
163- `crumb checkpoint <agent> [--reason R]`: creates `<root>/continuations/<id>.json` from the template with repository entries filled from git, prints the path for the agent to complete, then `crumb checkpoint --seal <id>` runs the checks, stamps `sealed_at` and sha256, writes the Markdown rendering, updates `LATEST`, leaves the whisper.
164- `crumb resume <id>`: prints the record, runs revalidation, records findings, prints the bootstrap text.
165
166Why checkpoint/resume may start outside the C binary: the logic exists today as `cc.sh` (POSIX sh + `jq`) and is being used; porting it to C is mechanical and planned, but landing the shared store first keeps the C change reviewable. Until the port, `cc.sh` resolves its store exactly as section 2.1 does, so records already land in `<root>/continuations/`. That is the precise, implementation-ready continuation for deliverable 14/15, not a TODO.
167
168## 8. Scope boundary
169
170This RFC closes the gap for **all linked worktrees of one repository on one filesystem**. Independent clones (another machine, CI, another Spark node) do not share a common git directory; on one filesystem they share coordination only through an explicitly configured shared root with layout 2 (section 2.7), and across machines they remain out of scope. The store is reached through one small internal interface (`store_read`, `store_write`, `store_lock`, `store_root`) so a later `DaemonStore` or distributed backend can replace `GitCommonStore` without touching command code. No transport is chosen now.
171
172## 9. Tests (the feature is not done until these run)
173
174| # | Test | Where | Result (2026-10-04) |
175|---|---|---|---|
176| T1 | Cross-worktree visibility: A claims `src/runtime.c`, B's sniff from worktree B shows it | `tools/crumb/test.sh` | PASS (`make -C tools/crumb test`, 0 FAIL) |
177| T2 | Cross-worktree conflict: B's claim of the same target exits 2 | same | PASS (`make -C tools/crumb test`, 0 FAIL) |
178| T3 | Release: A closes, B's claim succeeds | same | PASS (`make -C tools/crumb test`, 0 FAIL) |
179| T4 | Independent targets: both claims survive | same | PASS (`make -C tools/crumb test`, 0 FAIL) |
180| T5 | Concurrent mutation: 8 parallel distinct claims all survive; 8 same-target claims yield exactly one success | same | PASS (`make -C tools/crumb test`, 0 FAIL) |
181| T6 | TTL/crash: expired lock pruned, reclaimable | same | PASS (`make -C tools/crumb test`, 0 FAIL) |
182| T7 | Path normalization: two absolute worktree paths -> one lock identity | same | PASS (`make -C tools/crumb test`, 0 FAIL) |
183| T8 | Legacy `.crumb.local` read/import with provenance, never overriding newer shared state | same | PASS (`make -C tools/crumb test`, 0 FAIL) |
184| T9 | Continuation revalidation: checkpoint at C, advance the repo, resume reports STALE/SUPERSEDED and status NEEDS_REVIEW | `tools/crumb/test-continuation.sh` | PASS (8 checks; STALE repo HEAD + NEEDS_REVIEW; SKIP prints NOT_RUN where jq or cc.sh is absent) |
185| E1 | `crumb explain`: every section header, nearest `.crumb`, commits, locks and whispers, continuation surfaced by `owned_paths` and by `scope`, unrelated continuation ignored, missing path fails | `tools/crumb/test.sh` | PASS (15 checks) |
186| N1-N31 | Sections 2.7/2.8: store-init, cross-repository (same relative path, shared root), two independent clones (8-way race: exactly one holder), linked worktrees, overlap, generations and `check --generation`, expiry boundary (`CRUMB_TEST_NOW`), check absent/expired/held-by and read-only, agent id validation, aliases and duplicate sessions, malformed lease schema, inaccessible directory, STORE_ID mismatch, hostile record, legacy fallback refused, layout 1 never reinterpreted, repository id rules, relative root, concurrent and overlapping claims, key-qualified fencing token, Hermes session ids (N19); review fixes N20-N27: symlinked record directories refused, `_root/` record mapping, per-session lease ownership and strict agent records, missing `.lock`, ttl range, generation high-water mark, git booleans for `crumb.enforce`, repository id first character; N28: repository-discovery failure (malformed and unreadable `.git/config`, dangling `.git` file, inside `.git`) is `GIT_DISCOVERY_FAILED` for claim/update/whisper/close/check/sniff/list with no `.crumb.local` and a byte-identical shared store, with genuine non-repository and `GIT_CEILING_DIRECTORIES` fallback controls; N29: `store-init` without enforcement refuses a layout-1 root whose records sit in unreadable `dirs/`+`agents/`, an unreadable descendant directory, behind a descendant or top-level symbolic link, or beside a non-record file (exit 1, no `LAYOUT`, records byte-identical and the lease still blocking once restored; permission cases NOT_RUN as root), with an emptied-root control; N30: a symlinked or FIFO `.crumb.local` (fallback and layout-1 import) is `REFUSED_RECORD` (exit 4), link, target and store untouched, with a regular-file control; N31: a configured root with a `..` component is canonicalised (`store-init` names the canonical root and creates no stray directory), with same-store and symlinked-root controls | `tools/crumb/test-namespace.sh` | 151 checks (results in the merging PR; N28 against `ce562675`: 7 of 11 fail, the 4 that pass are setup and the non-repository controls; negative control against `c9dd6f37`: 66 of the first 75 fail, the 9 that pass are controls of unchanged behaviour; the 5 N18 checks need `--key`, which main lacks; N20-N27 against `d70b7d58`: see the merging PR; N29 against `0f32e086`: 8 of 10 fail, the 2 that pass are the top-level-symlink case its scan already refused; N30-N31 against `f2df4b4d`: 5 of 8 fail, the 3 that pass are the regular-file, same-store and symlinked-root controls) |
187
188Results are reported PASS / FAIL / NOT_RUN per test in the merging PR; nothing unrun is called PASS.
189
190## 10. Agent bootstrap rule (global, one paragraph)
191
192> Before modifying an unfamiliar repository path, inspect the applicable Crumb (`crumb explain <path>`, then `crumb sniff`). Respect its invariants and shared locks. Follow related Crumbs, Git history, evidence and active continuation state until the purpose of the code is understood. Do not rely on undocumented assumptions from previous sessions. Load context on demand; do not expect the whole architecture in your window up front.
193
194Workflow detail: `docs/crumbs/AGENT_WORKFLOW.md`.
195
196## 11. Principle (keep the layers apart)
197
198Git is the historical substrate. `.crumb` files are the semantic graph. Receipts are the proof layer. Continuation Crumbs are resumable execution state. The shared coordination plane is the live concurrency layer. None of them takes over the job of another: no history copied into crumbs, no claims accepted without receipts, no coordination state treated as architecture, no continuation treated as truth before revalidation.