merged48d8027553f32d37 #381 · opened 2026-11-07 05:22 UTC · closed 2026-11-07 07:20 UTC · merged 2026-11-07 07:20 UTC
Imported from GitHub aien-dev/aien-architecture-mv#381, by drakestapleton
Base c9dd6f37b6b83fad5e45662ee6ab423a8b74551d · Head 8261a7314def4b3b85977954713690f2043c4aca
Merged on GitHub as 4c195641588b356bbf698942f1994e13b3c44370; reachable from main bccab5ea7a17be6c9ab30b1bd05db4898a4601be (observed 2026-11-18T16:37:24Z)
Refs aien-dev/aien-sovereign-core-mv#924, #587; Linear DRA-97; ledger L900.
What changes (tools/crumb/crumb.c, docs)
Layout 2 store: <root>/LAYOUT (crumb-coord-layout/2), records under <root>/repos/<repo-id>/{dirs,agents,continuations,ledger}; root STORE_ID unchanged. Repo id = CRUMB_REPO_ID > git config crumb.repoId > origin URL <owner>/<repo> (host URLs only, never the path). crumb store-init creates layout 2 deliberately and refuses a root holding flat records, and proves the old flat record dirs empty in every mode before publishing LAYOUT (desk review B8, f2df4b4d). Layout-1 stores are never reinterpreted as layout 2, but they are not "unchanged": the overlap rule, TTL range, strict schema in enforcement and the missing-lock refusal (RFC-0002 2.8) apply to them too. Relative override roots anchor at the worktree top-level.
crumb check <agent> <dir> <target> [--generation N] [--key K]: read-only under the store lock (creates/prunes nothing); exit 0 only when a valid lease on target or an ancestor is held by exactly <agent> and no other agent holds one; 2 for absent / expired / held-by / key or generation mismatch; 1 I/O, usage, malformed; 3 store identity / layout / repo id; 4 hostile file.
Lease generation fencing token (per key, strictly increasing on each new acquisition, kept on renewal); claim prints it; claims refuse overlap with another agent's valid lease on the key, an ancestor or a descendant. The token is (key, generation): the Lean model of the protocol (crumb924 evidence proof-lean, obs_number_only_check_accepts) showed a bare number can match a later ancestor lease; --key closes it (test N18).
Enforcement mode (--enforce, CRUMB_ENFORCE=1, git config crumb.enforce true): strict registered STORE_ID, layout 2 + repo id, no .crumb.local fallback, every opendir/read/parse failure exit 1 (no silent empty state), strict lease schema (malformed = exit 1, never pruned or taken over), agent ids ^[A-Za-z0-9][A-Za-z0-9_.@-]{0,159}$ used verbatim (no _ aliases), one live session per agent id, failed dir sync is an error.
Desk review of #381 at 0f32e086 (MERGE_AFTER_FIX, B8 + G1): B8 store-init fix by the queen's CrumbInitFix (f2df4b4d, cherry-picked as asked; its report: hive/queen/mission/desk/crumb-init-fix/REPORT.md). G1 CodeQL: 06c94f59 (bounded writes), 29c8f5eb (N28 test hardening), b8e52719 (one checked opener), 8261a731 (store-init emptiness proof walks by descriptor: openat/unlinkat on the parent descriptor, after CodeQL flagged the lstat-then-rmdir in f2df4b4d as cpp/toctou-race-condition). Details in the CodeQL section below.
make -C tools/crumb test at 8261a731: 343 PASS 0 FAIL 0 NOT_RUN, rc 0 (lead rerun, receipt lead-make-test-8261a731.log with HEAD and binary sha256 header). At 0f32e086: 325 PASS (test.sh 153, test-continuation.sh 8, test-hostile.sh 31, test-namespace.sh 133).
x86_64 build like CI (x86_64-linux-gnu-gcc 13.3, -Wall -Wextra -Werror) rc 0; all 4 suites on that binary under qemu-user: 343 PASS 0 FAIL.
Negative control for the G1 tests: test-namespace.sh at b8e52719 against the f2df4b4d binary: 5 new checks FAIL (symlinked/FIFO .crumb.local, link reads, .. root), the 3 controls PASS. B8 (N29): 8 of 10 FAIL on 0f32e086 (CrumbInitFix report). Baseline main c9dd6f37 in this worktree: 192 PASS 0 FAIL.
test-namespace.sh covers: cross-repository same relpath on a shared root (no collision), two independent clones of one repo (8-way concurrent claim race: exactly one exit 0), linked worktrees, overlap (ancestor/descendant), generations and check --generation/--key, expiry boundary (CRUMB_TEST_NOW: ttl valid, ttl+1 expired), check absent/expired/held-by and read-only (store byte-identical), agent id validation, aliases and duplicate live session, malformed lease schema, chmod-000 store dir, STORE_ID mismatch (exit 3), hostile record (exit 4), legacy fallback refused, layout 1 never reinterpreted, repo id rules, relative root, Hermes session id with _.
Negative control: test-namespace.sh against main's binary (git archive c9dd6f37): 9 PASS / 66 FAIL of the first 75 (the 9 are controls of unchanged behaviour); N18 keyed-token checks FAIL against 0f2c9b8 (pre --key).
Gates: tests/gates/run.sh crumb-verify rc 0 at 8261a731 (28 crumbs current; receipt gate-crumb-verify-8261a731.log), crumb-tool-test rc 0 (343/0) at b8e52719. x86_64-linux-gnu-gcc -Wall -Wextra -Werror build rc 0 at 8261a731. Older: doctrine, zero-legacy, capreg, script-tests rc 0 at 0f2c9b8 (omc pinned 734f0a39...).
Lean model (separate evidence, not this repo): mutual exclusion, check soundness, fencing monotonicity/stale-token refusal, expiry boundary; all lean_verify trust standard.
NOT_RUN
qualification-status gate (needs ../omega sibling); CodeQL on 8261a731 until hosted CI reports (on b8e52719 it went from 25 new alerts to 1, the toctou fixed in 8261a731) (it cannot run on the Spark); AIEN Alpha (tag-only job, SKIPPED); checkpoint/resume against a layout-2 store; chmod-000 test as root.
Evidence: Spark ~/work/crumb924/evidence/crumb-c-g1/ (lead-make-test-8261a731.log, gate-crumb-verify-8261a731.log, gate-crumb-verify.log, gate-crumb-tool-test.log, x86_64-qemu-tests.log, negative-control-f2df4b4d.log); older heads in evidence/crumb-c/ (lead-make-test-b7b.log = 0f32e086; lead-gate-crumb-verify.log = d70b7d5).
Follow-up after merge: bump core crumb.lock to the merge sha (separate PR).
CodeQL on this PR: what changed and why (G1)
Threat model.crumb is a local CLI with no privilege boundary: it runs as the operator, and every path it opens derives from the store the operator selected (CRUMB_COORD_ROOT, git config crumb.coordinationRoot, the directory argument, HOME), from git's own output, or from names read from that store. The 20 cpp/path-injection alerts follow exactly that intended flow (environment/argv to file open). They are not vulnerabilities, and this PR does not say they were. The 5 cpp/unbounded-write alerts were sprintf into buffers malloc'd from the input lengths: they could not overflow, but nothing in the code checked that.
Change.
Bounded writes. All 5 sprintf calls are gone. Paths are now built with xsnprintf: snprintf with the allocated size and a checked return. An encoding error or truncation is an internal error (exit 1), never a silently cut path. The other heap path formats (pjoin, temp names, agent@host, the cc.sh path) use the same helper. root_canon no longer formats at all (see below).
One checked opener. Every former open()/fopen() call (slurp, fcreate, read_bounded, create_temp, /dev/urandom, fsync_dir, root_lock, lane reports) now goes through crumb_open / crumb_open_follow, and none is left in crumb.c. The opener:
refuses an empty path or a path with a .. component before opening anything (PATH_REFUSED, exit 1, never treated as "absent");
always adds O_CLOEXEC;
adds O_NOFOLLOW except where a final link must be followed: working-tree files git can track as links, git's info/exclude, lane reports, /dev/urandom, and the directory opened only to fsync it (that open is now O_DIRECTORY; a store root named through a symlink still works);
opens with openat(AT_FDCWD, ...).
The store-file sites keep their existing O_NOFOLLOW|O_NONBLOCK + lstat/fstat behaviour. New: fresh temp files from fcreate refuse a planted link, and .crumb.local (RFC-0001 fallback, layout-1 import, list) is read with the store-record reader. A symlinked or FIFO .crumb.local is REFUSED_RECORD (exit 4). Before, it was read through the link, and a FIFO hung.
No accepted input is refused... is resolved where paths are resolved, so the opener's refusal is a backstop that well-formed input never reaches:
a relative root was already canonicalised; an absolute root with a .. component now is too (realpath of the part that exists, the rest lexically);
an absolute root without .. is still used exactly as given;
CRUMB_COORD_ROOT outside a repository, HOME (backfill) and git's --git-path output (../../.git/info/exclude from a subdirectory) are canonicalised the same way.
About the alerts closing.openat is not a sink in CodeQL's TaintedPath query, which models fopen/open and their wrappers. So the path-injection alerts close because the opens were routed through one place, not because CodeQL proved anything new. Please judge the change on what it adds: one opener that refuses .. and applies O_NOFOLLOW (where a site does not need to follow) and O_CLOEXEC to every open. That is uniform hardening, not a fix for an exploitable bug. Tests: test-namespace.sh N30 (symlinked/FIFO .crumb.local refused, link/target/store untouched, regular-file control) and N31 (.. in CRUMB_COORD_ROOT / crumb.coordinationRoot canonicalised, same-store and symlinked-root controls). Against the unfixed f2df4b4d binary, 5 of the 8 new checks fail and the 3 controls pass. The N28 GIT_DIR/enforce checks now assert that .crumb.local is byte-identical, instead of the absence of a file that claim never creates.
Independent review rounds (profile reviewer, gpt-6-astra; verdicts in the crumb924 lead dir reviews/)
Round 1 at d70b7d58: B1 symlinked record dirs skipped, B2 _root/ record collision, B3 cross-session renew after heartbeat expiry, B4 check without .lock, B5 TTL accepted beyond the reader's range, B6 counter could decrease, N1-N3. Fixed in 2506ac54 + ce562675 (tests N20-N27; negative control 30 FAIL on d70b7d58).
Round 2 at ce562675: B7 repository-discovery failure fell back to legacy .crumb.local. Fixed in 9caffb1c (GIT_DISCOVERY_FAILED in every mode before any write; N28, 11 checks).
Round 3 at 9caffb1c: B7 PARTIAL (the non-repository diagnostic was matched as a substring, so a file name or GIT_DIR containing the words still fell back). Fixed in 0f32e086 (whole-diagnostic match, GIT_DIR unset; +3 checks, 2 FAIL on 9caffb1c).
Round 4 at 0f32e086: no blocking defect (signed verdict COMMENT; reviews/arch-crumb-c.verdict.md in the crumb924 lead dir).
Desk exact-PR review #381 at 0f32e086: MERGE_AFTER_FIX, B8 + G1 (hive/queen/mission/desk/aien-architecture-mv-381.verdict.txt). Fixed at 8261a731 as above; needs a fresh exact-head review.
Agent: crumb924 (Hermes worker, claude-opus-5-5, anthropic), lead of ledger L900; subagents crumb924-crumb-c, crumb924-g1, crumb924-telemetry, crumb924-session-bridge, crumb924-omp, crumb924-lean (same model). B8 commit f2df4b4d by CrumbInitFix (omp subagent of omp-queen-spark).
github-advanced-security[bot] commented on tools/crumb/crumb.c line 714 on 2026-11-07 05:23 UTC
CodeQL / Unbounded write
This 'call to sprintf' with input from an environment variable may overflow the destination.
This 'call to sprintf' with input from string read by fread may overflow the destination.
github-advanced-security[bot] commented on tools/crumb/crumb.c line 789 on 2026-11-07 05:23 UTC
CodeQL / Uncontrolled data used in path expression
This argument to a file access function is derived from user input (an environment variable) and then passed to create_temp(tmp), which calls open(__file).
This argument to a file access function is derived from user input (string read by fread) and then passed to create_temp(tmp), which calls open(__file).
github-advanced-security[bot] commented on tools/crumb/crumb.c line 936 on 2026-11-07 05:23 UTC
CodeQL / Uncontrolled data used in path expression
This argument to a file access function is derived from user input (an environment variable) and then passed to read_bounded(path), which calls open(__file).
This argument to a file access function is derived from user input (string read by fread) and then passed to read_bounded(path), which calls open(__file).
github-advanced-security[bot] commented on tools/crumb/crumb.c line 877 on 2026-11-07 05:23 UTC
CodeQL / Unbounded write
This 'call to sprintf' with input from an environment variable may overflow the destination.
This 'call to sprintf' with input from string read by fread may overflow the destination.
github-advanced-security[bot] commented on tools/crumb/crumb.c line 1100 on 2026-11-07 05:23 UTC
CodeQL / Uncontrolled data used in path expression
This argument to a file access function is derived from user input (an environment variable) and then passed to ident_gate(store), which calls ensure_marker_locked(store), which calls publish_once(dir), which calls fsync_dir(dir), which calls open(__file).
This argument to a file access function is derived from user input (string read by fread) and then passed to ident_gate(store), which calls ensure_marker_locked(store), which calls publish_once(dir), which calls fsync_dir(dir), which calls open(__file).
github-advanced-security[bot] commented on tools/crumb/crumb.c line 1194 on 2026-11-07 05:23 UTC
CodeQL / Uncontrolled data used in path expression
This argument to a file access function is derived from user input (an environment variable) and then passed to ident_gate(store), which calls ensure_marker_locked(store), which calls publish_once(dir), which calls fsync_dir(dir), which calls open(__file).
This argument to a file access function is derived from user input (string read by fread) and then passed to ident_gate(store), which calls ensure_marker_locked(store), which calls publish_once(dir), which calls fsync_dir(dir), which calls open(__file).
github-advanced-security[bot] commented on tools/crumb/crumb.c line 1206 on 2026-11-07 05:23 UTC
CodeQL / Unbounded write
This 'call to sprintf' with input from a command-line argument may overflow the destination.
This 'call to sprintf' with input from an environment variable may overflow the destination.
This 'call to sprintf' with input from an environment variable may overflow the destination.
This 'call to sprintf' with input from string read by fread may overflow the destination.
github-advanced-security[bot] commented on tools/crumb/crumb.c line 1208 on 2026-11-07 05:23 UTC
CodeQL / Unbounded write
This 'call to sprintf' with input from a command-line argument may overflow the destination.
This 'call to sprintf' with input from an environment variable may overflow the destination.
This 'call to sprintf' with input from an environment variable may overflow the destination.
This 'call to sprintf' with input from string read by fread may overflow the destination.
github-advanced-security[bot] commented on tools/crumb/crumb.c line 1343 on 2026-11-07 05:23 UTC
CodeQL / Uncontrolled data used in path expression
This argument to a file access function is derived from user input (an environment variable) and then passed to rec_load(path), which calls read_bounded(path), which calls open(__file).
This argument to a file access function is derived from user input (an environment variable) and then passed to rec_load(path), which calls read_bounded(path), which calls open(__file).
This argument to a file access function is derived from user input (string read by fread) and then passed to rec_load(path), which calls read_bounded(path), which calls open(__file).
github-advanced-security[bot] commented on tools/crumb/crumb.c line 1565 on 2026-11-07 05:23 UTC
CodeQL / Uncontrolled data used in path expression
This argument to a file access function is derived from user input (an environment variable) and then passed to ident_gate(store), which calls ensure_marker_locked(store), which calls publish_once(dir), which calls fsync_dir(dir), which calls open(__file).
This argument to a file access function is derived from user input (string read by fread) and then passed to ident_gate(store), which calls ensure_marker_locked(store), which calls publish_once(dir), which calls fsync_dir(dir), which calls open(__file).
github-advanced-security[bot] commented on tools/crumb/crumb.c line 1575 on 2026-11-07 05:23 UTC
CodeQL / Uncontrolled data used in path expression
This argument to a file access function is derived from user input (a command-line argument) and then passed to read_bounded(path), which calls open(__file).
This argument to a file access function is derived from user input (an environment variable) and then passed to read_bounded(path), which calls open(__file).
This argument to a file access function is derived from user input (an environment variable) and then passed to read_bounded(path), which calls open(__file).
This argument to a file access function is derived from user input (string read by fread) and then passed to read_bounded(path), which calls open(__file).
github-advanced-security[bot] commented on tools/crumb/crumb.c line 2259 on 2026-11-07 05:23 UTC
CodeQL / Uncontrolled data used in path expression
This argument to a file access function is derived from user input (an environment variable) and then passed to env_store(root), which ends up calling open(__file).
github-advanced-security[bot] commented on tools/crumb/crumb.c line 1822 on 2026-11-07 05:23 UTC
CodeQL / Uncontrolled data used in path expression
This argument to a file access function is derived from user input (an environment variable) and then passed to env_store(root), which ends up calling open(__file).
github-advanced-security[bot] commented on tools/crumb/crumb.c line 2942 on 2026-11-07 05:23 UTC
CodeQL / Uncontrolled data used in path expression
This argument to a file access function is derived from user input (an environment variable) and then passed to ident_gate(store), which calls ensure_marker_locked(store), which calls publish_once(dir), which calls fsync_dir(dir), which calls open(__file).
This argument to a file access function is derived from user input (string read by fread) and then passed to ident_gate(store), which calls ensure_marker_locked(store), which calls publish_once(dir), which calls fsync_dir(dir), which calls open(__file).
github-advanced-security[bot] commented on tools/crumb/crumb.c line 2943 on 2026-11-07 05:23 UTC
CodeQL / Uncontrolled data used in path expression
This argument to a file access function is derived from user input (an environment variable) and then passed to ident_gate(store), which calls ensure_marker_locked(store), which calls publish_once(dir), which calls fsync_dir(dir), which calls open(__file).
This argument to a file access function is derived from user input (string read by fread) and then passed to ident_gate(store), which calls ensure_marker_locked(store), which calls publish_once(dir), which calls fsync_dir(dir), which calls open(__file).
github-advanced-security[bot] commented on tools/crumb/crumb.c line 2999 on 2026-11-07 05:23 UTC
CodeQL / Uncontrolled data used in path expression
This argument to a file access function is derived from user input (an environment variable) and then passed to ident_gate(store), which calls ensure_marker_locked(store), which calls publish_once(dir), which calls fsync_dir(dir), which calls open(__file).
This argument to a file access function is derived from user input (string read by fread) and then passed to ident_gate(store), which calls ensure_marker_locked(store), which calls publish_once(dir), which calls fsync_dir(dir), which calls open(__file).
github-advanced-security[bot] reviewed (COMMENTED) on 2026-11-07 05:23 UTC
github-advanced-security[bot] commented on tools/crumb/crumb.c line 2883 on 2026-11-07 05:23 UTC
CodeQL / Uncontrolled data used in path expression
This argument to a file access function is derived from user input (an environment variable) and then passed to ident_gate(store), which calls ensure_marker_locked(store), which calls publish_once(dir), which calls fsync_dir(dir), which calls open(__file).
This argument to a file access function is derived from user input (string read by fread) and then passed to ident_gate(store), which calls ensure_marker_locked(store), which calls publish_once(dir), which calls fsync_dir(dir), which calls open(__file).
github-advanced-security[bot] commented on tools/crumb/crumb.c line 3014 on 2026-11-07 05:23 UTC
CodeQL / Uncontrolled data used in path expression
This argument to a file access function is derived from user input (an environment variable) and then passed to publish_once(dir), which calls fsync_dir(dir), which calls open(__file).
This argument to a file access function is derived from user input (string read by fread) and then passed to publish_once(dir), which calls fsync_dir(dir), which calls open(__file).
The filename being operated upon was previously checked, but the underlying file may have been changed since then.
The filename being operated upon was previously checked, but the underlying file may have been changed since then.
The filename being operated upon was previously checked, but the underlying file may have been changed since then.
diff --git a/docs/CRUMB_PROTOCOL_RFC_0002.md b/docs/CRUMB_PROTOCOL_RFC_0002.md
index 3b3d7b5..eeaf60f 100644
--- a/docs/CRUMB_PROTOCOL_RFC_0002.md
+++ b/docs/CRUMB_PROTOCOL_RFC_0002.md
@@ -67,6 +67,27 @@ CONTINUATIONS newest continuation ids whose scope touches this directory (sect
```
followed by the RFC-0001 `.crumb` summary (purpose, invariants, exports, related).
+### 2.7 Repository namespaces (store layout 2; crumb924, aien-sovereign-core#924)
+Section 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.
+
+- **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).
+- **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).
+- **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).
+- **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.
+- **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.
+- **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 `..`.
+- **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.
+
+### 2.8 `crumb check`, lease generations and enforcement mode (crumb924)
+- **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.
+- **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).
+- **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.
+- **`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.
+- **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.
+- **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.
+- **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.
+- **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.
+
## 3. Mutation discipline (transaction safety)
tmp + `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:
@@ -83,17 +104,18 @@ Two agents pointed at two different coordination roots each believe they hold th
- **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.
- **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`.
- **Three modes.**
- 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.
+ 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).
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.
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).
- **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.
- **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.
-- **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.
+- **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.
- **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`.
## 4. Legacy `.crumb.local` (RFC-0001 physical form)
- New writes go only to the shared store (inside a repository).
+- `.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).
- 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.
- `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.
- `.gitignore` handling for `.crumb.local` stays, for the transition and for non-repository directories.
@@ -145,7 +167,7 @@ Why checkpoint/resume may start outside the C binary: the logic exists today as
## 8. Scope boundary
-This 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 and are 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.
+This 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.
## 9. Tests (the feature is not done until these run)
@@ -161,6 +183,7 @@ This RFC closes the gap for **all linked worktrees of one repository on one file
| T8 | Legacy `.crumb.local` read/import with provenance, never overriding newer shared state | same | PASS (`make -C tools/crumb test`, 0 FAIL) |
| 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) |
| 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) |
+| 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) |
Results are reported PASS / FAIL / NOT_RUN per test in the merging PR; nothing unrun is called PASS.
diff --git a/docs/crumbs/AGENT_WORKFLOW.md b/docs/crumbs/AGENT_WORKFLOW.md
index 473107e..3deea96 100644
--- a/docs/crumbs/AGENT_WORKFLOW.md
+++ b/docs/crumbs/AGENT_WORKFLOW.md
@@ -18,6 +18,22 @@ crumb close <agent> <dir> <target> modify "<what landed>" # after pushing
```
`<agent>` is a stable session id you choose once (e.g. `claude-l6b-7f32`), never a process id. Targets are repository-relative; it does not matter which worktree you run the command in.
+## Enforced repositories: one identity per session, check before every write (RFC-0002 sections 2.7, 2.8)
+In a repository with `git config crumb.enforce true` (or `CRUMB_ENFORCE=1`) the write gate of your runtime runs `crumb check <you> <repo-root> <path>` before each write and blocks on anything but exit 0. So:
+- Your `<agent>` is `<agent-name>.<session-id>` (matches `^[A-Za-z0-9][A-Za-z0-9_.@-]{0,159}$`, used verbatim). Never share it with another session: a second live session presenting it is refused.
+- Claim before you write: `crumb claim <you> . <path-or-dir> "<intent>" <ttl>`. A directory lease covers everything below it; a claim that overlaps another agent's lease (same path, an ancestor or a descendant) exits 2. Note the `generation <N>` it prints.
+- `crumb check <you> . <path> [--generation N] [--key K]` answers `HELD ... generation <N> expires <time>` (exit 0) or `REFUSED absent|expired|held-by <who>|key <have>!=<want>|generation <have>!=<want> ...` (exit 2). A re-check passes both `--key` and `--generation` from the HELD line. Exit 1, 3 or 4 mean the store itself is broken or misconfigured: stop and report it; do not work around it.
+- Renew (claim again) before `expires`; a renewal keeps the generation, a lapsed lease does not.
+
+Onboarding a repository (once per shared root, then once per clone), which is also the migration rule from a layout-1 store (old leases are not carried over; close them in the old store):
+```
+git config crumb.coordinationRoot /abs/shared/root # the same absolute directory in every clone
+crumb store-init . # first clone only: layout 2 (refused unless old flat record dirs are provably empty)
+git config crumb.storeId "$(crumb store-id .)" # every clone
+git config crumb.repoId <owner>/<repo> # only if origin is not host/<owner>/<repo>
+git config crumb.enforce true # every clone
+```
+
## Ending a long session (QUIESCE -> CHECKPOINT -> VERIFY -> WHISPER -> RELEASE)
1. Quiesce: no new branches, decisions or workers; finish the cut in hand to a clean boundary or record exactly where it stopped.
2. `crumb checkpoint <agent> --reason context-pressure` (today: `cc.sh new`), fill the record from the machine state (`git`, receipts, test output), not from memory. Tag every fact PROVEN (with a reference) / PARTIAL / BLOCKED (named dependency) / ASSUMED / OPEN. Keep the definition of done verbatim. Order next tasks by dependency with gates. Carry operator boundaries and who-owns-what.
diff --git a/tools/crumb/Makefile b/tools/crumb/Makefile
index 39a9d7a..aa8c9b1 100644
--- a/tools/crumb/Makefile
+++ b/tools/crumb/Makefile
@@ -9,6 +9,7 @@ test: crumb
sh test.sh ./crumb
sh test-continuation.sh ./crumb
sh test-hostile.sh ./crumb
+ sh test-namespace.sh ./crumb
clean:
rm -f crumb
diff --git a/tools/crumb/crumb.c b/tools/crumb/crumb.c
index 6766768..9ca4fc1 100644
--- a/tools/crumb/crumb.c
+++ b/tools/crumb/crumb.c
@@ -12,8 +12,14 @@
* crumb list [path]
* crumb validate [path]
* crumb store-id [dir] print the coordination store id (STORE_ID marker, shared with synapse-coord)
+ * crumb store-init [dir] deliberately create a layout-2 (repository-namespaced) coordination root
+ * crumb check <agent> <dir> <target> [--generation N] [--key K] read-only: is target covered by agent's valid lease?
* crumb --strict <command> ... refuse an unregistered coordination store (also CRUMB_STRICT_STORE_ID=1)
+ * crumb --enforce <command> ... fail-closed enforcement mode (also CRUMB_ENFORCE=1, git config crumb.enforce true)
* Registered store identity: CRUMB_EXPECT_STORE_ID, else `git config crumb.storeId` (aien-architecture#234).
+ * Repository identity (layout 2): CRUMB_REPO_ID, else `git config crumb.repoId`, else the origin URL as <owner>/<repo>.
+ * Test-only clock: CRUMB_TEST_NOW=<epoch seconds> replaces the wall clock (tests of the expiry boundary; never set it
+ * in production).
*/
#define _DEFAULT_SOURCE
#define _POSIX_C_SOURCE 200809L
@@ -27,6 +33,7 @@
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
+#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
@@ -34,6 +41,7 @@
#define HISTORY_CAP 20
#define SCENT_TTL 3600
#define LOCK_TTL 1800
+#define MAX_TTL 315360000L /* 3650 days: the largest ttl any command writes and the strict reader accepts (crumb924 B5) */
#define WHISPER_RETENTION (24 * 3600)
static void die(const char *fmt, ...) {
@@ -48,6 +56,15 @@ static void die(const char *fmt, ...) {
static void *xmalloc(size_t n) { void *p = malloc(n ? n : 1); if (!p) die("out of memory"); return p; }
static void *xrealloc(void *q, size_t n) { void *p = realloc(q, n ? n : 1); if (!p) die("out of memory"); return p; }
static char *xstrdup(const char *s) { size_t n = strlen(s) + 1; char *p = xmalloc(n); memcpy(p, s, n); return p; }
+/* snprintf into a buffer of exactly size bytes, checked: an encoding error or a result that does not fit is an
+ * internal error (exit 1), never a silently truncated path. Every path the tool formats goes through a bounded write. */
+__attribute__((format(printf, 3, 4)))
+static void xsnprintf(char *dst, size_t size, const char *fmt, ...) {
+ va_list ap; va_start(ap, fmt);
+ int r = vsnprintf(dst, size, fmt, ap);
+ va_end(ap);
+ if (r < 0 || (size_t)r >= size) die("internal error: formatted string does not fit its %zu-byte buffer (format \"%s\")", size, fmt);
+}
/* ---------- growable buffer ---------- */
typedef struct { char *p; size_t n, cap; } Buf;
@@ -250,9 +267,39 @@ static J *jparse(const char *s) {
}
/* ---------- files ---------- */
+/* The one file opener: every open(2)/fopen(3) of this tool goes through crumb_open or crumb_open_follow.
+ * - An empty path, or one with a ".." component, is refused before any open (exit 1, never treated as absent):
+ * every path the tool opens is built from a canonical directory (realpath; a configured root, HOME or git path
+ * with a ".." is canonicalised where it is resolved, canon_path), keys normalised by norm_path, readdir names
+ * (never "." or "..") and constant names, so a ".." here is a resolution bug and is never followed.
+ * - O_CLOEXEC always: no descriptor leaks into the git or cc.sh children.
+ * - O_NOFOLLOW (crumb_open) unless the call site must read through a final symbolic link (crumb_open_follow: the
+ * working tree's own files such as .crumb or .gitignore, which git can track as links; git's info/exclude; the
+ * operator's lane reports; /dev/urandom; a directory opened only to fsync it, whose path may name a linked root).
+ * - openat(AT_FDCWD, ...).
+ * crumb is a local CLI without a privilege boundary: the paths come from the operator's own configuration
+ * (CRUMB_COORD_ROOT, git config, argv). This opener does not change that trust model; it makes the rules uniform. */
+static int has_dotdot(const char *p) { /* 1 when some '/'-separated component of p is exactly ".." */
+ for (const char *s = p;;) {
+ const char *e = strchr(s, '/'); size_t n = e ? (size_t)(e - s) : strlen(s);
+ if (n == 2 && s[0] == '.' && s[1] == '.') return 1;
+ if (!e) return 0;
+ s = e + 1;
+ }
+}
+static int open_checked(const char *path, int flags, mode_t mode, int follow) {
+ if (!*path) die("PATH_REFUSED: empty path; refusing to open it");
+ if (has_dotdot(path)) die("PATH_REFUSED: %s has a '..' component; refusing to open it (crumb opens canonical paths only)", path);
+ return openat(AT_FDCWD, path, flags | O_CLOEXEC | (follow ? 0 : O_NOFOLLOW), mode);
+}
+static int crumb_open(const char *path, int flags, mode_t mode) { return open_checked(path, flags, mode, 0); }
+static int crumb_open_follow(const char *path, int flags, mode_t mode) { return open_checked(path, flags, mode, 1); }
+/* a working-tree file (follows a final symlink); NULL when it cannot be opened */
static char *slurp(const char *path) {
- FILE *f = fopen(path, "rb");
- if (!f) return NULL;
+ int fd = crumb_open_follow(path, O_RDONLY, 0);
+ if (fd < 0) return NULL;
+ FILE *f = fdopen(fd, "rb");
+ if (!f) { close(fd); return NULL; }
Buf b = {0}; bstr(&b, "");
char t[4096]; size_t n;
while ((n = fread(t, 1, sizeof t, f)) > 0) bput(&b, t, n);
@@ -260,9 +307,11 @@ static char *slurp(const char *path) {
return b.p;
}
/* Every file this tool creates is mode 0644 (minus umask), never 0666: fopen() would create it world-writable
- * under a permissive umask (CodeQL cpp/world-writable-file-creation). append=1 opens for appending. */
+ * under a permissive umask (CodeQL cpp/world-writable-file-creation). append=1 opens git's info/exclude for appending
+ * (following a final link, as slurp read it); otherwise path is a fresh temp name and a planted link is refused. */
static FILE *fcreate(const char *path, int append) {
- int fd = open(path, O_WRONLY | O_CREAT | (append ? O_APPEND : O_TRUNC), 0644);
+ int flags = O_WRONLY | O_CREAT | (append ? O_APPEND : O_TRUNC);
+ int fd = append ? crumb_open_follow(path, flags, 0644) : crumb_open(path, flags, 0644);
if (fd < 0) return NULL;
FILE *f = fdopen(fd, append ? "a" : "wb");
if (!f) close(fd);
@@ -270,7 +319,7 @@ static FILE *fcreate(const char *path, int append) {
}
static void spit(const char *path, const char *data) {
size_t tn = strlen(path) + 32; char *tmp = xmalloc(tn);
- snprintf(tmp, tn, "%s.tmp%ld", path, (long)getpid());
+ xsnprintf(tmp, tn, "%s.tmp%ld", path, (long)getpid());
FILE *f = fcreate(tmp, 0);
if (!f) die("cannot write %s: %s", tmp, strerror(errno));
if (fputs(data, f) < 0 || fclose(f) != 0) die("write failed: %s", tmp);
@@ -278,7 +327,33 @@ static void spit(const char *path, const char *data) {
}
static char *pjoin(const char *a, const char *b) {
size_t n = strlen(a) + strlen(b) + 2; char *p = xmalloc(n);
- snprintf(p, n, "%s/%s", a, b); return p;
+ xsnprintf(p, n, "%s/%s", a, b); return p;
+}
+/* Canonical form of an absolute path: realpath when it exists, else each leading part that exists is resolved with
+ * realpath and the rest is applied lexically (".." of a component that does not exist yet drops it; ".." at / stays
+ * at /, as the kernel does). The result has no "." or ".." component, so no path built on it carries one. */
+static char *canon_path(const char *abs) {
+ char r[PATH_MAX];
+ if (realpath(abs, r)) return xstrdup(r);
+ Buf b = {0}; bstr(&b, "");
+ char *cp = xstrdup(abs);
+ for (char *tok = strtok(cp, "/"); tok; tok = strtok(NULL, "/")) {
+ if (!strcmp(tok, ".")) continue;
+ if (!strcmp(tok, "..")) { char *s = strrchr(b.p, '/'); if (s) { *s = 0; b.n = (size_t)(s - b.p); } continue; }
+ bstr(&b, "/"); bstr(&b, tok);
+ if (realpath(b.p, r)) { b.n = 0; bstr(&b, strcmp(r, "/") ? r : ""); }
+ }
+ free(cp);
+ if (!b.n) bstr(&b, "/");
+ return b.p;
+}
+/* a path the operator configured (environment, HOME), relative ones anchored at the working directory: as given
+ * unless it has a ".." component, which is resolved by canon_path */
+static char *canon_dotdot(const char *v) {
+ if (!has_dotdot(v)) return xstrdup(v);
+ if (v[0] == '/') return canon_path(v);
+ char cwd[PATH_MAX]; if (!getcwd(cwd, sizeof cwd)) die("cannot resolve the working directory for %s: %s", v, strerror(errno));
+ char *j = pjoin(cwd, v), *c = canon_path(j); free(j); return c;
}
static char *absdir(const char *d) {
char r[PATH_MAX];
@@ -289,7 +364,17 @@ static char *absdir(const char *d) {
static const char *base_of(const char *p) { const char *s = strrchr(p, '/'); return s && s[1] ? s + 1 : p; }
/* ---------- time ---------- */
-static void now_iso(char *out) { time_t t = time(NULL); struct tm tm; gmtime_r(&t, &tm); strftime(out, 21, "%Y-%m-%dT%H:%M:%SZ", &tm); }
+/* CRUMB_TEST_NOW (test-only, documented in RFC-0002 section 2.8): a fixed epoch second instead of the wall clock, so
+ * the lease expiry boundary can be tested exactly. Anything but decimal digits is refused. */
+static long now_epoch(void) {
+ const char *e = getenv("CRUMB_TEST_NOW");
+ if (!e || !*e) return (long)time(NULL);
+ for (const char *s = e; *s; s++) if (*s < '0' || *s > '9') die("CRUMB_TEST_NOW is \"%s\"; expected epoch seconds (test-only clock)", e);
+ if (strlen(e) > 12) die("CRUMB_TEST_NOW is out of range: %s", e);
+ return atol(e);
+}
+static void iso_of(long when, char *out) { time_t t = (time_t)when; struct tm tm; gmtime_r(&t, &tm); strftime(out, 21, "%Y-%m-%dT%H:%M:%SZ", &tm); }
+static void now_iso(char *out) { iso_of(now_epoch(), out); }
static long parse_iso(const char *s) { /* tolerant: first 19 chars, treated as UTC; -1 on failure */
struct tm tm; memset(&tm, 0, sizeof tm);
int y, mo, d, h, mi, se;
@@ -298,12 +383,37 @@ static long parse_iso(const char *s) { /* tolerant: first 19 chars, treated as
return (long)timegm(&tm);
}
static long jlong(const J *o, const char *key, long dflt) { J *v = jget(o, key); return v && v->t == JNUM ? atol(v->s) : dflt; }
+/* strict forms (enforcement mode, crumb check): exactly YYYY-MM-DDTHH:MM:SSZ with fields in range; a decimal u64 */
+static int iso_strict(const char *s, long *out) {
+ if (!s || strlen(s) != 20) return 0;
+ for (int i = 0; i < 20; i++) {
+ char c = s[i], want = i == 4 || i == 7 ? '-' : i == 10 ? 'T' : i == 13 || i == 16 ? ':' : i == 19 ? 'Z' : 0;
+ if (want ? c != want : !(c >= '0' && c <= '9')) return 0;
+ }
+ int y, mo, d, h, mi, se;
+ if (sscanf(s, "%4d-%2d-%2dT%2d:%2d:%2d", &y, &mo, &d, &h, &mi, &se) != 6) return 0;
+ static const int mdays[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
+ if (y < 1970 || mo < 1 || mo > 12 || h > 23 || mi > 59 || se > 59 || d < 1) return 0;
+ int leap = (y % 4 == 0 && y % 100) || y % 400 == 0;
+ if (d > mdays[mo - 1] + (mo == 2 && leap)) return 0;
+ long v = parse_iso(s); if (v < 0) return 0;
+ *out = v; return 1;
+}
+static int u64_str(const char *s, unsigned long long *out) {
+ if (!s || !*s || strlen(s) > 20) return 0;
+ for (const char *p = s; *p; p++) if (*p < '0' || *p > '9') return 0;
+ if (s[0] == '0' && s[1]) return 0; /* no leading zeros: one spelling per value */
+ errno = 0; char *e; unsigned long long v = strtoull(s, &e, 10);
+ if (errno || *e) return 0;
+ *out = v; return 1;
+}
+static J *jnum_u64(unsigned long long x) { char t[32]; snprintf(t, sizeof t, "%llu", x); J *j = jnew(JNUM); j->s = xstrdup(t); return j; }
/* ---------- .crumb.local (ephemeral bus) ---------- */
typedef struct { char *path, *dir, *before; J *root; } Local;
static void sweep(J *root) { /* SPEC 5.4 */
- long now = (long)time(NULL);
+ long now = now_epoch();
J *sc = jget(root, "active_scents");
if (sc && sc->t == JOBJ) for (size_t i = sc->n; i-- > 0;) {
long u = parse_iso(jstrval(sc->v[i], "updated_at"));
@@ -325,9 +435,15 @@ static void sweep(J *root) { /* SPEC 5.4 */
wh->n = m;
}
}
+static char *read_bounded(const char *path, size_t cap, size_t *len);
+/* .crumb.local is this tool's own state file (RFC-0001 fallback), never a link it wrote: read with the store-record
+ * reader (crumb_open, O_NOFOLLOW), so a symbolic link, FIFO or other special file there is refused (REFUSED_RECORD,
+ * exit 4) instead of being read through. The cap only bounds a runaway file; crumb's own files stay far below it. */
+#define MAX_LOCAL_BYTES ((size_t)64 << 20)
+static char *read_local(const char *path) { return read_bounded(path, MAX_LOCAL_BYTES, NULL); }
static Local local_open(const char *dir) {
Local l; l.dir = absdir(dir); l.path = pjoin(l.dir, ".crumb.local");
- char *txt = slurp(l.path);
+ char *txt = read_local(l.path);
l.root = txt ? jparse(txt) : NULL;
if (txt && (!l.root || l.root->t != JOBJ)) die("%s is not valid JSON; fix or move it aside", l.path);
if (!l.root) l.root = jnew(JOBJ);
@@ -346,6 +462,7 @@ static void git_exclude_local(const char *dir) { /* keep .crumb.local out of `
char *gp = run_git(dir, "rev-parse --git-path info/exclude");
if (!*gp) return;
char *full = gp[0] == '/' ? xstrdup(gp) : pjoin(dir, gp);
+ if (has_dotdot(full)) { char *c = canon_path(full); free(full); full = c; } /* git may print a path with ".." */
char *txt = slurp(full);
if (txt) { char *c = xstrdup(txt); for (char *l = strtok(c, "\n"); l; l = strtok(NULL, "\n")) if (!strcmp(l, ".crumb.local")) return; }
FILE *f = fcreate(full, 1); if (!f) return;
@@ -386,6 +503,25 @@ static int has_lock_by(J *root, const char *agent) {
for (size_t i = 0; i < lk->n; i++) { const char *h = jstrval(lk->v[i], "holder"); if (h && !strcmp(h, agent)) return 1; }
return 0;
}
+/* ---------- lease generation (fencing token) ----------
+ * Per key, the generation strictly increases on every 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 record's "generations" map, which outlives the lease itself (close and expiry remove only the lease). */
+static unsigned long long jgen(const J *o, const char *key) { J *v = jget(o, key); unsigned long long g; return v && v->t == JNUM && u64_str(v->s, &g) ? g : 0; }
+static unsigned long long gen_next(J *rec, const char *path, const char *key, const J *cur, const char *agent) {
+ J *gens = jget(rec, "generations");
+ if (gens && gens->t != JOBJ) die("MALFORMED_RECORD: %s: \"generations\" is not an object; refusing (a reset counter would reuse fencing tokens)", path);
+ gens = jobj_of(rec, "generations");
+ unsigned long long last = jgen(gens, key), cg = cur ? jgen(cur, "generation") : 0;
+ if (cg > last) last = cg;
+ const char *h = cur ? jstrval(cur, "holder") : NULL;
+ unsigned long long g = cur && cg && h && !strcmp(h, agent) ? cg : last + 1;
+ if (!g) die("generation counter for %s is exhausted", key);
+ /* the high-water mark never decreases: a renewal keeps the lease's generation but never lowers a larger
+ * counter (crumb924 B6; enforcement mode refuses such a pair before this point, dir_record_strict) */
+ jset(gens, key, jnum_u64(g > last ? g : last));
+ return g;
+}
/* ---------- operations ---------- */
static int legacy_claim(const char *agent, const char *dir, const char *target, const char *intent, long ttl) {
@@ -400,12 +536,14 @@ static int legacy_claim(const char *agent, const char *dir, const char *target,
}
}
char ts[21]; now_iso(ts);
+ unsigned long long gen = gen_next(l.root, l.path, target, cur, agent);
J *e = cur && cur->t == JOBJ ? cur : jnew(JOBJ);
jset(e, "holder", jstr(agent)); jset(e, "intent", jstr(intent)); jset(e, "acquired_at", jstr(ts)); jset(e, "ttl_seconds", jnum(ttl));
+ jset(e, "generation", jnum_u64(gen));
jset(jobj_of(l.root, "locks"), target, e);
scent_set(l.root, agent, intent, SCENT_TTL > ttl ? SCENT_TTL : ttl);
local_save(&l);
- printf("CLAIMED %s in %s as %s (ttl %lds)\n", target, l.dir, agent, ttl);
+ printf("CLAIMED %s in %s as %s (ttl %lds) generation %llu\n", target, l.dir, agent, ttl, gen);
return 0;
}
static int legacy_update(const char *agent, const char *dir, const char *focus, long ttl) {
@@ -477,7 +615,9 @@ static int legacy_sniff(const char *agent, const char *dir) { /* SPEC 5.1 */
static void mkdir_p(const char *path);
typedef struct { char expect[33]; const char *source; int has_expect, warned; } Ident; /* registered store identity, see below */
-typedef struct { char *store, *top, *abs, *rel, *branch, *head, *base; Ident id; } Plane;
+typedef struct { char *store, *top, *abs, *rel, *branch, *head, *base; Ident id; char *root, *repo_id; const char *repo_src; int layout; } Plane;
+/* root: the coordination root (STORE_ID, LAYOUT, .lock). store: where records live, the root itself in layout 1,
+ * <root>/repos/<repo-id> in layout 2 (NULL when layout 2 and no repository id resolved). */
typedef struct { char *path; J *root; char *before; int agent, dead, existed; } Rec;
typedef struct { Plane *p; Rec **r; size_t n, cap; int fd; } Txn;
@@ -552,7 +692,7 @@ static char *read_bounded(const char *path, size_t cap, size_t *len) {
die("cannot stat %s: %s", path, strerror(errno));
}
if (!S_ISREG(st.st_mode)) refuse(path, kind_of(st.st_mode));
- int fd = open(path, O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC);
+ int fd = crumb_open(path, O_RDONLY | O_NONBLOCK, 0);
if (fd < 0) {
if (errno == ENOENT) return NULL;
if (errno == ELOOP) refuse(path, "is a symbolic link");
@@ -597,7 +737,7 @@ static void check_real_parents(const char *store, const char *path) {
* neither block on a planted FIFO nor follow a planted link. */
static int create_temp(const char *tmp) {
if (unlink(tmp) != 0 && errno != ENOENT) die("cannot remove stale %s: %s", tmp, strerror(errno));
- int fd = open(tmp, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0644);
+ int fd = crumb_open(tmp, O_WRONLY | O_CREAT | O_EXCL, 0644);
if (fd < 0) die("cannot write %s: %s", tmp, strerror(errno));
return fd;
}
@@ -618,6 +758,7 @@ static void write_all(int fd, const char *data, size_t len, const char *path) {
#define STORE_ID_FILE "STORE_ID"
#define STORE_ID_FORMAT "crumb-coord-store-id/1"
static int g_strict; /* --strict or CRUMB_STRICT_STORE_ID=1 */
+static int g_enforce; /* --enforce, CRUMB_ENFORCE=1 or git config crumb.enforce true: fail closed everywhere (implies strict) */
static int hex_id_ok(const char *s, size_t n) {
if (n != 32) return 0;
for (size_t i = 0; i < n; i++) if (!((s[i] >= '0' && s[i] <= '9') || (s[i] >= 'a' && s[i] <= 'f'))) return 0;
@@ -641,30 +782,36 @@ static int read_marker(const char *store, char hex[33]) {
return 1;
}
static void fsync_dir(const char *dir);
+/* Publish a new store marker file at path: tmp, fsync, link(2) (never replaces an existing file), dir fsync. */
+static void publish_once(const char *dir, const char *path, const char *data, size_t len) {
+ size_t tn = strlen(path) + 32; char *tmp = xmalloc(tn);
+ xsnprintf(tmp, tn, "%s.tmp%ld", path, (long)getpid());
+ int fd = create_temp(tmp);
+ write_all(fd, data, len, tmp);
+ if (fsync(fd) != 0) die("fsync failed: %s", tmp);
+ if (close(fd) != 0) die("close failed: %s", tmp);
+ int lr = link(tmp, path), le = errno;
+ unlink(tmp);
+ if (lr != 0 && le != EEXIST) die("cannot publish %s: %s", path, strerror(le));
+ fsync_dir(dir);
+ free(tmp);
+}
/* Create the marker if absent; call only while holding the store's fcntl lock. link(2) never replaces an existing
* file, so even a writer outside the lock cannot overwrite a marker. A crash before the link leaves only a tmp file. */
static void ensure_marker_locked(const char *store, char hex[33]) {
if (read_marker(store, hex)) return;
unsigned char rb[16]; size_t got = 0;
- int rf = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
+ int rf = crumb_open_follow("/dev/urandom", O_RDONLY, 0);
if (rf < 0) die("cannot open /dev/urandom: %s", strerror(errno));
while (got < sizeof rb) { ssize_t r = read(rf, rb + got, sizeof rb - got); if (r < 0 && errno == EINTR) continue; if (r <= 0) die("cannot read /dev/urandom"); got += (size_t)r; }
close(rf);
char line[64]; int ll = snprintf(line, sizeof line, "%s ", STORE_ID_FORMAT);
for (size_t i = 0; i < sizeof rb; i++) ll += snprintf(line + ll, sizeof line - (size_t)ll, "%02x", rb[i]);
line[ll++] = '\n'; line[ll] = 0;
- char *mp = pjoin(store, STORE_ID_FILE), *tmp = xmalloc(strlen(mp) + 32);
- sprintf(tmp, "%s.tmp%ld", mp, (long)getpid());
- int fd = create_temp(tmp);
- write_all(fd, line, (size_t)ll, tmp);
- if (fsync(fd) != 0) die("fsync failed: %s", tmp);
- if (close(fd) != 0) die("close failed: %s", tmp);
- int lr = link(tmp, mp), le = errno;
- unlink(tmp);
- if (lr != 0 && le != EEXIST) die("cannot publish %s: %s", mp, strerror(le));
- fsync_dir(store);
+ char *mp = pjoin(store, STORE_ID_FILE);
+ publish_once(store, mp, line, (size_t)ll);
if (!read_marker(store, hex)) die_x(EXIT_STORE_ID, "STORE_ID_MISSING: coordination store %s has no %s marker after creating it", store, STORE_ID_FILE);
- free(tmp); free(mp);
+ free(mp);
}
/* Ident (expected store id, its source, warned-once flag) is declared with Plane above. */
static Ident ident_resolve(const char *gitdir) { /* gitdir NULL: no repository, environment only */
@@ -703,39 +850,266 @@ static char *session_id(const char *agent) {
if (e && *e) return xstrdup(e);
char h[256]; if (gethostname(h, sizeof h) != 0) strcpy(h, "unknown-host");
h[sizeof h - 1] = 0;
- size_t n = strlen(agent) + strlen(h) + 2; char *s = xmalloc(n); snprintf(s, n, "%s@%s", agent, h); return s;
+ size_t n = strlen(agent) + strlen(h) + 2; char *s = xmalloc(n); xsnprintf(s, n, "%s@%s", agent, h); return s;
}
+/* ---------- repository namespaces (store layout 2) and enforcement mode (crumb924) ----------
+ * Layout 1 (flat, the default and every store created before layout 2): records directly under the coordination root.
+ * Layout 2: <root>/LAYOUT holds exactly "crumb-coord-layout/2\n"; records live under <root>/repos/<repo-id>/; STORE_ID
+ * and .lock stay at the root. A root becomes layout 2 only through `crumb store-init` (refused while flat records
+ * exist), so a flat store is never reinterpreted. Repository id: CRUMB_REPO_ID, else git config crumb.repoId, else the
+ * origin remote URL normalised to <owner>/<repo> (lowercase); never the filesystem path. */
+#define LAYOUT_FILE "LAYOUT"
+#define LAYOUT_V2 "crumb-coord-layout/2\n"
+static void collect_json(const char *dir, char ***out, size_t *n);
+static int id_char(char c, int agent) {
+ return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '_' || c == '-' || (agent && c == '@');
+}
+static int alnum_c(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'); }
+/* ^[A-Za-z0-9][A-Za-z0-9_.@-]{0,159}$ (layout 2 and enforcement mode: used verbatim as the record name, no aliases) */
+static int agent_ok(const char *a) {
+ size_t n = strlen(a);
+ if (n < 1 || n > 160 || !alnum_c(a[0])) return 0;
+ for (size_t i = 0; i < n; i++) if (!id_char(a[i], 1)) return 0;
+ return 1;
+}
+static void agent_require(const Plane *p, const char *agent) { /* p NULL: before resolution (enforcement only) */
+ if (!(g_enforce || (p && p->layout == 2)) || agent_ok(agent)) return;
+ die("AGENT_ID_INVALID: agent id \"%s\" must match ^[A-Za-z0-9][A-Za-z0-9_.@-]{0,159}$ (%s uses it verbatim; nothing is rewritten into an alias)", agent, g_enforce ? "enforcement mode" : "layout 2");
+}
+/* ^[A-Za-z0-9][A-Za-z0-9._-]*(/[A-Za-z0-9][A-Za-z0-9._-]*)?$; the second component may not be a record directory name
+ * (dirs, agents, continuations, ledger), or namespace X/dirs would nest inside namespace X. */
+static int repo_id_ok(const char *s) {
+ size_t n = strlen(s);
+ if (n < 1 || n > 200 || !alnum_c(s[0])) return 0; /* a leading '/' (empty first component) would alias "x" (N2) */
+ const char *sl = strchr(s, '/');
+ if (sl && strchr(sl + 1, '/')) return 0;
+ for (const char *c = s; *c; c++) {
+ if (*c == '/') continue;
+ if ((c == s || c[-1] == '/') && !alnum_c(*c)) return 0;
+ if (!id_char(*c, 0)) return 0;
+ }
+ if (sl) {
+ const char *b = sl + 1;
+ if (!*b || !strcmp(b, "dirs") || !strcmp(b, "agents") || !strcmp(b, "continuations") || !strcmp(b, "ledger")) return 0;
+ }
+ return 1;
+}
+/* <owner>/<repo> from git@host:o/r(.git), ssh://[user@]host[:port]/o/r(.git), https://host/o/r(.git)(/); NULL for a
+ * local path or file:// URL (a path is never an identity) or anything not exactly two path components. */
+static char *repo_id_from_url(const char *url) {
+ const char *path = NULL, *se = strstr(url, "://");
+ if (se) {
+ if (!strncmp(url, "file:", 5)) return NULL;
+ const char *h = se + 3, *slash = strchr(h, '/');
+ if (!slash || slash == h) return NULL;
+ path = slash + 1;
+ } else {
+ const char *colon = strchr(url, ':'), *slash = strchr(url, '/');
+ if (!colon || colon == url || (slash && slash < colon)) return NULL; /* local path, not scp-like */
+ path = colon + 1;
+ }
+ char *c = xstrdup(path); size_t n = strlen(c);
+ while (n && c[n - 1] == '/') c[--n] = 0;
+ if (n > 4 && !strcmp(c + n - 4, ".git")) c[n -= 4] = 0;
+ while (n && c[n - 1] == '/') c[--n] = 0;
+ char *s = c; while (*s == '/') s++;
+ for (char *q = s; *q; q++) if (*q >= 'A' && *q <= 'Z') *q = (char)(*q - 'A' + 'a');
+ if (!strchr(s, '/') || !repo_id_ok(s)) return NULL;
+ return xstrdup(s);
+}
+static char *repo_id_resolve(const char *abs, const char **src) {
+ const char *e = getenv("CRUMB_REPO_ID"); char *v = NULL;
+ if (e && *e) { v = xstrdup(e); *src = "CRUMB_REPO_ID"; }
+ else { char *c = run_git(abs, "config --get crumb.repoId"); if (*c) { v = c; *src = "git config crumb.repoId"; } }
+ if (v) {
+ if (!repo_id_ok(v)) die_x(EXIT_STORE_ID, "REPO_ID_INVALID: %s is \"%s\"; expected <owner>/<repo> matching ^[A-Za-z0-9][A-Za-z0-9._-]*(/[A-Za-z0-9][A-Za-z0-9._-]*)?$ (second component not dirs|agents|continuations|ledger)", *src, v);
+ return v;
+ }
+ char *url = run_git(abs, "config --get remote.origin.url");
+ *src = "origin remote URL";
+ return *url ? repo_id_from_url(url) : NULL;
+}
+/* 1: no LAYOUT marker (flat); 2: exactly LAYOUT_V2; anything else is refused (exit 3; hostile file exit 4) */
+static int read_layout(const char *root) {
+ char *lp = pjoin(root, LAYOUT_FILE); size_t n = 0;
+ char *b = read_bounded(lp, MAX_MARKER_BYTES, &n);
+ if (!b) { free(lp); return 1; }
+ if (n != strlen(LAYOUT_V2) || memcmp(b, LAYOUT_V2, n))
+ die_x(EXIT_STORE_ID, "STORE_LAYOUT_UNSUPPORTED: %s is not \"crumb-coord-layout/2\"; refusing (never rewritten)", lp);
+ free(b); free(lp);
+ return 2;
+}
+/* A relative CRUMB_COORD_ROOT / crumb.coordinationRoot is anchored at the worktree top-level, not the process cwd,
+ * and canonicalised (canon_path: realpath of what exists, the rest lexically), so the cwd never changes the store.
+ * An absolute root is used exactly as given unless it has a ".." component, which is canonicalised the same way:
+ * no store path ever carries a "..", and crumb_open refuses one. */
+static char *root_canon(const char *v, const char *top) {
+ if (v[0] == '/' && !has_dotdot(v)) return xstrdup(v);
+ char *j = v[0] == '/' ? xstrdup(v) : pjoin(top, v), *c = canon_path(j);
+ free(j);
+ return c;
+}
+static int bool_word(const char *v, const char *what) { /* git-style boolean; anything else is refused */
+ if (!strcmp(v, "1") || !strcmp(v, "true") || !strcmp(v, "yes") || !strcmp(v, "on")) return 1;
+ if (!*v || !strcmp(v, "0") || !strcmp(v, "false") || !strcmp(v, "no") || !strcmp(v, "off")) return 0;
+ die("%s is \"%s\"; expected true or false", what, v);
+ return 0;
+}
+static void enforce_on(void) { g_enforce = 1; g_strict = 1; }
+/* git config crumb.enforce, read with git's own boolean conversion (`git config --bool --get`: a valueless key, yes,
+ * on, 1, any non-zero integer are true). 1 true, 0 false, -1 absent (git exit 1); any other outcome (a value git
+ * refuses as a boolean, git failing to run) is an error, never "absent" (crumb924 N1). */
+static int git_config_bool(const char *dir, const char *key) {
+ Buf q = {0}; bstr(&q, "'");
+ for (const char *p = dir; *p; p++) { if (*p == '\'') bstr(&q, "'\\''"); else bput(&q, p, 1); }
+ bstr(&q, "'");
+ size_t cn = q.n + strlen(key) + 64; char *cmd = xmalloc(cn);
+ snprintf(cmd, cn, "git -C %s config --bool --get %s 2>/dev/null", q.p, key);
+ FILE *f = popen(cmd, "r");
+ if (!f) die("cannot run git to read git config %s: %s", key, strerror(errno));
+ char t[64]; size_t n = fread(t, 1, sizeof t - 1, f); t[n] = 0;
+ int st = pclose(f), rc = st != -1 && WIFEXITED(st) ? WEXITSTATUS(st) : -1;
+ free(cmd); free(q.p);
+ while (n && (t[n - 1] == '\n' || t[n - 1] == '\r')) t[--n] = 0;
+ if (rc == 1 && !n) return -1;
+ if (rc == 0 && !strcmp(t, "true")) return 1;
+ if (rc == 0 && !strcmp(t, "false")) return 0;
+ die("cannot read git config %s as a boolean (git exit %d%s%s); refusing to guess whether enforcement is on", key, rc, n ? ", output " : "", t);
+ return 0;
+}
+static char *ns_path(const char *root, const char *repo_id) { char *r = pjoin(root, "repos"), *s = pjoin(r, repo_id); free(r); return s; }
+
+static char *shq(const char *s);
+/* run a git command in dir under the C locale: stdout (trailing newlines stripped) and the exit status (-1 when git
+ * could not be run or did not exit); stderr is captured into *err when err is non-NULL, else discarded */
+static char *git_rc(const char *dir, const char *args, int *rc, char **err) {
+ char *q = shq(dir); size_t cn = strlen(q) + strlen(args) + 96; char *cmd = xmalloc(cn);
+ if (err) snprintf(cmd, cn, "LC_ALL=C LANGUAGE=C git -C %s %s 2>&1 >/dev/null", q, args);
+ else snprintf(cmd, cn, "LC_ALL=C LANGUAGE=C git -C %s %s 2>/dev/null", q, args);
+ FILE *f = popen(cmd, "r"); Buf b = {0}; bstr(&b, "");
+ *rc = -1;
+ if (f) {
+ char t[4096]; size_t n;
+ while ((n = fread(t, 1, sizeof t, f)) > 0) bput(&b, t, n);
+ int st = pclose(f); *rc = st != -1 && WIFEXITED(st) ? WEXITSTATUS(st) : -1;
+ }
+ free(cmd); free(q);
+ while (b.n && (b.p[b.n - 1] == '\n' || b.p[b.n - 1] == '\r')) b.p[--b.n] = 0;
+ if (err) { *err = b.p; return xstrdup(""); }
+ return b.p;
+}
+static int has_git_ancestor(const char *abs) { /* a .git entry (directory, gitdir file or link) in abs or above */
+ char *d = xstrdup(abs);
+ for (;;) {
+ char *g = pjoin(*d ? d : "/", ".git"); struct stat st; int hit = lstat(g, &st) == 0; free(g);
+ if (hit) { free(d); return 1; }
+ char *s = strrchr(d, '/'); if (!s || !*d) break;
+ *s = 0;
+ }
+ free(d); return 0;
+}
+/* git's own end-of-discovery diagnostic (LC_ALL=C), matched as the WHOLE stderr, never as a substring: git names
+ * files in other diagnostics ("bad config line 1 in file <path>"), so a path containing the words must not turn a
+ * configuration error into "outside any repository" (re-review of B7). The two forms git prints: */
+static int git_nonrepo_diagnostic(const char *err) {
+ if (!strcmp(err, "fatal: not a git repository (or any of the parent directories): .git")) return 1;
+ const char *head = "fatal: not a git repository (or any parent up to mount point ",
+ *tail = ")\nStopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).";
+ size_t hl = strlen(head), tl = strlen(tail), n = strlen(err);
+ return n > hl + tl && !strncmp(err, head, hl) && !strcmp(err + n - tl, tail) && !memchr(err + hl, '\n', n - hl - tl);
+}
+/* Repository discovery (crumb924 B7). Returns the canonical work-tree top level, or NULL only when the directory is
+ * positively established to be outside any repository: git's own discovery ran to its end (its whole stderr is
+ * exactly the end-of-discovery diagnostic, exit 128, GIT_DIR unset), or, with GIT_DIR unset, git did not succeed and no .git entry exists in the directory or
+ * any ancestor. Every other failure (a malformed or unreadable .git/config, a .git file or GIT_DIR naming nothing,
+ * dubious ownership, git not runnable inside a repository, a top level that does not contain the directory) is
+ * GIT_DISCOVERY_FAILED (exit 1) in every mode, before anything is written: whether enforcement is configured cannot
+ * be known, so the .crumb.local fallback is never taken on a discovery error. */
+static char *git_discover(const char *abs) {
+ int rc; char *top = git_rc(abs, "rev-parse --show-toplevel", &rc, NULL), r[PATH_MAX];
+ if (rc == 0 && *top) {
+ if (!realpath(top, r)) die("GIT_DISCOVERY_FAILED: git reports top level %s for %s but it cannot be resolved: %s; refusing (no .crumb.local fallback on a discovery error)", top, abs, strerror(errno));
+ free(top); top = xstrdup(r);
+ size_t tl = strlen(top);
+ if (strncmp(abs, top, tl) || (abs[tl] && abs[tl] != '/'))
+ die("GIT_DISCOVERY_FAILED: %s is not inside its git top level %s; refusing (no .crumb.local fallback on a discovery error)", abs, top);
+ return top;
+ }
+ free(top);
+ char *err = NULL; int rc2; git_rc(abs, "rev-parse --show-toplevel", &rc2, &err);
+ const char *gd = getenv("GIT_DIR");
+ int nonrepo = (rc == 128 && rc2 == 128 && !(gd && *gd) && git_nonrepo_diagnostic(err))
+ || (rc != 0 && !(gd && *gd) && !has_git_ancestor(abs));
+ if (nonrepo) { free(err); return NULL; }
+ char *nl = strchr(err, '\n'); if (nl && !strncmp(err, "warning:", 8) && nl[1]) memmove(err, nl + 1, strlen(nl + 1) + 1);
+ if ((nl = strchr(err, '\n'))) *nl = 0;
+ die("GIT_DISCOVERY_FAILED: git cannot establish whether %s is inside a repository (git rev-parse exit %d%s%s); refusing before any write (no .crumb.local fallback on a discovery error; fix the repository or its .git/config)", abs, rc, *err ? ": " : "", err);
+ return NULL;
+}
static Plane *plane_find(const char *dir) { /* resolve the coordination root; no identity check yet */
- char *abs = absdir(dir), *top = run_git(abs, "rev-parse --show-toplevel"), r[PATH_MAX];
- if (!*top || !realpath(top, r)) return NULL;
- top = xstrdup(r);
+ char *abs = absdir(dir), *top = git_discover(abs), r[PATH_MAX];
+ if (!top) {
+ if (g_enforce) die("ENFORCE_NO_REPOSITORY: %s is not inside a git repository; enforcement mode has no .crumb.local fallback", abs);
+ return NULL;
+ }
size_t tl = strlen(top);
- if (strncmp(abs, top, tl) || (abs[tl] && abs[tl] != '/')) return NULL;
+ if (!g_enforce && git_config_bool(abs, "crumb.enforce") == 1) enforce_on();
Plane *p = xmalloc(sizeof *p); memset(p, 0, sizeof *p);
p->abs = abs; p->top = top; p->rel = abs[tl] ? xstrdup(abs + tl + 1) : xstrdup(".");
const char *env = getenv("CRUMB_COORD_ROOT");
- if (env && *env) p->store = xstrdup(env);
- else { char *cfg = run_git(abs, "config --get crumb.coordinationRoot"); if (*cfg) p->store = cfg; }
- if (!p->store) {
+ if (env && *env) p->root = root_canon(env, top);
+ else { char *cfg = run_git(abs, "config --get crumb.coordinationRoot"); if (*cfg) p->root = root_canon(cfg, top); }
+ if (!p->root) {
char *cd = run_git(abs, "rev-parse --git-common-dir");
if (!*cd) die("inside a git repository (%s) but cannot resolve its common directory; set CRUMB_COORD_ROOT", top);
char *full = cd[0] == '/' ? cd : pjoin(abs, cd);
if (!realpath(full, r)) die("cannot resolve git common directory %s; set CRUMB_COORD_ROOT", full);
- p->store = pjoin(r, "crumb/v1");
+ p->root = pjoin(r, "crumb/v1");
}
p->branch = run_git(abs, "symbolic-ref --short -q HEAD"); if (!*p->branch) p->branch = xstrdup("(detached)");
p->head = run_git(abs, "rev-parse --short=12 HEAD");
p->base = run_git(abs, "merge-base HEAD origin/main"); if (strlen(p->base) > 12) p->base[12] = 0;
p->id = ident_resolve(abs);
+ p->layout = read_layout(p->root);
+ if (p->layout == 2 || g_enforce) p->repo_id = repo_id_resolve(abs, &p->repo_src);
+ p->store = p->layout == 1 ? xstrdup(p->root) : p->repo_id ? ns_path(p->root, p->repo_id) : NULL;
return p;
}
+static size_t count_json(const char *dir) { char **f = NULL; size_t n = 0; collect_json(dir, &f, &n); for (size_t i = 0; i < n; i++) free(f[i]); free(f); return n; }
+/* the conditions every coordination command needs on top of the store identity (enforcement mode fails closed) */
+static void plane_require(Plane *p) {
+ if (g_enforce && p->layout != 2)
+ die_x(EXIT_STORE_ID, "STORE_LAYOUT_V1: coordination root %s has layout 1 (flat, no repository namespaces); enforcement mode needs layout 2: `crumb store-init` on a new or empty root (see RFC-0002 section 2.7)", p->root);
+ if (p->layout != 2) return;
+ if (!p->repo_id)
+ die_x(EXIT_STORE_ID, "REPO_ID_MISSING: coordination root %s is namespaced (layout 2) but this repository has no id: set git config crumb.repoId <owner>/<repo> (or CRUMB_REPO_ID), or an origin remote URL host/<owner>/<repo>", p->root);
+ char *fd = pjoin(p->root, "dirs"), *fa = pjoin(p->root, "agents");
+ if (count_json(fd) + count_json(fa)) {
+ if (g_enforce) die_x(EXIT_STORE_ID, "STORE_LAYOUT_MIXED: layout-2 root %s also holds flat (layout 1) records under dirs/ or agents/ (an older crumb wrote them); their locks are invisible here: refusing", p->root);
+ fprintf(stderr, "crumb: warning: STORE_LAYOUT_MIXED: layout-2 root %s also holds flat records under dirs/ or agents/; they are ignored (enforcement mode refuses this)\n", p->root);
+ }
+ free(fd); free(fa);
+ char *lp = pjoin(p->abs, ".crumb.local"); struct stat st;
+ if (lstat(lp, &st) == 0) fprintf(stderr, "crumb: warning: %s is ignored: a layout-2 store never imports .crumb.local\n", lp);
+ free(lp);
+}
/* every coordination command: resolve the root, then check its identity before touching anything in it */
static Plane *plane_resolve(const char *dir) {
Plane *p = plane_find(dir);
- if (p) ident_gate(&p->id, p->store, 0);
+ if (p) { ident_gate(&p->id, p->root, 0); plane_require(p); }
return p;
}
+/* no repository (explain, checkpoint/resume with only CRUMB_COORD_ROOT): the records base of that root, after the
+ * env-only identity check; a layout-2 root needs CRUMB_REPO_ID (there is no git config or origin to read) */
+static char *env_store(const char *root) {
+ Ident id = ident_resolve(NULL); ident_gate(&id, root, 0);
+ if (read_layout(root) != 2) return xstrdup(root);
+ const char *r = getenv("CRUMB_REPO_ID");
+ if (!r || !*r) die_x(EXIT_STORE_ID, "REPO_ID_MISSING: coordination root %s is namespaced (layout 2); outside a repository set CRUMB_REPO_ID", root);
+ if (!repo_id_ok(r)) die_x(EXIT_STORE_ID, "REPO_ID_INVALID: CRUMB_REPO_ID is \"%s\"", r);
+ return ns_path(root, r);
+}
/* repository-relative key for a target: <dir>/<target> if that exists, else <target> from the
* repo root if that exists, else repo-relative as given when it contains '/', else <dir>/<target>.
* An absolute path inside this worktree is made repo-relative, so two worktrees agree. */
@@ -756,7 +1130,14 @@ static char *target_key(const Plane *p, const char *target, const char *rel) {
die("target %s escapes the repository", target);
return NULL;
}
-static void fsync_dir(const char *dir) { int fd = open(dir, O_RDONLY); if (fd >= 0) { (void)fsync(fd); close(fd); } }
+/* directory fsync after a rename or link; best effort normally, fatal in enforcement mode (EINVAL: the filesystem
+ * cannot sync directories, which is not a failure to persist) */
+static void fsync_dir(const char *dir) {
+ int fd = crumb_open_follow(dir, O_RDONLY | O_DIRECTORY, 0);
+ if (fd < 0) { if (g_enforce) die("cannot open directory %s to sync it: %s", dir, strerror(errno)); return; }
+ if (fsync(fd) != 0 && g_enforce && errno != EINVAL) die("fsync of directory %s failed: %s", dir, strerror(errno));
+ close(fd);
+}
static void durable_write(const char *store, const char *path, const char *data) { /* tmp, fsync, rename, fsync dir */
size_t len = strlen(data);
if (len > MAX_RECORD_BYTES) die_x(EXIT_REFUSED, "REFUSED_RECORD: %s would be larger than %zu bytes; refusing to write it", path, MAX_RECORD_BYTES);
@@ -765,7 +1146,7 @@ static void durable_write(const char *store, const char *path, const char *data)
if (lstat(path, &st) == 0 && !S_ISREG(st.st_mode)) die_x(EXIT_REFUSED, "REFUSED_RECORD: %s %s; refusing to replace it (fix or move it aside)", path, kind_of(st.st_mode));
char *dd = dir_of(path); mkdir_p(dd);
size_t tn = strlen(path) + 32; char *tmp = xmalloc(tn);
- snprintf(tmp, tn, "%s.tmp%ld", path, (long)getpid());
+ xsnprintf(tmp, tn, "%s.tmp%ld", path, (long)getpid());
int fd = create_temp(tmp);
write_all(fd, data, len, tmp);
if (fsync(fd) != 0) die("fsync failed: %s", tmp);
@@ -773,38 +1154,110 @@ static void durable_write(const char *store, const char *path, const char *data)
if (rename(tmp, path) != 0) die("rename failed: %s", path);
fsync_dir(dd);
}
-static Txn *txn_begin(Plane *p, int mutate) {
- Txn *t = xmalloc(sizeof *t); memset(t, 0, sizeof *t); t->p = p; t->fd = -1;
- if (!mutate) return t;
- static const char *sub[] = { "dirs", "agents", "continuations", "ledger", NULL };
- for (int i = 0; sub[i]; i++) { char *d = pjoin(p->store, sub[i]); mkdir_p(d); free(d); }
- char *lp = pjoin(p->store, ".lock");
+/* fcntl lock on <root>/.lock. create: open O_CREAT, exclusive lock (mutations); else shared lock on an existing lock
+ * file and -1 when there is none (crumb check: creates nothing). A planted FIFO, device, symlink or directory is refused. */
+static int root_lock(const char *root, int create) {
+ char *lp = pjoin(root, ".lock");
struct stat st; /* the lock file is a store file too: a planted FIFO, device, symlink or directory is refused */
- if (lstat(lp, &st) == 0 && !S_ISREG(st.st_mode)) refuse(lp, kind_of(st.st_mode));
- t->fd = open(lp, O_RDWR | O_CREAT | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC, 0644);
- if (t->fd < 0) {
+ if (lstat(lp, &st) == 0) { if (!S_ISREG(st.st_mode)) refuse(lp, kind_of(st.st_mode)); }
+ else if (!create) { if (errno == ENOENT) { free(lp); return -1; } if (errno == ENOTDIR) refuse(lp, "has a parent that is not a directory"); die("cannot stat %s: %s", lp, strerror(errno)); }
+ int fd = crumb_open(lp, (create ? O_RDWR | O_CREAT : O_RDONLY) | O_NONBLOCK, 0644);
+ if (fd < 0) {
+ if (!create && errno == ENOENT) { free(lp); return -1; }
if (errno == ELOOP) refuse(lp, "is a symbolic link");
if (errno == EISDIR) refuse(lp, "is a directory, not a regular file");
die("cannot open %s: %s", lp, strerror(errno));
}
- if (fstat(t->fd, &st) != 0) die("cannot stat %s: %s", lp, strerror(errno));
+ if (fstat(fd, &st) != 0) die("cannot stat %s: %s", lp, strerror(errno));
if (!S_ISREG(st.st_mode)) refuse(lp, kind_of(st.st_mode));
- struct flock fl; memset(&fl, 0, sizeof fl); fl.l_type = F_WRLCK; fl.l_whence = SEEK_SET;
- while (fcntl(t->fd, F_SETLKW, &fl) != 0) if (errno != EINTR) die("cannot lock %s: %s", lp, strerror(errno));
- ident_gate(&p->id, p->store, 1); /* under the lock: re-check the registered id, or create the marker once */
+ struct flock fl; memset(&fl, 0, sizeof fl); fl.l_type = create ? F_WRLCK : F_RDLCK; fl.l_whence = SEEK_SET;
+ while (fcntl(fd, F_SETLKW, &fl) != 0) if (errno != EINTR) die("cannot lock %s: %s", lp, strerror(errno));
+ free(lp);
+ return fd;
+}
+/* A root that any command has initialized or written: layout 2 (store-init creates .lock with LAYOUT), enforcement,
+ * or a layout-1 root holding a marker or record directories (every first mutation creates .lock before them). Only a
+ * never-used compatibility root may lack .lock; for crumb check that is plain absence (crumb924 B4). */
+static int store_used(const Plane *p) {
+ if (p->layout == 2 || g_enforce) return 1;
+ static const char *names[] = { STORE_ID_FILE, LAYOUT_FILE, "dirs", "agents", NULL };
+ for (int i = 0; names[i]; i++) { char *f = pjoin(p->root, names[i]); struct stat st; int e = lstat(f, &st) == 0; free(f); if (e) return 1; }
+ return 0;
+}
+static Txn *txn_begin(Plane *p, int mutate) {
+ Txn *t = xmalloc(sizeof *t); memset(t, 0, sizeof *t); t->p = p; t->fd = -1;
+ if (!mutate) return t;
+ mkdir_p(p->root);
+ t->fd = root_lock(p->root, 1); /* the lock exists before any record directory (crumb check relies on it, B4) */
+ static const char *sub[] = { "dirs", "agents", "continuations", "ledger", NULL };
+ for (int i = 0; sub[i]; i++) { char *d = pjoin(p->store, sub[i]); mkdir_p(d); free(d); }
+ ident_gate(&p->id, p->root, 1); /* under the lock: re-check the registered id, or create the marker once */
+ if (read_layout(p->root) != p->layout) die("STORE_LAYOUT_CHANGED: coordination root %s changed layout while this command ran (store-init); retry", p->root);
return t;
}
+/* Strict lease schema (enforcement mode always; crumb check for the leases it judges): holder a non-empty string,
+ * session a non-empty string, acquired_at YYYY-MM-DDTHH:MM:SSZ, ttl_seconds an integer in 1..MAX_TTL (what claim
+ * accepts), generation an integer >= 1. Lenient (check
+ * outside enforcement mode, layout-1 stores written by older tools): a parseable acquired_at, ttl_seconds >= 0 (default
+ * LOCK_TTL when absent, as the sweep does), generation optional (0 when absent). Returns NULL or what is wrong. */
+typedef struct { const char *holder, *session; long acq, ttl; unsigned long long gen; } Lease;
+static const char *lease_parse(const J *e, int strict, Lease *l) {
+ memset(l, 0, sizeof *l);
+ if (!e || e->t != JOBJ) return "is not an object";
+ J *h = jget(e, "holder"); if (!h || h->t != JSTR || !*h->s) return "holder is not a non-empty string";
+ l->holder = h->s;
+ J *a = jget(e, "acquired_at");
+ if (!a || a->t != JSTR || !(strict ? iso_strict(a->s, &l->acq) : (l->acq = parse_iso(a->s)) >= 0)) return "acquired_at is not a YYYY-MM-DDTHH:MM:SSZ timestamp";
+ J *t = jget(e, "ttl_seconds"); unsigned long long v = LOCK_TTL;
+ if (t || strict) { if (!t || t->t != JNUM || !u64_str(t->s, &v) || v > (strict ? (unsigned long long)MAX_TTL : (unsigned long long)LONG_MAX / 4) || (strict && !v)) return strict ? "ttl_seconds is not an integer in 1..315360000" : "ttl_seconds is not a positive integer"; }
+ l->ttl = (long)v;
+ J *g = jget(e, "generation");
+ if (g ? g->t != JNUM || !u64_str(g->s, &l->gen) || (strict && !l->gen) : strict) return "generation is not an integer >= 1";
+ if (strict) { J *s = jget(e, "session"); if (!s || s->t != JSTR || !*s->s) return "session is not a non-empty string"; l->session = s->s; }
+ return NULL;
+}
+static void malformed(const char *path, const char *key, const char *why) {
+ die("MALFORMED_LEASE: %s: lease \"%s\" %s; refusing (enforcement mode never prunes or takes over a malformed lease: fix or move it aside)", path, key, why);
+}
+/* enforcement mode: a dir record must be exactly what this tool writes before anything is swept or decided */
+static void dir_record_strict(const char *path, const J *j, const char *label) {
+ J *lk = jget(j, "locks"), *gens = jget(j, "generations");
+ if (lk && lk->t != JOBJ) die("MALFORMED_RECORD: %s: \"locks\" is not an object; refusing", path);
+ if (gens && gens->t != JOBJ) die("MALFORMED_RECORD: %s: \"generations\" is not an object; refusing", path);
+ if (gens) for (size_t i = 0; i < gens->n; i++) { unsigned long long g; if (gens->v[i]->t != JNUM || !u64_str(gens->v[i]->s, &g)) die("MALFORMED_RECORD: %s: generations[\"%s\"] is not an integer; refusing", path, gens->k[i]); }
+ if (lk) for (size_t i = 0; i < lk->n; i++) {
+ Lease l; const char *why = lease_parse(lk->v[i], 1, &l);
+ if (why) malformed(path, lk->k[i], why);
+ char *nk = norm_path(lk->k[i]), *kd = nk ? key_dir(nk) : NULL;
+ if (!nk || strcmp(nk, lk->k[i]) || strcmp(kd, label)) malformed(path, lk->k[i], "is not a normalised key of this directory record");
+ if (jgen(gens, lk->k[i]) != l.gen) malformed(path, lk->k[i], "has a generation that differs from the record's generations counter (the tool keeps them equal; a renewal would lower the high-water mark or reuse a token)");
+ free(nk); free(kd);
+ }
+}
+/* enforcement mode: an existing agent record must be what agent_set writes, or session ownership cannot be judged
+ * (crumb924 B3: a malformed session is an error, never "no session") */
+static void agent_record_strict(const char *path, const J *j) {
+ const char *why = NULL; J *s = jget(j, "session"), *u = jget(j, "updated_at"), *t = jget(j, "ttl_seconds"), *a = jget(j, "agent");
+ long acq; unsigned long long v;
+ if (!a || a->t != JSTR || !*a->s) why = "agent is not a non-empty string";
+ else if (!s || s->t != JSTR || !*s->s) why = "session is not a non-empty string";
+ else if (!u || u->t != JSTR || !iso_strict(u->s, &acq)) why = "updated_at is not a YYYY-MM-DDTHH:MM:SSZ timestamp";
+ else if (!t || t->t != JNUM || !u64_str(t->s, &v) || !v || v > (unsigned long long)MAX_TTL) why = "ttl_seconds is not an integer in 1..315360000";
+ if (why) die("MALFORMED_RECORD: %s: agent record: %s; refusing (enforcement mode never treats malformed session metadata as absent: fix or move it aside)", path, why);
+}
static Rec *rec_load(Txn *t, const char *path, int agent, const char *label) {
for (size_t i = 0; i < t->n; i++) if (!strcmp(t->r[i]->path, path)) return t->r[i];
Rec *r = xmalloc(sizeof *r); memset(r, 0, sizeof *r);
if (t->n == t->cap) { t->cap = t->cap ? t->cap * 2 : 16; t->r = xrealloc(t->r, t->cap * sizeof *t->r); }
t->r[t->n++] = r;
r->path = xstrdup(path); r->agent = agent;
- check_real_parents(t->p->store, path); /* never read through a symlinked directory (listing does not follow one) */
+ check_real_parents(t->p->root, path); /* never read through a symlinked directory (listing does not follow one) */
size_t len = 0; char *txt = read_bounded(path, MAX_RECORD_BYTES, &len); J *j = txt && strlen(txt) == len ? jparse(txt) : NULL;
if (txt && (!j || j->t != JOBJ)) die("%s is not valid JSON; fix or move it aside", path);
r->existed = txt != NULL;
if (!j) j = jnew(JOBJ);
+ if (!agent && g_enforce) dir_record_strict(path, j, label);
+ if (agent && g_enforce && r->existed) agent_record_strict(path, j);
if (!agent) {
if (!jget(j, "schema_version")) jset(j, "schema_version", jstr(SCHEMA));
if (!jget(j, "directory")) jset(j, "directory", jstr(label));
@@ -812,38 +1265,68 @@ static Rec *rec_load(Txn *t, const char *path, int agent, const char *label) {
r->root = j; r->before = jdump(j);
if (agent) {
long u = parse_iso(jstrval(j, "updated_at"));
- if (r->existed && (u < 0 || (long)time(NULL) - u > jlong(j, "ttl_seconds", SCENT_TTL))) r->dead = 1;
+ if (r->existed && (u < 0 || now_epoch() - u > jlong(j, "ttl_seconds", SCENT_TTL))) r->dead = 1;
} else sweep(j);
return r;
}
+/* Directory record path. "." is dirs/_root.json in both layouts. Layout 2 (crumb924 B2): a first component that
+ * starts with '_' gets one more '_' (`_root/x` -> dirs/__root/x.json, `_root` -> dirs/__root.json), so no repository
+ * directory can map onto dirs/_root.json or dirs/_root/ and every record name maps back to exactly one key directory
+ * (dir_label). Layout 1 keeps its historical mapping (where `_root` shares the root record) byte for byte. */
static char *dir_path(const Plane *p, const char *rel) {
if (!strcmp(rel, ".")) return pjoin(p->store, "dirs/_root.json");
- char *a = pjoin(p->store, "dirs"), *b = pjoin(a, rel), *c = xmalloc(strlen(b) + 6);
- sprintf(c, "%s.json", b); return c;
+ char *a = pjoin(p->store, "dirs"), *b, *c;
+ if (p->layout == 2 && rel[0] == '_') { size_t bn = strlen(a) + strlen(rel) + 3; b = xmalloc(bn); xsnprintf(b, bn, "%s/_%s", a, rel); }
+ else b = pjoin(a, rel);
+ size_t cn = strlen(b) + 6; c = xmalloc(cn);
+ xsnprintf(c, cn, "%s.json", b); free(a); free(b); return c;
+}
+/* the key directory a record name under dirs/ (without .json) stands for; NULL when no key maps to that name */
+static char *dir_label(const Plane *p, const char *name) {
+ if (!strcmp(name, "_root")) return xstrdup(".");
+ if (p->layout != 2 || name[0] != '_') return xstrdup(name);
+ return name[1] == '_' ? xstrdup(name + 1) : NULL;
}
static Rec *dir_rec(Txn *t, const char *rel) { return rec_load(t, dir_path(t->p, rel), 0, rel); }
static char *agent_path(const Plane *p, const char *agent) {
- char *n = xstrdup(agent);
- for (char *s = n; *s; s++) if (!((*s >= 'a' && *s <= 'z') || (*s >= 'A' && *s <= 'Z') || (*s >= '0' && *s <= '9') || *s == '.' || *s == '-' || *s == '_')) *s = '_';
- char *a = pjoin(p->store, "agents"), *b = pjoin(a, n), *c = xmalloc(strlen(b) + 6);
- sprintf(c, "%s.json", b); return c;
+ char *n = xstrdup(agent); /* layout 1: legacy sanitising (aliases possible); layout 2: the validated id verbatim */
+ if (p->layout != 2) for (char *s = n; *s; s++) if (!((*s >= 'a' && *s <= 'z') || (*s >= 'A' && *s <= 'Z') || (*s >= '0' && *s <= '9') || *s == '.' || *s == '-' || *s == '_')) *s = '_';
+ char *a = pjoin(p->store, "agents"), *b = pjoin(a, n); size_t cn = strlen(b) + 6; char *c = xmalloc(cn);
+ xsnprintf(c, cn, "%s.json", b); return c;
}
static Rec *agent_rec(Txn *t, const char *agent) { return rec_load(t, agent_path(t->p, agent), 1, NULL); }
/* Record names under dir, recursively, without opening any entry: lstat, so real subdirectories are walked and
* symlinked directories are not (no escape from the store, no symlink loop). Every other name ending in .json is
- * returned whatever its type; read_bounded then refuses a non-regular one without opening it. */
-static void collect_json(const char *dir, char ***out, size_t *n) {
- DIR *d = opendir(dir); if (!d) return;
+ * returned whatever its type; read_bounded then refuses a non-regular one without opening it. A missing top
+ * directory is empty state. Any other failure to list (permissions, I/O, a vanished subdirectory) is fatal in
+ * enforcement mode and a stderr warning otherwise: it is never silently treated as empty. */
+static void walk_fail(const char *what, const char *path) {
+ if (g_enforce) die("STORE_UNREADABLE: cannot %s %s: %s; refusing (enforcement mode never treats unreadable state as empty)", what, path, strerror(errno));
+ fprintf(stderr, "crumb: warning: cannot %s %s: %s; records under it are ignored (enforcement mode refuses this)\n", what, path, strerror(errno));
+}
+static void collect_json_at(const char *dir, char ***out, size_t *n, int top) {
+ DIR *d = opendir(dir);
+ if (!d) { if (!(top && errno == ENOENT)) walk_fail("open directory", dir); return; }
struct dirent *e;
- while ((e = readdir(d))) {
+ for (;;) {
+ errno = 0;
+ if (!(e = readdir(d))) { if (errno) walk_fail("read directory", dir); break; }
if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue;
char *full = pjoin(dir, e->d_name); struct stat st;
- if (lstat(full, &st) == 0 && S_ISDIR(st.st_mode)) collect_json(full, out, n);
+ int ls = lstat(full, &st);
+ if (ls != 0 && g_enforce) walk_fail("stat", full);
+ if (ls == 0 && S_ISLNK(st.st_mode)) { /* never followed; in enforcement mode never skipped either (crumb924 B1) */
+ if (g_enforce) refuse(full, "is a symbolic link inside the coordination records (never followed; enforcement mode refuses to skip the records it may hide)");
+ size_t l = strlen(e->d_name);
+ if (!(l > 5 && !strcmp(e->d_name + l - 5, ".json"))) { fprintf(stderr, "crumb: warning: %s is a symbolic link; it is not walked and records under it are ignored (enforcement mode refuses this)\n", full); free(full); continue; }
+ }
+ if (ls == 0 && S_ISDIR(st.st_mode)) collect_json_at(full, out, n, 0);
else { size_t l = strlen(e->d_name); if (l > 5 && !strcmp(e->d_name + l - 5, ".json")) { *out = xrealloc(*out, (*n + 1) * sizeof **out); (*out)[(*n)++] = full; continue; } }
free(full);
}
closedir(d);
}
+static void collect_json(const char *dir, char ***out, size_t *n) { collect_json_at(dir, out, n, 1); }
static void txn_prune(Txn *t) { /* load every record: expired entries drop out (written back on commit) */
char **f = NULL; size_t n = 0;
char *dd = pjoin(t->p->store, "dirs"), *ad = pjoin(t->p->store, "agents");
@@ -851,7 +1334,14 @@ static void txn_prune(Txn *t) { /* load every record: expired entries drop out
size_t pl = strlen(dd) + 1;
for (size_t i = 0; i < n; i++) {
char *rel = xstrdup(f[i] + pl); rel[strlen(rel) - 5] = 0;
- rec_load(t, f[i], 0, !strcmp(rel, "_root") ? "." : rel);
+ char *label = dir_label(t->p, rel);
+ if (!label) { /* layout 2: a '_' name no key maps to (an older layout-2 build wrote it, or it was planted) */
+ if (g_enforce) die("MALFORMED_RECORD: %s is not a directory record name of layout 2 (a first component starting with '_' is stored as '__'; dirs/_root.json is only the repository root); refusing (fix or move it aside)", f[i]);
+ fprintf(stderr, "crumb: warning: %s is not a directory record name of layout 2; it is ignored (enforcement mode refuses this)\n", f[i]);
+ free(rel); continue;
+ }
+ rec_load(t, f[i], 0, label);
+ free(rel);
}
char **g = NULL; size_t m = 0;
collect_json(ad, &g, &m);
@@ -862,7 +1352,7 @@ static void txn_end(Txn *t, int commit) {
Rec *r = t->r[i];
if (r->dead) { if (unlink(r->path) == 0) { char *d = dir_of(r->path); fsync_dir(d); free(d); } continue; }
char *now = jdump(r->root);
- if (strcmp(now, r->before)) durable_write(t->p->store, r->path, now);
+ if (strcmp(now, r->before)) durable_write(t->p->root, r->path, now);
}
if (t->fd >= 0) close(t->fd); /* releases the OS lock */
}
@@ -882,7 +1372,8 @@ static int agent_has_lock(Txn *t, const char *agent) {
}
static void import_legacy(Txn *t) { /* one-time merge of this worktree's .crumb.local into the shared store */
Plane *p = t->p;
- char *lp = pjoin(p->abs, ".crumb.local"), *txt = slurp(lp);
+ if (p->layout == 2) return; /* layout 2 never imports .crumb.local (plane_require warns when one is present) */
+ char *lp = pjoin(p->abs, ".crumb.local"), *txt = read_local(lp);
if (!txt) return;
J *l = jparse(txt);
if (!l || l->t != JOBJ) die("%s is not valid JSON; fix or move it aside", lp);
@@ -927,11 +1418,48 @@ static void print_lock(const char *key, const J *e) {
printf(" lock %-16s held by %s [%s]: %s [%s]%s%s\n", key, sv(e, "holder"), sv(e, "branch"), sv(e, "intent"), sv(e, "acquired_at"),
jstrval(e, "imported_from") ? " imported from " : "", jstrval(e, "imported_from") ? jstrval(e, "imported_from") : "");
}
+/* anc is k itself or one of its ancestor keys ("." is the whole repository) */
+static int key_covers(const char *anc, const char *k) {
+ if (!strcmp(anc, ".") || !strcmp(anc, k)) return 1;
+ size_t n = strlen(anc);
+ return !strncmp(k, anc, n) && k[n] == '/';
+}
+/* enforcement mode: an agent id names exactly one live session; a second session presenting it is refused (exit 2).
+ * Live means a live heartbeat from another session, or a live lease of this id recorded by another session: the
+ * heartbeat can expire long before the lease, and the lease's session decides who may renew or close it (crumb924 B3).
+ * Every dir record is loaded and swept (txn_prune) before this runs, so the leases left are the live ones. */
+static int agent_in_use(Txn *t, const char *agent) {
+ if (!g_enforce) return 0;
+ Rec *r = agent_rec(t, agent);
+ const char *s = jstrval(r->root, "session");
+ char *me = session_id(agent);
+ if (r->existed && !r->dead && s && strcmp(s, me)) {
+ printf("BLOCKED agent %s is live in session %s, not this session %s (an agent id names one session: use <agent-name>.<session-id>)\n", agent, s, me);
+ free(me); return 1;
+ }
+ for (size_t i = 0; i < t->n; i++) if (!t->r[i]->agent) {
+ J *lk = jget(t->r[i]->root, "locks");
+ if (lk && lk->t == JOBJ) for (size_t k = 0; k < lk->n; k++) {
+ const char *h = jstrval(lk->v[k], "holder"), *ls = jstrval(lk->v[k], "session");
+ if (!h || strcmp(h, agent)) continue;
+ if (!ls) die("MALFORMED_LEASE: %s: lease \"%s\" has no session; refusing", t->r[i]->path, lk->k[k]); /* dir_record_strict already refused it */
+ if (strcmp(ls, me)) {
+ printf("BLOCKED agent %s is live in session %s, not this session %s (live lease on %s generation %s; an agent id names one session: use <agent-name>.<session-id>)\n", agent, ls, me, lk->k[k], jget(lk->v[k], "generation") ? jget(lk->v[k], "generation")->s : "?");
+ free(me); return 1;
+ }
+ }
+ }
+ free(me);
+ return 0;
+}
static int cmd_claim(const char *agent, const char *dir, const char *target, const char *intent, long ttl) {
Plane *p = plane_resolve(dir);
if (!p) return legacy_claim(agent, dir, target, intent, ttl);
+ agent_require(p, agent);
+ if (g_enforce && ttl <= 0) die("enforcement mode needs a positive ttl (got %ld)", ttl);
char *key = target_key(p, target, p->rel), *td = key_dir(key);
Txn *t = txn_begin(p, 1); txn_prune(t); import_legacy(t);
+ if (agent_in_use(t, agent)) { txn_end(t, 0); return 2; }
Rec *tr = dir_rec(t, td);
J *cur = jget(jobj_of(tr->root, "locks"), key);
if (cur) {
@@ -942,21 +1470,37 @@ static int cmd_claim(const char *agent, const char *dir, const char *target, con
return 2;
}
}
+ /* no overlap: another agent's valid lease on an ancestor or a descendant of key blocks too (expired ones are pruned) */
+ for (size_t i = 0; i < t->n; i++) if (!t->r[i]->agent) {
+ J *lk = jget(t->r[i]->root, "locks");
+ if (lk && lk->t == JOBJ) for (size_t k = 0; k < lk->n; k++) {
+ const char *h = jstrval(lk->v[k], "holder");
+ if (!h || !strcmp(h, agent) || !(key_covers(lk->k[k], key) || key_covers(key, lk->k[k]))) continue;
+ J *o = lk->v[k];
+ printf("BLOCKED %s held by %s on branch %s (worktree %s) since %s (%s) [overlapping lease on %s]\n", key, h, sv(o, "branch"), sv(o, "worktree"), sv(o, "acquired_at"), sv(o, "intent"), lk->k[k]);
+ txn_end(t, 1);
+ return 2;
+ }
+ }
char ts[21]; now_iso(ts);
+ unsigned long long gen = gen_next(tr->root, tr->path, key, cur, agent);
J *e = jnew(JOBJ);
jset(e, "holder", jstr(agent)); jset(e, "session", jstr(session_id(agent))); jset(e, "target", jstr(key)); jset(e, "intent", jstr(intent));
jset(e, "worktree", jstr(p->top)); jset(e, "branch", jstr(p->branch)); jset(e, "head", jstr(p->head)); jset(e, "base", jstr(p->base));
- jset(e, "acquired_at", jstr(ts)); jset(e, "ttl_seconds", jnum(ttl));
+ jset(e, "acquired_at", jstr(ts)); jset(e, "ttl_seconds", jnum(ttl)); jset(e, "generation", jnum_u64(gen));
jset(jobj_of(tr->root, "locks"), key, e);
agent_set(t, agent, intent, SCENT_TTL > ttl ? SCENT_TTL : ttl);
txn_end(t, 1);
- printf("CLAIMED %s in %s as %s on %s (ttl %lds)\n", key, p->top, agent, p->branch, ttl);
+ printf("CLAIMED %s in %s as %s on %s (ttl %lds) generation %llu\n", key, p->top, agent, p->branch, ttl, gen);
return 0;
}
static int cmd_update(const char *agent, const char *dir, const char *focus, long ttl) {
Plane *p = plane_resolve(dir);
if (!p) return legacy_update(agent, dir, focus, ttl);
+ agent_require(p, agent);
+ if (g_enforce && ttl <= 0) die("enforcement mode needs a positive ttl (got %ld)", ttl); /* the strict agent record reader refuses ttl 0 */
Txn *t = txn_begin(p, 1); txn_prune(t); import_legacy(t);
+ if (agent_in_use(t, agent)) { txn_end(t, 0); return 2; }
agent_set(t, agent, focus, ttl);
txn_end(t, 1);
printf("SCENT %s in %s: %s (ttl %lds)\n", agent, p->abs, focus, ttl);
@@ -966,6 +1510,7 @@ static int cmd_whisper(const char *from, const char *dir, const char *to, const
if (prio && *prio && strcmp(prio, "low") && strcmp(prio, "normal") && strcmp(prio, "high") && strcmp(prio, "critical")) die("priority must be low|normal|high|critical");
Plane *p = plane_resolve(dir);
if (!p) return legacy_whisper(from, dir, to, msg, prio, tf);
+ agent_require(p, from);
Txn *t = txn_begin(p, 1); txn_prune(t); import_legacy(t);
whisper_add(dir_rec(t, p->rel)->root, from, to, msg, prio, tf);
txn_end(t, 1);
@@ -978,8 +1523,10 @@ static int cmd_close(const char *agent, const char *dir, const char *target, con
if (!good) die("action must be create|modify|delete|audit|test|build");
Plane *p = plane_resolve(dir);
if (!p) return legacy_close(agent, dir, target, action, msg);
+ agent_require(p, agent);
char *key = target_key(p, target, p->rel), *td = key_dir(key);
Txn *t = txn_begin(p, 1); txn_prune(t); import_legacy(t);
+ if (agent_in_use(t, agent)) { txn_end(t, 0); return 2; }
Rec *tr = dir_rec(t, td);
J *lk = jobj_of(tr->root, "locks"), *cur = jget(lk, key);
const char *intent = "";
@@ -996,8 +1543,77 @@ static int cmd_close(const char *agent, const char *dir, const char *target, con
printf("CLOSED %s in %s by %s (%s)%s\n", key, p->top, agent, action, cur ? "" : " [no lock was held]");
return 0;
}
+/* check <agent> <dir> <target> [--generation N] (crumb924; the pre-write guard the session bridge calls).
+ * Read-only: a shared fcntl lock on <root>/.lock (never created) for a consistent read; nothing is created, swept,
+ * pruned or written. The leases on target and on every ancestor key (up to "." = the whole repository) are judged
+ * with the strict schema in enforcement mode (lenient otherwise; malformed = exit 1 either way). Exit 0 only when a
+ * valid lease on target or an ancestor is held by exactly <agent>, no other agent holds a valid lease on target or
+ * an ancestor, and (when given) the nearest such lease has generation N and key K. Generations are counted per key,
+ * so a bare number is ambiguous across keys (an ancestor lease can carry the same number later); a writer that
+ * re-checks a token passes both --key and --generation, exactly as printed on the HELD line. Exit 2 otherwise. */
+static int cmd_check(const char *agent, const char *dir, const char *target, int has_want, unsigned long long want, const char *want_key) {
+ Plane *p = plane_resolve(dir);
+ if (!p) die("check needs a git repository: %s", dir);
+ agent_require(p, agent);
+ char *key = target_key(p, target, p->rel);
+ int fd = root_lock(p->root, 0);
+ if (fd < 0 && store_used(p)) /* crumb924 B4: an initialized store without its lock is broken, not empty */
+ die("STORE_LOCK_MISSING: coordination root %s is in use (layout %d%s) but has no .lock; refusing to report a lease without a consistent read (check never creates the lock)", p->root, p->layout, g_enforce ? ", enforcement mode" : "");
+ ident_gate(&p->id, p->root, 0); /* again under the lock: the root may have been swapped meanwhile */
+ if (read_layout(p->root) != p->layout) die("STORE_LAYOUT_CHANGED: coordination root %s changed layout while this command ran (store-init); retry", p->root);
+ long now = now_epoch();
+ const char *mine_key = NULL, *other_key = NULL, *exp_key = NULL; Lease mine, other, gone;
+ memset(&mine, 0, sizeof mine); memset(&other, 0, sizeof other); memset(&gone, 0, sizeof gone);
+ char *k = xstrdup(key), *loaded_path = NULL; J *rec = NULL;
+ for (;;) {
+ char *kd = key_dir(k), *path = dir_path(p, kd);
+ if (!loaded_path || strcmp(loaded_path, path)) {
+ check_real_parents(p->root, path);
+ size_t len = 0; char *txt = read_bounded(path, MAX_RECORD_BYTES, &len);
+ rec = txt && strlen(txt) == len ? jparse(txt) : NULL;
+ if (txt && (!rec || rec->t != JOBJ)) die("%s is not valid JSON; fix or move it aside", path);
+ if (rec && g_enforce) dir_record_strict(path, rec, kd);
+ J *lk0 = jget(rec, "locks");
+ if (lk0 && lk0->t != JOBJ) die("MALFORMED_RECORD: %s: \"locks\" is not an object; refusing", path);
+ loaded_path = path;
+ }
+ J *e = jget(jget(rec, "locks"), k);
+ if (e) {
+ Lease l; const char *why = lease_parse(e, g_enforce, &l);
+ if (why) malformed(loaded_path, k, why);
+ int valid = now - l.acq <= l.ttl; /* now - acquired_at == ttl is still valid; ttl + 1 is expired */
+ if (!valid) { if (!exp_key) { exp_key = xstrdup(k); gone = l; } }
+ else if (!strcmp(l.holder, agent)) { if (!mine_key) { mine_key = xstrdup(k); mine = l; } }
+ else if (!other_key) { other_key = xstrdup(k); other = l; }
+ }
+ if (!strcmp(k, ".")) break;
+ char *up = strchr(k, '/') ? dir_of(k) : xstrdup(".");
+ free(k); k = up; free(kd);
+ }
+ if (fd >= 0) close(fd);
+ char ex[21];
+ if (other_key) {
+ iso_of(other.acq + other.ttl, ex);
+ printf("REFUSED held-by %s %s key %s generation %llu expires %s\n", other.holder, key, other_key, other.gen, ex);
+ return 2;
+ }
+ if (mine_key) {
+ iso_of(mine.acq + mine.ttl, ex);
+ if (want_key && strcmp(mine_key, want_key)) { printf("REFUSED key %s!=%s %s generation %llu by %s expires %s\n", mine_key, want_key, key, mine.gen, agent, ex); return 2; }
+ if (has_want && mine.gen != want) { printf("REFUSED generation %llu!=%llu %s key %s by %s expires %s\n", mine.gen, want, key, mine_key, agent, ex); return 2; }
+ printf("HELD %s by %s key %s generation %llu expires %s\n", key, agent, mine_key, mine.gen, ex);
+ return 0;
+ }
+ if (exp_key) {
+ iso_of(gone.acq + gone.ttl, ex);
+ printf("REFUSED expired %s key %s holder %s generation %llu expired %s\n", key, exp_key, gone.holder, gone.gen, ex);
+ return 2;
+ }
+ printf("REFUSED absent %s (no lease on it or any ancestor)\n", key);
+ return 2;
+}
static void print_agent(const J *e, const char *name) {
- long u = parse_iso(jstrval(e, "updated_at")), age = u < 0 ? -1 : (long)time(NULL) - u;
+ long u = parse_iso(jstrval(e, "updated_at")), age = u < 0 ? -1 : now_epoch() - u;
printf(" agent %-16s branch %s focus: %s heartbeat %lds ago [%s]\n", name, sv(e, "branch"), sv(e, "focus"), age, sv(e, "worktree"));
}
static int cmd_sniff(const char *agent, const char *dir) { /* SPEC 5.1 + RFC-0002 */
@@ -1007,6 +1623,7 @@ static int cmd_sniff(const char *agent, const char *dir) { /* SPEC 5.1 + RFC-0
printf("shared coordination: none (not a git repository)\n");
return r;
}
+ agent_require(p, agent);
char *cp = pjoin(p->abs, ".crumb"), *txt = slurp(cp); J *c = txt ? jparse(txt) : NULL;
printf("sniff %s as %s\n", p->abs, agent);
if (c) {
@@ -1015,7 +1632,9 @@ static int cmd_sniff(const char *agent, const char *dir) { /* SPEC 5.1 + RFC-0
if (inv && inv->t == JARR) for (size_t i = 0; i < inv->n; i++) if (inv->v[i]->t == JSTR) printf(" invariant: %s\n", inv->v[i]->s);
} else printf(" no .crumb here\n");
Txn *t = txn_begin(p, 0); txn_prune(t); import_legacy(t); /* read side: merged in memory, never saved */
- printf("shared coordination: ACTIVE\n common root: %s\n this worktree: %s [%s %s]\nACTIVE AGENTS\n", p->store, p->top, p->branch, p->head);
+ printf("shared coordination: ACTIVE\n common root: %s\n", p->root);
+ if (p->layout == 2) printf(" repository: %s (layout 2, id from %s)\n", p->repo_id, p->repo_src);
+ printf(" this worktree: %s [%s %s]\nACTIVE AGENTS\n", p->top, p->branch, p->head);
int any = 0;
for (size_t i = 0; i < t->n; i++) if (t->r[i]->agent && !t->r[i]->dead && jget(t->r[i]->root, "updated_at")) { print_agent(t->r[i]->root, sv(t->r[i]->root, "agent")); any = 1; }
if (!any) printf(" (none)\n");
@@ -1324,7 +1943,7 @@ static void walk_list(const char *path, const char *rel, int depth, int validate
}
}
}
- if (!validate && !g_skip_local && slurp(lp)) {
+ if (!validate && !g_skip_local && read_local(lp)) {
Local l = local_open(path); /* read side: sweep applied in memory, never saved */
J *sc = jget(l.root, "active_scents"), *lk = jget(l.root, "locks"), *wh = jget(l.root, "whispers");
if ((sc && sc->n) || (lk && lk->n) || (wh && wh->n)) { t->n_local++; printf("%s\n", rel); show_local(path, l.root, NULL); }
@@ -1426,7 +2045,8 @@ static void lr_add(const char *lane, const char *note, const char *ref, long pr,
LaneRef *r = &g_lr[g_nlr++]; r->lane = xstrdup(lane); r->note = xstrdup(note); r->ref = xstrdup(ref); r->pr = pr; r->repo = repo ? xstrdup(repo) : NULL; r->sha = sha ? xstrdup(sha) : NULL; r->id = id;
}
static void parse_lane_file(const char *path) {
- FILE *f = fopen(path, "r"); if (!f) return;
+ int lfd = crumb_open_follow(path, O_RDONLY, 0); if (lfd < 0) return; /* the operator's own report (may be a link) */
+ FILE *f = fdopen(lfd, "r"); if (!f) { close(lfd); return; }
const char *bn = base_of(path), *fl = strstr(bn, "lane"); char filelane[24] = "";
if (fl && isdigit((unsigned char)fl[4])) { int k = 0; fl += 4; while (isdigit((unsigned char)*fl) && k < 8) { filelane[k++] = *fl++; } filelane[k] = 0; }
char *line = NULL; size_t lc = 0; ssize_t len; static int idc = 0; int id;
@@ -1537,7 +2157,7 @@ static void backfill_node(const Node *n, int depth, const char *repo, BfStats *s
}
static int cmd_backfill(const char *root, const char *since, int dry) {
char *r = absdir(root);
- char *home = getenv("HOME"); if (!home) home = "";
+ char *home = getenv("HOME"); home = home ? canon_dotdot(home) : xstrdup("");
load_ignore(r);
Node *tree = scan(r, ".", 1);
char *remote = run_git(r, "remote get-url origin"), *repo = xstrdup(base_of(remote));
@@ -1633,8 +2253,7 @@ static int cmd_explain(const char *target) {
size_t tl = strlen(top);
rel = abs[tl] ? xstrdup(abs + tl + 1) : xstrdup(".");
} else rel = xstrdup(base_of(abs));
- char *store = p ? p->store : (env && *env ? xstrdup(env) : NULL);
- if (!p && store) { Ident id = ident_resolve(NULL); ident_gate(&id, store, 0); } /* no repository: env-only identity */
+ char *store = p ? p->store : (env && *env ? env_store(canon_dotdot(env)) : NULL); /* no repository: env-only identity */
printf("EXPLAIN %s\n repository path: %s\n", abs, rel);
/* 1. nearest .crumb */
@@ -1734,6 +2353,7 @@ static int cmd_explain(const char *target) {
collect_json(cd, &f, &n);
for (size_t i = 0; i < n; i++) {
char *txt = read_bounded(f[i], MAX_RECORD_BYTES, NULL); J *c = txt ? jparse(txt) : NULL;
+ if (g_enforce && (!c || c->t != JOBJ)) die("%s is not valid JSON; refusing (enforcement mode never skips unreadable state)", f[i]);
if (!c || c->t != JOBJ || !jget(c, "identity") || !cont_matches(c, rel)) continue;
nmatch++;
J *ev = jget(c, "evidence");
@@ -1765,13 +2385,20 @@ static char *cc_path(void) {
const char *h = getenv("HOME");
if (!h || !*h) die("HOME is not set; set CRUMB_CC to the path of cc.sh");
size_t n = strlen(h) + 64; char *s = xmalloc(n);
- snprintf(s, n, "%s/.claude/skills/checkpoint/scripts/cc.sh", h); return s;
+ xsnprintf(s, n, "%s/.claude/skills/checkpoint/scripts/cc.sh", h); return s;
}
-static void cc_env(Plane *p) { /* records must land in <coordination root>/continuations */
+static void cc_env(Plane *p) { /* records must land in <coordination root>/continuations (layout 2: the namespace's) */
const char *env = getenv("CRUMB_COORD_ROOT");
- if (p) setenv("CRUMB_COORD_ROOT", p->store, 1);
+ if (p && p->layout == 2) {
+ char *cs = pjoin(p->store, "continuations");
+ setenv("CRUMB_COORD_ROOT", p->root, 1); setenv("CC_STORE", cs, 1); setenv("CRUMB_REPO_ID", p->repo_id, 1);
+ } else if (p) setenv("CRUMB_COORD_ROOT", p->store, 1);
else if (!(env && *env)) die("no repository context: run inside a git checkout or set CRUMB_COORD_ROOT");
- else { Ident id = ident_resolve(NULL); ident_gate(&id, env, 0); }
+ else { /* a ".." in the root is resolved here (canon_dotdot), for this process and for cc.sh alike */
+ char *rt = canon_dotdot(env), *st = env_store(rt);
+ if (strcmp(rt, env)) setenv("CRUMB_COORD_ROOT", rt, 1);
+ if (strcmp(st, rt)) { char *cs = pjoin(st, "continuations"); setenv("CC_STORE", cs, 1); }
+ }
char self[PATH_MAX]; ssize_t n = readlink("/proc/self/exe", self, sizeof self - 1);
if (n > 0 && !getenv("CRUMB_BIN")) { self[n] = 0; setenv("CRUMB_BIN", self, 1); }
}
@@ -1823,7 +2450,18 @@ static int cmd_resume(const char *id) {
return 1;
}
-static long ttl_arg(const char *s, long dflt) { if (!s) return dflt; char *e; long v = strtol(s, &e, 10); if (*e || v < 0) die("bad ttl: %s", s); return v; }
+/* decimal seconds, 0..MAX_TTL, nothing else (no sign, no spaces, no overflow): the writer accepts exactly what every
+ * reader accepts (crumb924 B5; the strict reader refuses ttl_seconds above MAX_TTL, enforcement also refuses 0) */
+static long ttl_arg(const char *s, long dflt) {
+ if (!s) return dflt;
+ long v = 0;
+ for (const char *c = s; *c; c++) {
+ if (*c < '0' || *c > '9' || v > (MAX_TTL - (*c - '0')) / 10) die("bad ttl: %s (expected 0..%ld seconds)", s, MAX_TTL);
+ v = v * 10 + (*c - '0');
+ }
+ if (!*s) die("bad ttl: (empty) (expected 0..%ld seconds)", MAX_TTL);
+ return v;
+}
/* ---------- RFC-0003: Crumb Compiler (C port of crumb-compile.sh; design decisions D1-D9 there are binding) ----------
* compile/verify/status: hand-authored kernel stays, everything structural is generated bottom-up into
* .crumb extensions.generated with Merkle digests. Output is byte-identical to the shell reference. */
@@ -2078,7 +2716,7 @@ static int root_on_demand(const char *top) {
}
static void write_crumb(const char *full, J *cr) { /* D9: key-sorted, temp file then rename */
jsort(cr);
- char *out = jdump(cr), *tmp = xmalloc(strlen(full) + 32); snprintf(tmp, strlen(full) + 32, "%s.tmp.%ld", full, (long)getpid());
+ char *out = jdump(cr), *tmp = xmalloc(strlen(full) + 32); xsnprintf(tmp, strlen(full) + 32, "%s.tmp.%ld", full, (long)getpid());
FILE *f = fcreate(tmp, 0); if (!f) die("cannot write %s", tmp);
if (fputs(out, f) < 0 || fclose(f) != 0) die("write failed: %s", tmp);
if (rename(tmp, full)) die("rename failed: %s", full);
@@ -2157,7 +2795,7 @@ static int compile_engine(char mode, const char *root, int quiet, int *total_out
J *x = jget(cr, "extensions"); if (!x || x->t != JOBJ) { x = jnew(JOBJ); jset(cr, "extensions", x); }
J *g = jclone(nw); jset(g, "generated_at_commit", jstr(head)); jset(g, "compiled_at", jstr(stamp));
jset(x, "generated", g); jsort(cr);
- char *out = jdump(cr), *tmp = xmalloc(strlen(full) + 32); snprintf(tmp, strlen(full) + 32, "%s.tmp.%ld", full, (long)getpid());
+ char *out = jdump(cr), *tmp = xmalloc(strlen(full) + 32); xsnprintf(tmp, strlen(full) + 32, "%s.tmp.%ld", full, (long)getpid());
FILE *f = fcreate(tmp, 0); if (!f) die("cannot write %s", tmp);
if (fputs(out, f) < 0 || fclose(f) != 0) die("write failed: %s", tmp);
if (rename(tmp, full)) die("rename failed: %s", full);
@@ -2277,6 +2915,7 @@ static int cmd_context(const char *target) {
{ char **f = NULL; size_t n = 0; char *cd = pjoin(p->store, "continuations"); collect_json(cd, &f, &n);
for (size_t i = 0; i < n; i++) {
char *txt = read_bounded(f[i], MAX_RECORD_BYTES, NULL); J *c = txt ? jparse(txt) : NULL;
+ if (g_enforce && (!c || c->t != JOBJ)) die("%s is not valid JSON; refusing (enforcement mode never skips unreadable state)", f[i]);
if (!c || c->t != JOBJ || !jget(c, "identity") || !cont_matches(c, rel)) continue;
nmatch++; if (!best || strcmp(cont_when(c), cont_when(best)) > 0) { best = c; bestf = f[i]; }
} }
@@ -2296,17 +2935,95 @@ static int cmd_context(const char *target) {
static int cmd_store_id(const char *dir) {
Plane *p = plane_find(dir);
if (!p) die("store-id needs a git repository: %s", dir);
- if (p->id.has_expect) ident_gate(&p->id, p->store, 0);
+ if (p->id.has_expect) ident_gate(&p->id, p->root, 0);
+ else if (p->layout == 2) { p->id.warned = 1; int fd = root_lock(p->root, 1); ident_gate(&p->id, p->root, 1); close(fd); }
else { p->id.warned = 1; Txn *t = txn_begin(p, 1); txn_end(t, 0); }
char hex[33];
- if (!read_marker(p->store, hex)) die_x(EXIT_STORE_ID, "STORE_ID_MISSING: coordination store %s has no %s marker", p->store, STORE_ID_FILE);
+ if (!read_marker(p->root, hex)) die_x(EXIT_STORE_ID, "STORE_ID_MISSING: coordination store %s has no %s marker", p->root, STORE_ID_FILE);
printf("%s\n", hex);
- if (!p->id.has_expect) fprintf(stderr, "crumb: coordination store %s is unregistered; register it: git config crumb.storeId %s\n", p->store, hex);
+ if (!p->id.has_expect) fprintf(stderr, "crumb: coordination store %s is unregistered; register it: git config crumb.storeId %s\n", p->root, hex);
+ return 0;
+}
+/* store-init's proof that a layout-1 record directory (dirs/, agents/, continuations/) holds nothing, independent of
+ * enforcement mode (crumb924 B8): absent, or a real directory whose whole tree is real (empty) subdirectories only.
+ * Every open/read failure, symbolic link, record or other file refuses: an inspection that could not see everything
+ * is never taken for an empty store. With rm set (only after every directory has been proved), the empty tree is
+ * removed bottom-up and a failed removal refuses too (a file added since the proof makes the removal fail: refused).
+ * The walk is descriptor-relative (openat with O_DIRECTORY|O_NOFOLLOW from the parent's descriptor, unlinkat on the
+ * same descriptor), so no name is checked by one call and then used by another (no check-to-use window, CodeQL
+ * cpp/toctou-race-condition). pfd is the parent directory, name the entry in it, shown the path for messages. */
+static void legacy_empty(const char *root, int pfd, const char *name, const char *shown, int top, int rm) {
+ int fd = openat(pfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC);
+ if (fd < 0) {
+ int er = errno;
+ if (top && er == ENOENT) return;
+ /* Linux reports a link to a directory as ENOTDIR under O_DIRECTORY; which refusal to print is decided after the
+ * failed open (every branch here refuses, so the lookup only picks the message) */
+ struct stat st;
+ if (er == ELOOP || (er == ENOTDIR && fstatat(pfd, name, &st, AT_SYMLINK_NOFOLLOW) == 0 && S_ISLNK(st.st_mode)))
+ die("STORE_LAYOUT_V1_UNPROVEN: %s is a symbolic link; refusing to make %s a layout-2 root (records behind it cannot be proved absent): move it aside", shown, root);
+ if (er == ENOTDIR) {
+ size_t l = strlen(name);
+ if (!top && l > 5 && !strcmp(name + l - 5, ".json")) die("STORE_LAYOUT_V1_DATA: %s is a layout-1 record; refusing to make %s a layout-2 root (their locks would silently vanish): use a new empty root, or close every lease and move dirs/ agents/ continuations/ aside first", shown, root);
+ die("STORE_LAYOUT_V1_UNPROVEN: %s is not a directory; refusing to make %s a layout-2 root until it is moved aside", shown, root);
+ }
+ die("STORE_LAYOUT_V1_UNPROVEN: cannot open directory %s: %s; refusing to make %s a layout-2 root without proving the layout-1 records empty", shown, strerror(er), root);
+ }
+ DIR *d = fdopendir(fd);
+ if (!d) { int er = errno; close(fd); die("STORE_LAYOUT_V1_UNPROVEN: cannot open directory %s: %s; refusing to make %s a layout-2 root without proving the layout-1 records empty", shown, strerror(er), root); }
+ struct dirent *e;
+ for (;;) {
+ errno = 0;
+ if (!(e = readdir(d))) { if (errno) die("STORE_LAYOUT_V1_UNPROVEN: cannot read directory %s: %s; refusing to make %s a layout-2 root without proving the layout-1 records empty", shown, strerror(errno), root); break; }
+ if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue;
+ char *full = pjoin(shown, e->d_name);
+ legacy_empty(root, dirfd(d), e->d_name, full, 0, rm);
+ free(full);
+ }
+ closedir(d);
+ if (rm && unlinkat(pfd, name, AT_REMOVEDIR) != 0) die("STORE_LAYOUT_V1_UNPROVEN: cannot remove empty %s: %s; refusing to make %s a layout-2 root", shown, strerror(errno), root);
+}
+/* store-init [dir] (crumb924): make the coordination root a layout-2 (repository-namespaced) root, deliberately.
+ * Under the root lock: STORE_ID as store-id does (registered: must match, never created); then LAYOUT is published
+ * once (link(2), never replaced) and repos/ created. Refused unless dirs/ agents/ continuations/ are proved empty
+ * whatever the enforcement mode (legacy_empty), so old locks are never silently dropped or reinterpreted.
+ * Idempotent on a layout-2 root. */
+static int cmd_store_init(const char *dir) {
+ Plane *p = plane_find(dir);
+ if (!p) die("store-init needs a git repository: %s", dir);
+ if (p->id.has_expect) ident_gate(&p->id, p->root, 0);
+ mkdir_p(p->root);
+ int fd = root_lock(p->root, 1);
+ p->id.warned = 1; ident_gate(&p->id, p->root, 1);
+ int created = 0;
+ if (read_layout(p->root) != 2) {
+ static const char *flat[] = { "dirs", "agents", "continuations", NULL };
+ int rfd = crumb_open_follow(p->root, O_RDONLY | O_DIRECTORY, 0); /* the root may be named through a link */
+ if (rfd < 0) die("STORE_LAYOUT_V1_UNPROVEN: cannot open coordination root %s: %s", p->root, strerror(errno));
+ for (int pass = 0; pass < 2; pass++) /* prove all three first; only then remove the empty trees */
+ for (int i = 0; flat[i]; i++) { char *d = pjoin(p->root, flat[i]); legacy_empty(p->root, rfd, flat[i], d, 1, pass); free(d); }
+ char *ld = pjoin(p->root, "ledger"); /* never holds records; left in place when it is not empty */
+ if (unlinkat(rfd, "ledger", AT_REMOVEDIR) != 0 && errno != ENOENT && errno != ENOTEMPTY && errno != EEXIST) die("STORE_LAYOUT_V1_UNPROVEN: cannot remove empty %s: %s; refusing to make %s a layout-2 root", ld, strerror(errno), p->root);
+ free(ld); close(rfd);
+ char *lp = pjoin(p->root, LAYOUT_FILE);
+ publish_once(p->root, lp, LAYOUT_V2, strlen(LAYOUT_V2));
+ free(lp); created = 1;
+ }
+ if (read_layout(p->root) != 2) die("store-init: %s did not become layout 2", p->root);
+ char *rd = pjoin(p->root, "repos"); mkdir_p(rd); free(rd);
+ close(fd);
+ char hex[33];
+ if (!read_marker(p->root, hex)) die_x(EXIT_STORE_ID, "STORE_ID_MISSING: coordination store %s has no %s marker", p->root, STORE_ID_FILE);
+ if (!p->repo_id) p->repo_id = repo_id_resolve(p->abs, &p->repo_src);
+ printf("STORE_INIT %s layout crumb-coord-layout/2 store %s%s\n", p->root, hex, created ? "" : " (already layout 2)");
+ if (p->repo_id) printf("repository %s (from %s) -> %s/repos/%s\n", p->repo_id, p->repo_src, p->root, p->repo_id);
+ else printf("repository (none resolved: set git config crumb.repoId <owner>/<repo> before using this root)\n");
+ if (!p->id.has_expect) fprintf(stderr, "crumb: coordination store %s is unregistered; register it: git config crumb.storeId %s\n", p->root, hex);
return 0;
}
static void usage(void) {
- fputs("usage: crumb [--strict] <command> ...\n"
+ fputs("usage: crumb [--strict] [--enforce] <command> ...\n"
" seed <root> [-n] [-v] write/refresh .crumb files (idempotent; -n dry run)\n"
" backfill <root> [--since <date>] [-n] reconstruct history from git + lane reports (run after seed)\n"
" create <dir> <name> <purpose> [layer] new .crumb for one directory\n"
@@ -2328,13 +3045,20 @@ static void usage(void) {
" list [path] live scents, locks, whispers under path\n"
" validate [path] check .crumb files against RFC-0001 required fields\n"
" store-id [dir] print the coordination store id (creates it if unregistered and absent)\n"
+ " store-init [dir] make the coordination root layout 2 (repos/<repo-id>/ namespaces), deliberately\n"
+ " check <agent> <dir> <target> [--generation N] [--key K] read-only: exit 0 only if agent holds a valid lease on target or an ancestor\n"
"store identity: expected id from CRUMB_EXPECT_STORE_ID, else git config crumb.storeId; --strict or\n"
- " CRUMB_STRICT_STORE_ID=1 refuses unregistered stores. Exit 3 = store identity refusal, 4 = refused store file.\n", stderr);
+ " CRUMB_STRICT_STORE_ID=1 refuses unregistered stores. Exit 3 = store identity refusal, 4 = refused store file.\n"
+ "repository id (layout 2): CRUMB_REPO_ID, else git config crumb.repoId, else origin URL <owner>/<repo>.\n"
+ "enforcement (--enforce, CRUMB_ENFORCE=1, git config crumb.enforce true): registered store, layout 2, repo id,\n"
+ " verbatim agent ids, strict lease schema, no .crumb.local fallback, unreadable state is an error (exit 1).\n", stderr);
exit(1);
}
+static unsigned long long gen_arg(const char *s) { unsigned long long g; if (!u64_str(s, &g)) die("bad generation: %s (expected a decimal integer)", s); return g; }
int main(int argc, char **argv) {
{ const char *s = getenv("CRUMB_STRICT_STORE_ID"); if (s && !strcmp(s, "1")) g_strict = 1; }
- while (argc > 1 && !strcmp(argv[1], "--strict")) { g_strict = 1; argv++; argc--; }
+ { const char *s = getenv("CRUMB_ENFORCE"); if (s && bool_word(s, "CRUMB_ENFORCE")) enforce_on(); }
+ while (argc > 1 && (!strcmp(argv[1], "--strict") || !strcmp(argv[1], "--enforce"))) { if (!strcmp(argv[1], "--enforce")) enforce_on(); else g_strict = 1; argv++; argc--; }
if (argc < 2) usage();
const char *c = argv[1]; int a = argc - 2; char **v = argv + 2;
if (!strcmp(c, "seed") && a >= 1) {
@@ -2365,6 +3089,16 @@ int main(int argc, char **argv) {
if (!strcmp(c, "checkpoint")) return cmd_checkpoint(a, v);
if (!strcmp(c, "resume") && a == 1) return cmd_resume(v[0]);
if (!strcmp(c, "store-id") && a <= 1) return cmd_store_id(a ? v[0] : ".");
+ if (!strcmp(c, "store-init") && a <= 1) return cmd_store_init(a ? v[0] : ".");
+ if (!strcmp(c, "check") && a >= 3 && (a - 3) % 2 == 0 && a <= 7) {
+ int has_want = 0; unsigned long long want = 0; const char *want_key = NULL;
+ for (int i = 3; i < a; i += 2) {
+ if (!strcmp(v[i], "--generation") && !has_want) { has_want = 1; want = gen_arg(v[i + 1]); }
+ else if (!strcmp(v[i], "--key") && !want_key && *v[i + 1]) want_key = v[i + 1];
+ else usage();
+ }
+ return cmd_check(v[0], v[1], v[2], has_want, want, want_key);
+ }
if (!strcmp(c, "list") || !strcmp(c, "validate")) {
int val = !strcmp(c, "validate"); Tot t = {0, 0, 0};
char *r = absdir(a ? v[0] : ".");
diff --git a/tools/crumb/test-namespace.sh b/tools/crumb/test-namespace.sh
new file mode 100644
index 0000000..c52ddb9
--- /dev/null
+++ b/tools/crumb/test-namespace.sh
@@ -0,0 +1,577 @@
+#!/bin/sh
+# Repository namespaces (layout 2), crumb check, lease generations (fencing) and enforcement mode (crumb924).
+# usage: sh test-namespace.sh ./crumb. Scratch directories only; no network (origin URLs are set, never fetched).
+# Clock: CRUMB_TEST_NOW (test-only, epoch seconds) pins "now" for the expiry boundary.
+C=${1:-./crumb}; C=$(cd "$(dirname "$C")" && pwd)/$(basename "$C")
+T=$(mktemp -d); trap 'chmod -R u+rwx "$T" 2>/dev/null; rm -rf "$T"' EXIT
+export GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_SYSTEM=/dev/null
+unset CRUMB_COORD_ROOT CRUMB_EXPECT_STORE_ID CRUMB_STRICT_STORE_ID CRUMB_ENFORCE CRUMB_REPO_ID CRUMB_SESSION CRUMB_TEST_NOW CC_STORE
+fail=0; ok() { echo "PASS $1"; }; bad() { echo "FAIL $1"; fail=1; }
+TO=""; command -v timeout >/dev/null 2>&1 && TO="timeout 20"
+r() { # r <dir> <command...>: RC, OUT (stdout), ERR (stderr); a hung command is killed after 20 s (rc 124)
+ d=$1; shift
+ OUT=$(cd "$d" && $TO "$@" 2>"$T/err" </dev/null); RC=$?; ERR=$(cat "$T/err")
+}
+why() { echo " (rc=$RC) out: $(printf '%s' "$OUT" | head -2 | cut -c1-200) err: $(printf '%s' "$ERR" | head -2 | cut -c1-200)"; }
+has() { printf '%s\n' "$OUT" | grep -Eq "$1"; }
+herr() { printf '%s\n' "$ERR" | grep -Eq "$1"; }
+mkrepo() { # mkrepo <path> <origin-url or ->
+ mkdir -p "$1/src/deep" && (cd "$1" && git init -q -b main . && echo a > src/a.c && echo b > src/b.c && echo d > src/deep/d.c &&
+ git add -A && git -c user.name=t -c user.email=t@t commit -qm init && { [ "$2" = - ] || git remote add origin "$2"; }) >/dev/null 2>&1
+}
+enroll() { # enroll <repo> <root>: shared root, layout 2 (store-init once per root), registered store id, enforcement on
+ git -C "$1" config crumb.coordinationRoot "$2"
+ [ -f "$2/LAYOUT" ] || (cd "$1" && "$C" store-init . >/dev/null 2>&1)
+ git -C "$1" config crumb.storeId "$(cd "$1" && "$C" store-id . 2>/dev/null)"
+ git -C "$1" config crumb.enforce true
+}
+sum() { find "$1" -type f -exec cksum {} + 2>/dev/null | sort; }
+NOW=1800000000 # 2027-01-15T08:00:00Z
+
+echo "crumb under test: $C"
+# ---- N1 store-init / layout 2 ----
+ROOT="$T/shared"; mkdir -p "$ROOT"
+mkrepo "$T/one" https://github.com/Acme/One.git; mkrepo "$T/two" git@github.com:acme/two.git
+git -C "$T/one" config crumb.coordinationRoot "$ROOT"
+r "$T/one" "$C" store-init .
+[ $RC -eq 0 ] && has '^STORE_INIT .* layout crumb-coord-layout/2 store [0-9a-f]{32}$' && [ "$(cat "$ROOT/LAYOUT" 2>/dev/null)" = crumb-coord-layout/2 ] && [ -d "$ROOT/repos" ] && ok "N1 store-init writes LAYOUT crumb-coord-layout/2 and repos/ under the shared root" || { why; bad "N1 store-init"; }
+has '^repository acme/one \(from origin remote URL\)' && ok "N1 repo id derived from the origin URL as lowercase owner/repo" || { why; bad "N1 repo id from origin"; }
+l0=$(cksum < "$ROOT/LAYOUT" 2>/dev/null); id0=$(cat "$ROOT/STORE_ID" 2>/dev/null)
+r "$T/one" "$C" store-init .
+[ $RC -eq 0 ] && has 'already layout 2' && [ "$(cksum < "$ROOT/LAYOUT")" = "$l0" ] && [ "$(cat "$ROOT/STORE_ID")" = "$id0" ] && ok "N1 store-init is idempotent (LAYOUT and STORE_ID unchanged)" || { why; bad "N1 store-init idempotent"; }
+enroll "$T/one" "$ROOT"; enroll "$T/two" "$ROOT"
+
+# ---- N2 cross-repository: two repositories, same relative path, one shared root ----
+r "$T/one" "$C" claim alice . src/a.c "one's a.c" 600
+[ $RC -eq 0 ] && has '^CLAIMED src/a.c .* generation 1$' && ok "N2 alice claims src/a.c in repo one (generation 1)" || { why; bad "N2 claim one"; }
+r "$T/two" "$C" claim bob . src/a.c "two's a.c" 600
+[ $RC -eq 0 ] && has '^CLAIMED src/a.c .* generation 1$' && ok "N2 bob claims src/a.c in repo two: no collision across repositories" || { why; bad "N2 cross-repo collision"; }
+r "$T/two" "$C" check alice . src/a.c
+[ $RC -eq 2 ] && has '^REFUSED held-by bob src/a.c key src/a.c ' && ok "N2 check in repo two sees only repo two's holder" || { why; bad "N2 check two"; }
+r "$T/one" "$C" check alice . src/a.c
+[ $RC -eq 0 ] && ok "N2 check in repo one: alice holds it" || { why; bad "N2 check one"; }
+[ -f "$ROOT/repos/acme/one/dirs/src.json" ] && [ -f "$ROOT/repos/acme/two/dirs/src.json" ] && [ ! -e "$ROOT/dirs" ] && ok "N2 records live in repos/<owner>/<repo>/ namespaces, nothing flat at the root" || bad "N2 namespace layout"
+
+# ---- N3 two independent clones of one repository sharing the root (origin URL spellings differ) ----
+mkrepo "$T/origin-src" -; git clone -q --bare "$T/origin-src" "$T/origin.git" 2>/dev/null
+git clone -q "$T/origin.git" "$T/c1" 2>/dev/null; git clone -q "$T/origin.git" "$T/c2" 2>/dev/null
+git -C "$T/c1" remote set-url origin https://github.com/Acme/Widget.git; git -C "$T/c2" remote set-url origin git@github.com:acme/widget.git
+enroll "$T/c1" "$ROOT"; enroll "$T/c2" "$ROOT"
+i=1; while [ $i -le 8 ]; do d="$T/c$(( (i % 2) + 1 ))"; ( cd "$d" && "$C" claim "racer$i" . src/a.c race 600 >/dev/null 2>&1; echo $? > "$T/rc.$i" ) & i=$((i + 1)); done; wait
+w=$(cat "$T"/rc.[1-8] | grep -c '^0$'); b=$(cat "$T"/rc.[1-8] | grep -c '^2$')
+[ "$w" -eq 1 ] && [ "$b" -eq 7 ] && ok "N3 8 concurrent claims from two independent clones: exactly 1 exit 0, 7 exit 2" || bad "N3 clone race (wins=$w blocked=$b)"
+win=$(for i in 1 2 3 4 5 6 7 8; do [ "$(cat "$T/rc.$i")" = 0 ] && echo "racer$i"; done | head -1)
+r "$T/c2" "$C" check "${win:-none}" . src/a.c; a=$RC; r "$T/c1" "$C" check "${win:-none}" . src/a.c
+[ $a -eq 0 ] && [ $RC -eq 0 ] && ok "N3 both clones agree on the single holder ($win)" || { why; bad "N3 clones disagree"; }
+[ -d "$ROOT/repos/acme/widget" ] && [ "$(ls "$ROOT/repos/acme")" = "one
+two
+widget" ] && ok "N3 https://github.com/Acme/Widget.git and git@github.com:acme/widget.git are one namespace" || bad "N3 URL normalisation ($(ls "$ROOT/repos/acme" | tr '\n' ' '))"
+
+# ---- N4 linked worktrees of one repository on the shared root ----
+git -C "$T/one" worktree add -q -b wt "$T/one-wt" 2>/dev/null
+r "$T/one-wt" "$C" claim carol . src/a.c "from the worktree"
+[ $RC -eq 2 ] && has '^BLOCKED src/a.c held by alice' && ok "N4 linked worktree sees alice's lease (BLOCKED, exit 2)" || { why; bad "N4 worktree block"; }
+r "$T/one-wt" "$C" check alice . src/a.c
+[ $RC -eq 0 ] && has '^HELD src/a.c by alice key src/a.c generation 1 expires [0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$' && ok "N4 check from the linked worktree: HELD line shape" || { why; bad "N4 worktree check"; }
+r "$T/one-wt" "$C" claim carol . src/b.c "other file"
+[ $RC -eq 0 ] && ok "N4 a different file is free from the worktree" || { why; bad "N4 worktree other file"; }
+
+# ---- N5 overlap: ancestor and descendant leases of another agent block a claim ----
+r "$T/one" "$C" claim dave . src "whole src"
+[ $RC -eq 2 ] && has '^BLOCKED src held by (alice|carol) .*\[overlapping lease on src/[ab].c\]' && ok "N5 claim of src refused: another agent holds a descendant (exit 2, BLOCKED shape)" || { why; bad "N5 descendant overlap"; }
+r "$T/one" "$C" claim dave . . "whole repo"
+[ $RC -eq 2 ] && has '^BLOCKED \. held by' && ok "N5 claim of . (whole repository) refused while any lease exists" || { why; bad "N5 root overlap"; }
+r "$T/one" "$C" claim dave . src/deep "deep"
+[ $RC -eq 0 ] && ok "N5 an unrelated subtree is free" || { why; bad "N5 unrelated subtree"; }
+r "$T/one" "$C" claim erin . src/deep/d.c "under dave"
+[ $RC -eq 2 ] && has 'overlapping lease on src/deep\]' && ok "N5 claim under another agent's directory lease refused (ancestor overlap)" || { why; bad "N5 ancestor overlap"; }
+r "$T/one" "$C" check dave . src/deep/d.c
+[ $RC -eq 0 ] && has '^HELD src/deep/d.c by dave key src/deep generation 1 ' && ok "N5 check covers a file through an ancestor directory lease" || { why; bad "N5 ancestor coverage"; }
+r "$T/one" "$C" claim dave . src/deep/d.c "nested, same agent"
+[ $RC -eq 0 ] && ok "N5 the same agent may nest a lease inside its own" || { why; bad "N5 same-agent nesting"; }
+r "$T/one" "$C" check erin . src/deep/d.c
+[ $RC -eq 2 ] && has '^REFUSED held-by dave src/deep/d.c key src/deep/d.c ' && ok "N5 check reports the nearest other holder" || { why; bad "N5 other holder"; }
+
+# ---- N6 lease generation: increments on each new acquisition, kept on renewal, fenced by check --generation ----
+G="$T/gen"; mkrepo "$G" https://github.com/acme/gen.git; enroll "$G" "$ROOT"
+gen() { printf '%s\n' "$OUT" | sed -n 's/.* generation \([0-9][0-9]*\)$/\1/p'; }
+r "$G" env CRUMB_TEST_NOW=$NOW "$C" claim alice . src/a.c g 100; g1=$(gen)
+r "$G" env CRUMB_TEST_NOW=$((NOW + 10)) "$C" claim alice . src/a.c renew 100; g2=$(gen)
+[ "$g1" = 1 ] && [ "$g2" = 1 ] && ok "N6 first acquisition is generation 1; renewal by the valid holder keeps it" || bad "N6 renewal ($g1 $g2)"
+r "$G" env CRUMB_TEST_NOW=$((NOW + 20)) "$C" close alice . src/a.c; r "$G" env CRUMB_TEST_NOW=$((NOW + 21)) "$C" claim bob . src/a.c after-release 100; g3=$(gen)
+[ "$g3" = 2 ] && ok "N6 takeover after release: generation 2" || { why; bad "N6 after release ($g3)"; }
+r "$G" env CRUMB_TEST_NOW=$((NOW + 21 + 101)) "$C" claim alice . src/a.c after-expiry 100; g4=$(gen)
+[ "$g4" = 3 ] && ok "N6 re-acquire after expiry: generation 3" || { why; bad "N6 after expiry ($g4)"; }
+r "$G" env CRUMB_TEST_NOW=$((NOW + 130)) "$C" check alice . src/a.c --generation 3
+[ $RC -eq 0 ] && has 'generation 3 ' && ok "N6 check --generation 3 matches (exit 0)" || { why; bad "N6 generation match"; }
+r "$G" env CRUMB_TEST_NOW=$((NOW + 130)) "$C" check alice . src/a.c --generation 2
+[ $RC -eq 2 ] && has '^REFUSED generation 3!=2 src/a.c key src/a.c' && ok "N6 check --generation 2 against generation 3: REFUSED generation 3!=2 (exit 2)" || { why; bad "N6 generation mismatch"; }
+r "$G" "$C" check alice . src/a.c --generation x
+[ $RC -eq 1 ] && herr "bad generation: x" && ok "N6 non-numeric --generation is a usage error (exit 1)" || { why; bad "N6 bad generation arg"; }
+r "$G" "$C" check alice . src/a.c --gen 3
+[ $RC -eq 1 ] && ok "N6 unknown check option is a usage error (exit 1)" || { why; bad "N6 bad option"; }
+
+# ---- N7 expiry boundary (CRUMB_TEST_NOW): now - acquired_at == ttl still valid, ttl + 1 expired ----
+E="$T/exp"; mkrepo "$E" https://github.com/acme/exp.git; enroll "$E" "$ROOT"
+r "$E" env CRUMB_TEST_NOW=$NOW "$C" claim alice . src/a.c boundary 100
+r "$E" env CRUMB_TEST_NOW=$((NOW + 100)) "$C" check alice . src/a.c
+[ $RC -eq 0 ] && has 'expires 2027-01-15T08:01:40Z$' && ok "N7 check at acquired+ttl: still HELD (exit 0), expires = acquired+ttl" || { why; bad "N7 boundary valid"; }
+r "$E" env CRUMB_TEST_NOW=$((NOW + 101)) "$C" check alice . src/a.c
+[ $RC -eq 2 ] && has '^REFUSED expired src/a.c key src/a.c holder alice generation 1 expired 2027-01-15T08:01:40Z$' && ok "N7 check at acquired+ttl+1: REFUSED expired (exit 2)" || { why; bad "N7 boundary expired"; }
+r "$E" env CRUMB_TEST_NOW=$((NOW + 100)) "$C" claim bob . src/a.c early 100
+[ $RC -eq 2 ] && ok "N7 claim by another agent at acquired+ttl: BLOCKED" || { why; bad "N7 claim at boundary"; }
+s0=$(sum "$ROOT/repos/acme/exp")
+r "$E" env CRUMB_TEST_NOW=$((NOW + 101)) "$C" check bob . src/a.c
+[ "$(sum "$ROOT/repos/acme/exp")" = "$s0" ] && grep -q '"holder": "alice"' "$ROOT/repos/acme/exp/dirs/src.json" && ok "N7 check never prunes the expired lease (store byte-identical)" || bad "N7 check pruned"
+r "$E" env CRUMB_TEST_NOW=$((NOW + 101)) "$C" claim bob . src/a.c late 100
+[ $RC -eq 0 ] && has 'generation 2$' && ok "N7 claim at acquired+ttl+1 succeeds with generation 2" || { why; bad "N7 claim after boundary"; }
+
+# ---- N8 check: absent / other holder / expired / read-only on a store that does not exist ----
+F="$T/fresh"; mkrepo "$F" -
+r "$F" "$C" check alice . src/a.c
+[ $RC -eq 2 ] && has '^REFUSED absent src/a.c' && [ ! -e "$F/.git/crumb" ] && ok "N8 check on a never-used store: REFUSED absent (exit 2), creates nothing" || { why; bad "N8 absent/read-only"; }
+r "$F" "$C" claim alice . src/a.c x 600; r "$F" "$C" check bob . src/a.c
+[ $RC -eq 2 ] && has '^REFUSED held-by alice ' && ok "N8 layout-1 store: check by another agent REFUSED held-by (exit 2)" || { why; bad "N8 v1 other holder"; }
+r "$F" "$C" check alice . src
+[ $RC -eq 2 ] && has '^REFUSED absent src ' && ok "N8 a lease on a file does not cover its directory" || { why; bad "N8 no upward coverage"; }
+r "$F" "$C" check alice . "$T/elsewhere"
+[ $RC -eq 1 ] && herr "outside the repository" && ok "N8 target outside the repository: exit 1" || { why; bad "N8 outside target"; }
+r "$T" "$C" check alice "$T" x
+[ $RC -eq 1 ] && herr "check needs a git repository" && ok "N8 check outside any git repository: exit 1 (no .crumb.local fallback)" || { why; bad "N8 check outside git"; }
+
+# ---- N9 enforcement: agent identity verbatim, no aliases, one live session per id ----
+A="$T/ag"; mkrepo "$A" https://github.com/acme/ag.git; enroll "$A" "$ROOT"
+n=0; for id in "bad agent" "a/b" "_lead" ".hidden" "a:b" "$(printf 'x%.0s' $(seq 1 161))"; do
+ r "$A" "$C" claim "$id" . src/a.c x 600; [ $RC -eq 1 ] && herr 'AGENT_ID_INVALID' && n=$((n + 1)); done
+[ $n -eq 6 ] && ok "N9 enforcement refuses agent ids that would be rewritten (space, /, leading _ or ., :, 161 chars): exit 1" || bad "N9 invalid ids ($n of 6 refused)"
+r "$A" "$C" claim "$(printf 'x%.0s' $(seq 1 160))" . src/deep/d.c x 600
+[ $RC -eq 0 ] && ok "N9 a 160-character id is accepted" || { why; bad "N9 160 chars"; }
+r "$A" "$C" claim a@b . src/a.c x 600; r1=$RC; r "$A" "$C" claim a_b . src/b.c y 600; r2=$RC
+[ $r1 -eq 0 ] && [ $r2 -eq 0 ] && [ -f "$ROOT/repos/acme/ag/agents/a@b.json" ] && [ -f "$ROOT/repos/acme/ag/agents/a_b.json" ] && ok "N9 a@b and a_b are two identities with two records (no sanitising alias)" || bad "N9 alias records"
+r "$A" "$C" check a_b . src/a.c
+[ $RC -eq 2 ] && has 'REFUSED held-by a@b' && ok "N9 a_b does not inherit a@b's lease" || { why; bad "N9 alias lease"; }
+r "$A" env CRUMB_SESSION=sess-1 "$C" claim w.dup . src/deep/x.c x 600; r1=$RC
+r "$A" env CRUMB_SESSION=sess-2 "$C" claim w.dup . src/deep/y.c y 600
+[ $r1 -eq 0 ] && [ $RC -eq 2 ] && has '^BLOCKED agent w.dup is live in session sess-1, not this session sess-2' && ok "N9 duplicate agent identity: a second session presenting the same id is refused (exit 2)" || { why; bad "N9 duplicate session"; }
+r "$A" env CRUMB_SESSION=sess-1 "$C" claim w.dup . src/deep/y.c y 600
+[ $RC -eq 0 ] && ok "N9 the owning session keeps working" || { why; bad "N9 owning session"; }
+r "$A" "$C" claim alice2 . src/c.c x 0
+[ $RC -eq 1 ] && ok "N9 enforcement refuses ttl 0 (ttl_seconds must be positive)" || { why; bad "N9 ttl 0"; }
+
+# ---- N10 enforcement: malformed lease schema is exit 1, never pruned, never taken over ----
+M="$T/mal"; mkrepo "$M" https://github.com/acme/mal.git; enroll "$M" "$ROOT"
+r "$M" "$C" claim alice . src/a.c x 600; REC="$ROOT/repos/acme/mal/dirs/src.json"; cp "$REC" "$T/pristine.json"
+n=0; tot=0
+for f in '.ttl_seconds="600"' '.ttl_seconds=0' '.ttl_seconds=-5' '.acquired_at="yesterday"' '.acquired_at="2026-13-01T00:00:00Z"' '.holder=5' 'del(.holder)' 'del(.generation)' '.generation=-1' '.generation=1.5' '.generation=0'; do
+ tot=$((tot + 1)); jq ".locks[\"src/a.c\"] |= ($f)" "$T/pristine.json" > "$REC"; s0=$(cksum < "$REC")
+ r "$M" "$C" check alice . src/a.c; c1=$RC; e1=$ERR; r "$M" "$C" claim bob . src/a.c takeover 600; c2=$RC
+ if [ $c1 -eq 1 ] && [ $c2 -eq 1 ] && printf '%s' "$e1" | grep -q MALFORMED_LEASE && [ "$(cksum < "$REC")" = "$s0" ]; then n=$((n + 1)); else echo " malformed $f: check=$c1 claim=$c2 $e1"; fi
+done
+[ $n -eq $tot ] && ok "N10 $tot malformed lease variants: check and claim exit 1 (MALFORMED_LEASE), record untouched, no takeover" || bad "N10 malformed schema ($n of $tot)"
+jq '.locks["src/a.c"].acquired_at="2000-01-01T00:00:00Z" | .locks["src/a.c"].holder=7' "$T/pristine.json" > "$REC"; s0=$(cksum < "$REC")
+r "$M" "$C" claim bob . src/b.c other 600
+[ $RC -eq 1 ] && [ "$(cksum < "$REC")" = "$s0" ] && ok "N10 an expired but malformed lease is not swept by an unrelated claim (exit 1)" || { why; bad "N10 malformed swept"; }
+jq '.locks="nope"' "$T/pristine.json" > "$REC"
+r "$M" "$C" check alice . src/a.c
+[ $RC -eq 1 ] && herr MALFORMED_RECORD && ok "N10 locks of the wrong type: exit 1" || { why; bad "N10 locks type"; }
+cp "$T/pristine.json" "$REC"; mkdir -p "$F/.git/crumb/v1/dirs"
+printf '{"locks": {"src/a.c": {"acquired_at": "%s", "ttl_seconds": 600}}}\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$F/.git/crumb/v1/dirs/src.json"
+r "$F" "$C" check alice . src/a.c
+[ $RC -eq 1 ] && herr MALFORMED_LEASE && ok "N10 outside enforcement too, check refuses a lease without a holder (exit 1)" || { why; bad "N10 lenient holderless"; }
+
+# ---- N11 enforcement: an inaccessible store directory is exit 1, never empty state ----
+if [ "$(id -u)" -eq 0 ]; then echo "NOT_RUN N11 inaccessible directory (running as root: chmod 000 does not deny)"; else
+ P="$T/perm"; mkrepo "$P" https://github.com/acme/perm.git; enroll "$P" "$ROOT"; NS="$ROOT/repos/acme/perm"
+ r "$P" "$C" claim alice . src/deep/d.c x 600; chmod 000 "$NS/dirs/src"
+ r "$P" "$C" claim bob . src/b.c y 600
+ [ $RC -eq 1 ] && herr 'STORE_UNREADABLE: cannot open directory .*/dirs/src' && ok "N11 chmod 000 dirs/src: enforcement-mode claim exits 1 (STORE_UNREADABLE), not empty" || { why; bad "N11 claim unreadable"; }
+ r "$P" "$C" check alice . src/deep/d.c
+ [ $RC -eq 1 ] && herr "Permission denied" && ok "N11 check through the unreadable directory: exit 1" || { why; bad "N11 check unreadable"; }
+ r "$P" env CRUMB_REPO_ID=acme/perm "$C" sniff alice .
+ [ $RC -eq 1 ] && ok "N11 sniff in enforcement mode: exit 1" || { why; bad "N11 sniff unreadable"; }
+ git -C "$P" config crumb.enforce false
+ r "$P" "$C" sniff alice .
+ [ $RC -eq 0 ] && herr 'warning: cannot open directory .*/dirs/src' && ok "N11 outside enforcement: the same failure is a stderr warning, never silent" || { why; bad "N11 normal-mode warning"; }
+ chmod 755 "$NS/dirs/src"; git -C "$P" config crumb.enforce true
+fi
+
+# ---- N12 store identity and hostile files: exit 3 / exit 4 for check ----
+r "$T/one" env CRUMB_EXPECT_STORE_ID=0123456789abcdef0123456789abcdef "$C" check alice . src/a.c
+[ $RC -eq 3 ] && herr STORE_ID_MISMATCH && ok "N12 STORE_ID mismatch: check exit 3" || { why; bad "N12 mismatch check"; }
+r "$T/one" env CRUMB_EXPECT_STORE_ID=0123456789abcdef0123456789abcdef "$C" claim zed . src/z.c x
+[ $RC -eq 3 ] && ok "N12 STORE_ID mismatch: claim exit 3" || { why; bad "N12 mismatch claim"; }
+H="$T/host"; mkrepo "$H" https://github.com/acme/host.git; enroll "$H" "$ROOT"
+r "$H" "$C" claim alice . src/a.c x 600; rm -f "$ROOT/repos/acme/host/dirs/src.json"; mkfifo "$ROOT/repos/acme/host/dirs/src.json"
+r "$H" "$C" check alice . src/a.c
+[ $RC -eq 4 ] && herr 'REFUSED_RECORD: .*src.json is a fifo' && ok "N12 FIFO planted as a record: check exit 4, no hang" || { why; bad "N12 fifo check"; }
+rm -f "$ROOT/repos/acme/host/dirs/src.json"
+U="$T/unreg-root"; mkrepo "$T/u" https://github.com/acme/u.git; git -C "$T/u" config crumb.coordinationRoot "$U"; (cd "$T/u" && "$C" store-init . >/dev/null 2>&1)
+r "$T/u" env CRUMB_ENFORCE=1 "$C" check alice . src/a.c
+[ $RC -eq 3 ] && herr STORE_UNREGISTERED && ok "N12 enforcement refuses an unregistered store (exit 3)" || { why; bad "N12 unregistered"; }
+printf 'crumb-coord-layout/9\n' > "$T/bad-layout"; mkdir -p "$T/bl"; cp "$T/bad-layout" "$T/bl/LAYOUT"
+r "$T/u" env CRUMB_COORD_ROOT="$T/bl" "$C" check alice . src/a.c
+[ $RC -eq 3 ] && herr STORE_LAYOUT_UNSUPPORTED && ok "N12 unknown LAYOUT content: exit 3, never rewritten" || { why; bad "N12 bad layout"; }
+mkdir -p "$ROOT/dirs"; echo '{}' > "$ROOT/dirs/stray.json"
+r "$T/one" "$C" check alice . src/a.c
+[ $RC -eq 3 ] && herr STORE_LAYOUT_MIXED && ok "N12 flat records written into a layout-2 root by an older tool: enforcement exit 3" || { why; bad "N12 mixed"; }
+rm -rf "$ROOT/dirs"
+
+# ---- N13 legacy .crumb.local fallback refused in enforcement mode ----
+mkdir -p "$T/plain"
+r "$T/plain" env CRUMB_ENFORCE=1 "$C" claim alice "$T/plain" x.c x
+[ $RC -eq 1 ] && herr ENFORCE_NO_REPOSITORY && [ ! -e "$T/plain/.crumb.local" ] && ok "N13 CRUMB_ENFORCE=1 outside git: exit 1, no .crumb.local written" || { why; bad "N13 env fallback"; }
+r "$T/plain" "$C" --enforce sniff alice "$T/plain"
+[ $RC -eq 1 ] && [ ! -e "$T/plain/.crumb.local" ] && ok "N13 --enforce outside git: exit 1" || { why; bad "N13 flag fallback"; }
+r "$T/plain" "$C" claim alice "$T/plain" x.c x
+[ $RC -eq 0 ] && [ -f "$T/plain/.crumb.local" ] && ok "N13 control: without enforcement the RFC-0001 fallback still works" || { why; bad "N13 control"; }
+
+# ---- N14 layout 1 is never reinterpreted ----
+V="$T/v1"; mkrepo "$V" https://github.com/acme/v1.git
+r "$V" "$C" claim alice . src/a.c "flat lease" 600
+r "$V" "$C" store-init .
+[ $RC -eq 1 ] && herr STORE_LAYOUT_V1_DATA && [ ! -e "$V/.git/crumb/v1/LAYOUT" ] && ok "N14 store-init refuses a root with layout-1 records (exit 1), no LAYOUT written" || { why; bad "N14 store-init on v1"; }
+r "$V" "$C" claim bob . src/a.c x
+[ $RC -eq 2 ] && ok "N14 the layout-1 lease still blocks after the refused init" || { why; bad "N14 v1 lease lost"; }
+VID=$(cd "$V" && "$C" store-id . 2>/dev/null)
+r "$V" env CRUMB_ENFORCE=1 CRUMB_EXPECT_STORE_ID="$VID" "$C" check alice . src/a.c
+[ $RC -eq 3 ] && herr STORE_LAYOUT_V1 && ok "N14 enforcement refuses a layout-1 store (exit 3)" || { why; bad "N14 enforce on v1"; }
+r "$V" env CRUMB_ENFORCE=1 CRUMB_EXPECT_STORE_ID="$VID" "$C" claim alice . src/b.c x
+[ $RC -eq 3 ] && ok "N14 enforcement: claim on layout 1 exit 3" || { why; bad "N14 enforce claim v1"; }
+
+# ---- N15 repository id rules ----
+r "$T/u" env CRUMB_REPO_ID=a/b/c "$C" claim alice . src/a.c x
+[ $RC -eq 3 ] && herr REPO_ID_INVALID && ok "N15 CRUMB_REPO_ID with three components refused (exit 3)" || { why; bad "N15 three components"; }
+r "$T/u" env CRUMB_REPO_ID=acme/dirs "$C" claim alice . src/a.c x
+[ $RC -eq 3 ] && herr REPO_ID_INVALID && ok "N15 a record directory name as second component refused (no nested namespaces)" || { why; bad "N15 reserved component"; }
+mkrepo "$T/noorigin" -; git -C "$T/noorigin" config crumb.coordinationRoot "$U"
+r "$T/noorigin" "$C" claim alice . src/a.c x
+[ $RC -eq 3 ] && herr REPO_ID_MISSING && [ ! -e "$U/repos/noorigin" ] && ok "N15 layout 2 without origin or crumb.repoId: REPO_ID_MISSING (exit 3), nothing derived from the path" || { why; bad "N15 missing repo id"; }
+git -C "$T/noorigin" remote add origin "$T/origin.git"
+r "$T/noorigin" "$C" claim alice . src/a.c x
+[ $RC -eq 3 ] && herr REPO_ID_MISSING && ok "N15 a local-path origin is never used as an identity" || { why; bad "N15 path origin"; }
+git -C "$T/noorigin" config crumb.repoId acme/explicit
+r "$T/noorigin" "$C" claim alice . src/a.c x
+[ $RC -eq 0 ] && [ -d "$U/repos/acme/explicit/dirs" ] && ok "N15 git config crumb.repoId names the namespace" || { why; bad "N15 config repo id"; }
+r "$T/noorigin" env CRUMB_REPO_ID=acme/envwins "$C" claim alice . src/a.c x
+[ $RC -eq 0 ] && [ -d "$U/repos/acme/envwins/dirs" ] && ok "N15 CRUMB_REPO_ID overrides git config crumb.repoId" || { why; bad "N15 env precedence"; }
+
+# ---- N16 a relative override root is anchored at the worktree top-level, not the cwd ----
+RL="$T/rel"; mkrepo "$RL" https://github.com/acme/rel.git
+(cd "$RL" && CRUMB_COORD_ROOT=../relroot "$C" store-init . >/dev/null 2>&1)
+r "$RL/src/deep" env CRUMB_COORD_ROOT=../relroot "$C" claim alice "$RL/src/deep" d.c "from a subdirectory" 600
+r2=$RC; r "$RL" env CRUMB_COORD_ROOT=../relroot "$C" check alice . src/deep/d.c
+[ $r2 -eq 0 ] && [ $RC -eq 0 ] && [ -f "$T/relroot/LAYOUT" ] && [ ! -e "$RL/src/relroot" ] && [ ! -e "$RL/relroot" ] && ok "N16 CRUMB_COORD_ROOT=../relroot means one store whatever the cwd" || { why; bad "N16 relative root"; }
+
+# ---- N17 concurrent claims in enforcement mode: same key, and nested keys ----
+i=1; while [ $i -le 8 ]; do ( cd "$T/one" && CRUMB_REPO_ID=acme/race1 "$C" claim "r$i" . src/b.c race 600 >/dev/null 2>&1; echo $? > "$T/rr.$i" ) & i=$((i + 1)); done; wait
+w=$(cat "$T"/rr.[1-8] | grep -c '^0$'); b=$(cat "$T"/rr.[1-8] | grep -c '^2$')
+[ "$w" -eq 1 ] && [ "$b" -eq 7 ] && ok "N17 8 concurrent claims of one key: exactly 1 exit 0, 7 exit 2" || bad "N17 race (wins=$w blocked=$b)"
+i=1; while [ $i -le 8 ]; do k=src; [ $((i % 2)) -eq 0 ] && k=src/a.c; ( cd "$T/one" && CRUMB_REPO_ID=acme/race2 "$C" claim "n$i" . "$k" race 600 >/dev/null 2>&1; echo $? > "$T/rn.$i" ) & i=$((i + 1)); done; wait
+w=$(cat "$T"/rn.[1-8] | grep -c '^0$'); b=$(cat "$T"/rn.[1-8] | grep -c '^2$')
+[ "$w" -eq 1 ] && [ "$b" -eq 7 ] && ok "N17 8 concurrent claims of src and src/a.c (overlapping keys): exactly 1 exit 0" || bad "N17 nested race (wins=$w blocked=$b)"
+
+# ---- N18 key-qualified fencing token (trace found by the Lean model, evidence/proof-lean obs_number_only_check_accepts) ----
+# Generations count per key, so a bare number can match a different covering lease: alice holds src/a.c at
+# generation 1, it expires, bob takes it (2), that expires, alice claims the ancestor src (its own generation 1).
+# check alice src/a.c --generation 1 is then HELD through src; --key src/a.c --generation 1 must be REFUSED.
+K="$T/keytok"; mkrepo "$K" https://github.com/acme/keytok.git; enroll "$K" "$ROOT"
+r "$K" env CRUMB_TEST_NOW=$NOW "$C" claim alice . src/a.c first 100
+r "$K" env CRUMB_TEST_NOW=$((NOW + 101)) "$C" claim bob . src/a.c second 100; gb=$(gen)
+r "$K" env CRUMB_TEST_NOW=$((NOW + 202)) "$C" claim alice . src third 100; ga=$(gen)
+[ "$gb" = 2 ] && [ "$ga" = 1 ] && ok "N18 trace: bob re-acquires src/a.c (generation 2), alice then claims src (generation 1)" || { why; bad "N18 trace ($gb $ga)"; }
+r "$K" env CRUMB_TEST_NOW=$((NOW + 210)) "$C" check alice . src/a.c --generation 1
+[ $RC -eq 0 ] && has '^HELD src/a.c by alice key src generation 1 ' && ok "N18 a bare --generation 1 is satisfied by the ancestor lease (why a token must name its key)" || { why; bad "N18 bare number"; }
+r "$K" env CRUMB_TEST_NOW=$((NOW + 210)) "$C" check alice . src/a.c --key src/a.c --generation 1
+[ $RC -eq 2 ] && has '^REFUSED key src!=src/a.c src/a.c generation 1 by alice ' && ok "N18 --key src/a.c --generation 1 (the stale token): REFUSED key (exit 2)" || { why; bad "N18 keyed stale token"; }
+r "$K" env CRUMB_TEST_NOW=$((NOW + 210)) "$C" check alice . src/a.c --generation 1 --key src
+[ $RC -eq 0 ] && ok "N18 the current token (--key src --generation 1, either order) is HELD (exit 0)" || { why; bad "N18 keyed current token"; }
+r "$K" "$C" check alice . src/a.c --key src --key src
+[ $RC -eq 1 ] && ok "N18 a repeated --key is a usage error (exit 1)" || { why; bad "N18 repeated key"; }
+
+# ---- N19 a Hermes-style session identity (<agent-name>.<YYYYMMDD_HHMMSS_hex>, with `_`) is a valid verbatim id ----
+HI="worker.20261106_173039_c44e6c"
+r "$K" env CRUMB_TEST_NOW=$((NOW + 220)) CRUMB_SESSION="$HI" "$C" claim "$HI" . docs/h.md hermes 100
+r2=$RC; r "$K" env CRUMB_TEST_NOW=$((NOW + 221)) "$C" check "$HI" . docs/h.md
+[ $r2 -eq 0 ] && [ $RC -eq 0 ] && has "^HELD docs/h.md by $HI key docs/h.md generation 1 " && ok "N19 Hermes session identity with '_' claims and checks verbatim in enforcement mode" || { why; bad "N19 underscore identity"; }
+
+# ---- N20 (review B1) a symlinked directory inside the record tree: refused in enforcement mode, never skipped, never followed ----
+SL="$T/symdesc"; mkrepo "$SL" https://github.com/acme/symdesc.git; enroll "$SL" "$ROOT"; NS="$ROOT/repos/acme/symdesc"
+r "$SL" "$C" claim alice . src/deep/a.c deep 600
+mv "$NS/dirs/src" "$T/hidden-src"; ln -s "$T/hidden-src" "$NS/dirs/src"; h0=$(sum "$T/hidden-src"); s0=$(sum "$NS")
+r "$SL" "$C" claim bob . src ancestor 600
+[ $RC -eq 4 ] && herr 'REFUSED_RECORD: .*/dirs/src is a symbolic link' && [ "$(sum "$NS")" = "$s0" ] && ok "N20 ancestor claim over a symlinked descendant record directory: exit 4, not granted, store unchanged" || { why; bad "N20 symlinked descendant record directory skipped"; }
+r "$SL" "$C" claim bob . . whole 600; c1=$RC; r "$SL" "$C" claim bob . other.c unrelated 600; c2=$RC
+[ $c1 -eq 4 ] && [ $c2 -eq 4 ] && [ "$(sum "$NS")" = "$s0" ] && ok "N20 claims of . and of an unrelated key exit 4 too (the record walk never skips)" || bad "N20 other claims over the link ($c1 $c2)"
+r "$SL" "$C" check bob . src
+[ $RC -eq 2 ] && has '^REFUSED absent src ' && ok "N20 check bob src: REFUSED absent (no ancestor lease was granted)" || { why; bad "N20 check after the refused claim"; }
+[ "$(sum "$T/hidden-src")" = "$h0" ] && [ -L "$NS/dirs/src" ] && ok "N20 the link is never followed: link and target left as found" || bad "N20 link followed or changed"
+git -C "$SL" config crumb.enforce false
+r "$SL" "$C" sniff alice .
+[ $RC -eq 0 ] && herr 'warning: .*/dirs/src is a symbolic link; it is not walked' && ok "N20 outside enforcement the unwalked link is a stderr warning, never silent" || { why; bad "N20 normal-mode warning"; }
+git -C "$SL" config crumb.enforce true; rm -f "$NS/dirs/src"; mv "$T/hidden-src" "$NS/dirs/src"
+
+# ---- N21 (review B2) a top-level directory named _root never shares the repository root's record (layout 2) ----
+RT="$T/rootname"; mkrepo "$RT" https://github.com/acme/rootname.git; enroll "$RT" "$ROOT"; NS="$ROOT/repos/acme/rootname"
+r "$RT" env CRUMB_TEST_NOW=$NOW "$C" claim alice . _root/a.c under 600; a1=$RC; ga=$(gen)
+r "$RT" env CRUMB_TEST_NOW=$NOW "$C" claim alice . README.md top 600; a2=$RC; gr=$(gen)
+[ $a1 -eq 0 ] && [ $a2 -eq 0 ] && [ "$ga" = 1 ] && [ "$gr" = 1 ] && grep -q '"_root/a.c"' "$NS/dirs/__root.json" 2>/dev/null && ! grep -q '"_root/a.c"' "$NS/dirs/_root.json" && grep -q '"README.md"' "$NS/dirs/_root.json" && ok "N21 _root/a.c lives in dirs/__root.json, root-level README.md in dirs/_root.json (generation 1 each)" || { why; bad "N21 _root mapping"; }
+r "$RT" env CRUMB_TEST_NOW=$((NOW + 1)) "$C" check alice . _root/a.c; c1=$RC; o1=$OUT
+r "$RT" env CRUMB_TEST_NOW=$((NOW + 1)) "$C" check alice . README.md
+[ $c1 -eq 0 ] && [ $RC -eq 0 ] && printf '%s\n' "$o1" | grep -q '^HELD _root/a.c by alice key _root/a.c generation 1 ' && has '^HELD README.md by alice key README.md generation 1 ' && ok "N21 check: _root/a.c and README.md both HELD" || { why; bad "N21 check"; }
+r "$RT" env CRUMB_TEST_NOW=$((NOW + 2)) "$C" claim alice . _root/a.c renew 600; c1=$RC; g1=$(gen)
+r "$RT" env CRUMB_TEST_NOW=$((NOW + 2)) "$C" claim alice . README.md renew 600; g2=$(gen)
+[ $c1 -eq 0 ] && [ $RC -eq 0 ] && [ "$g1" = 1 ] && [ "$g2" = 1 ] && ok "N21 renewals of _root/a.c and README.md keep generation 1" || { why; bad "N21 renew ($g1 $g2)"; }
+r "$RT" env CRUMB_TEST_NOW=$((NOW + 3)) "$C" claim bob . src/b.c unrelated 600; c1=$RC
+r "$RT" env CRUMB_TEST_NOW=$((NOW + 3)) "$C" claim bob . other.c root-level 600
+[ $c1 -eq 0 ] && [ $RC -eq 0 ] && ok "N21 unrelated claims (src/b.c, root-level other.c) still work" || { why; bad "N21 unrelated claims"; }
+r "$RT" env CRUMB_TEST_NOW=$((NOW + 4)) "$C" claim bob . _root dir 600; c1=$RC; o1=$OUT
+r "$RT" env CRUMB_TEST_NOW=$((NOW + 4)) "$C" check bob . _root/a.c
+[ $c1 -eq 2 ] && printf '%s\n' "$o1" | grep -q 'overlapping lease on _root/a.c\]' && [ $RC -eq 2 ] && has '^REFUSED held-by alice _root/a.c key _root/a.c ' && ok "N21 bob: claim of _root BLOCKED by the descendant, check REFUSED held-by alice" || { why; bad "N21 overlap on _root"; }
+r "$RT" env CRUMB_TEST_NOW=$((NOW + 5)) "$C" close alice . _root/a.c; c1=$RC
+r "$RT" env CRUMB_TEST_NOW=$((NOW + 5)) "$C" close alice . README.md; c2=$RC
+r "$RT" env CRUMB_TEST_NOW=$((NOW + 6)) "$C" claim bob . _root/a.c next 600
+[ $c1 -eq 0 ] && [ $c2 -eq 0 ] && [ $RC -eq 0 ] && has 'generation 2$' && ok "N21 close of both, then bob takes _root/a.c at generation 2" || { why; bad "N21 close and re-acquire ($c1 $c2)"; }
+r "$RT" env CRUMB_TEST_NOW=$((NOW + 7)) "$C" check bob . _root/a.c --key _root/a.c --generation 2
+[ $RC -eq 0 ] && ok "N21 check of the new token (--key _root/a.c --generation 2): HELD" || { why; bad "N21 new token"; }
+echo '{}' > "$NS/dirs/_old.json"; s0=$(sum "$NS")
+r "$RT" "$C" claim carol . src/a.c x 600
+[ $RC -eq 1 ] && herr 'MALFORMED_RECORD: .*dirs/_old.json is not a directory record name of layout 2' && [ "$(sum "$NS")" = "$s0" ] && ok "N21 a '_' record name no key maps to (old layout-2 mapping): enforcement exit 1, store unchanged" || { why; bad "N21 unmapped name"; }
+rm -f "$NS/dirs/_old.json"; mkdir -p "$NS/dirs/_root"; echo '{}' > "$NS/dirs/_root/x.json"
+r "$RT" "$C" claim carol . src/a.c x 600
+[ $RC -eq 1 ] && herr 'dirs/_root/x.json is not a directory record name' && ok "N21 a dirs/_root/ subtree is never a key directory: exit 1" || { why; bad "N21 dirs/_root subtree"; }
+rm -rf "$NS/dirs/_root"
+L1="$T/rootname1"; mkrepo "$L1" -
+r "$L1" "$C" claim alice . _root/a.c v1 600
+[ $RC -eq 0 ] && grep -q '"_root/a.c"' "$L1/.git/crumb/v1/dirs/_root.json" && [ ! -e "$L1/.git/crumb/v1/dirs/__root.json" ] && ok "N21 control: layout 1 keeps its historical mapping (dirs/_root.json) byte for byte" || { why; bad "N21 layout 1 mapping changed"; }
+
+# ---- N22 (review B3) a lease belongs to the session that took it: heartbeat expiry and malformed metadata never hand it over ----
+SE="$T/sess"; mkrepo "$SE" https://github.com/acme/sess.git; enroll "$SE" "$ROOT"; NS="$ROOT/repos/acme/sess"
+r "$SE" env CRUMB_TEST_NOW=$NOW CRUMB_SESSION=first "$C" claim worker . other.c long 600
+r "$SE" env CRUMB_TEST_NOW=$NOW CRUMB_SESSION=first "$C" update worker . heartbeat 1; s0=$(sum "$NS")
+r "$SE" env CRUMB_TEST_NOW=$((NOW + 2)) CRUMB_SESSION=second "$C" claim worker . other.c takeover 600
+[ $RC -eq 2 ] && has '^BLOCKED agent worker is live in session first, not this session second \(live lease on other.c generation 1' && ok "N22 heartbeat expired, lease live: another session of the same id cannot renew it (exit 2)" || { why; bad "N22 session takeover after heartbeat expiry"; }
+r "$SE" env CRUMB_TEST_NOW=$((NOW + 2)) CRUMB_SESSION=second "$C" close worker . other.c; c1=$RC
+r "$SE" env CRUMB_TEST_NOW=$((NOW + 2)) CRUMB_SESSION=second "$C" update worker . mine 600; c2=$RC
+r "$SE" env CRUMB_TEST_NOW=$((NOW + 2)) CRUMB_SESSION=second "$C" claim worker . src/new.c new 600; c3=$RC
+[ $c1 -eq 2 ] && [ $c2 -eq 2 ] && [ $c3 -eq 2 ] && [ "$(sum "$NS")" = "$s0" ] && ok "N22 the other session's close, update and new claim: exit 2 each, store unchanged" || bad "N22 other session ($c1 $c2 $c3)"
+r "$SE" env CRUMB_TEST_NOW=$((NOW + 3)) CRUMB_SESSION=first "$C" claim worker . other.c renew 600
+[ $RC -eq 0 ] && has 'generation 1$' && ok "N22 the owning session renews its lease after its heartbeat expired (generation 1)" || { why; bad "N22 owner renew"; }
+AR="$NS/agents/worker.json"; cp "$AR" "$T/agent-pristine.json"; n=0; tot=0
+for f in '.session=42' 'del(.session)' '.session=""' '.updated_at="yesterday"' '.ttl_seconds=0' '.ttl_seconds="600"'; do
+ tot=$((tot + 1)); jq "$f" "$T/agent-pristine.json" > "$AR"; s0=$(sum "$NS")
+ r "$SE" env CRUMB_TEST_NOW=$((NOW + 4)) CRUMB_SESSION=second "$C" claim worker . other.c takeover 600; c1=$RC; e1=$ERR
+ r "$SE" env CRUMB_TEST_NOW=$((NOW + 4)) CRUMB_SESSION=first "$C" claim worker . other.c renew 600; c2=$RC
+ if [ $c1 -eq 1 ] && [ $c2 -eq 1 ] && printf '%s' "$e1" | grep -q 'MALFORMED_RECORD: .*agents/worker.json: agent record' && [ "$(sum "$NS")" = "$s0" ]; then n=$((n + 1)); else echo " malformed agent $f: second=$c1 first=$c2 $e1"; fi
+done
+[ $n -eq $tot ] && ok "N22 $tot malformed agent-record variants (session 42/absent/empty, updated_at, ttl): exit 1 for every session, store unchanged" || bad "N22 malformed agent metadata ($n of $tot)"
+cp "$T/agent-pristine.json" "$AR"; LR="$NS/dirs/_root.json"; cp "$LR" "$T/lease-pristine.json"
+jq 'del(.locks["other.c"].session)' "$T/lease-pristine.json" > "$LR"
+r "$SE" env CRUMB_TEST_NOW=$((NOW + 4)) "$C" check worker . other.c; c1=$RC; e1=$ERR
+r "$SE" env CRUMB_TEST_NOW=$((NOW + 4)) CRUMB_SESSION=second "$C" claim worker . other.c takeover 600
+[ $c1 -eq 1 ] && printf '%s' "$e1" | grep -q 'MALFORMED_LEASE: .*session is not a non-empty string' && [ $RC -eq 1 ] && ok "N22 a lease without its session: check and claim exit 1 (MALFORMED_LEASE)" || { why; bad "N22 sessionless lease"; }
+cp "$T/lease-pristine.json" "$LR"
+
+# ---- N23 (review B4) crumb check on an initialized store whose .lock is missing: exit 1, lock never created ----
+NL="$T/nolock"; NLR="$T/nolock-root"; mkrepo "$NL" https://github.com/acme/nolock.git; enroll "$NL" "$NLR"
+r "$NL" "$C" claim alice . src/a.c x 600; rm -f "$NLR/.lock"
+r "$NL" "$C" check alice . src/a.c --key src/a.c --generation 1
+[ $RC -eq 1 ] && herr 'STORE_LOCK_MISSING' && [ ! -e "$NLR/.lock" ] && ok "N23 enforced layout-2 store without .lock: check exit 1 (no HELD), lock not created" || { why; bad "N23 enforced missing lock"; }
+git -C "$NL" config crumb.enforce false
+r "$NL" "$C" check alice . src/a.c
+[ $RC -eq 1 ] && herr 'STORE_LOCK_MISSING' && [ ! -e "$NLR/.lock" ] && ok "N23 the same layout-2 store outside enforcement: exit 1" || { why; bad "N23 layout-2 missing lock"; }
+git -C "$NL" config crumb.enforce true
+N1R="$T/nolock1"; mkrepo "$N1R" -
+r "$N1R" "$C" claim alice . src/a.c x 600; rm -f "$N1R/.git/crumb/v1/.lock"
+r "$N1R" "$C" check alice . src/a.c
+[ $RC -eq 1 ] && herr 'STORE_LOCK_MISSING' && [ ! -e "$N1R/.git/crumb/v1/.lock" ] && ok "N23 a used layout-1 store without .lock: exit 1, lock not created" || { why; bad "N23 layout-1 missing lock"; }
+N0R="$T/nolock0"; mkrepo "$N0R" -
+r "$N0R" "$C" check alice . src/a.c
+[ $RC -eq 2 ] && has '^REFUSED absent src/a.c' && [ ! -e "$N0R/.git/crumb" ] && ok "N23 control: a never-used compatibility store is still REFUSED absent (exit 2), nothing created" || { why; bad "N23 never-used store"; }
+
+# ---- N24 (review B5) ttl: the writer accepts exactly what the strict reader accepts (1..315360000 in enforcement) ----
+TT="$T/ttl"; mkrepo "$TT" https://github.com/acme/ttl.git; enroll "$TT" "$ROOT"; NS="$ROOT/repos/acme/ttl"
+r "$TT" "$C" claim alice . src/a.c base 600; s0=$(sum "$NS"); n=0; tot=0
+for v in 9223372036854775807999999999999999999999992305843009213693952315360001 -5 +5; do
+ tot=$((tot + 1)); r "$TT" "$C" claim bob . src/b.c x "$v"
+ if [ $RC -eq 1 ] && herr 'bad ttl' && [ "$(sum "$NS")" = "$s0" ]; then n=$((n + 1)); else echo " ttl $v: rc=$RC $OUT"; fi
+done
+[ $n -eq $tot ] && ok "N24 $tot out-of-range or malformed ttls (LONG_MAX, overflow, LONG_MAX/4+1, 315360001, -5, +5): exit 1, store unchanged" || bad "N24 ttl range ($n of $tot)"
+r "$TT" env CRUMB_TEST_NOW=$NOW "$C" claim bob . src/b.c max 315360000; c1=$RC
+r "$TT" env CRUMB_TEST_NOW=$NOW "$C" check bob . src/b.c
+[ $c1 -eq 0 ] && [ $RC -eq 0 ] && has 'expires 2037-01-12T08:00:00Z$' && ok "N24 ttl 315360000 (3650 days) is accepted and checks HELD, expires 2037-01-12T08:00:00Z" || { why; bad "N24 max ttl"; }
+r "$TT" env CRUMB_TEST_NOW=$NOW "$C" claim carol . src/deep/d.c after 600
+[ $RC -eq 0 ] && ok "N24 the namespace is not poisoned: an unrelated claim succeeds" || { why; bad "N24 poisoned"; }
+s0=$(sum "$NS"); r "$TT" "$C" update carol . focus 0; c1=$RC; r "$TT" "$C" update carol . focus 315360001
+[ $c1 -eq 1 ] && [ $RC -eq 1 ] && [ "$(sum "$NS")" = "$s0" ] && ok "N24 update with ttl 0 or 315360001 in enforcement: exit 1, store unchanged" || { why; bad "N24 update ttl ($c1)"; }
+TL="$T/ttl1"; mkrepo "$TL" -
+r "$TL" "$C" claim alice . src/a.c x 9223372036854775807
+[ $RC -eq 1 ] && herr 'bad ttl' && [ ! -e "$TL/.git/crumb/v1/dirs/src.json" ] && ok "N24 layout 1 refuses an over-range ttl too (no record written)" || { why; bad "N24 layout-1 ttl"; }
+
+# ---- N25 (review B6) the generations high-water mark never decreases ----
+GW="$T/hwm"; mkrepo "$GW" https://github.com/acme/hwm.git; enroll "$GW" "$ROOT"; REC="$ROOT/repos/acme/hwm/dirs/src.json"
+r "$GW" "$C" claim alice . src/a.c g 600; cp "$REC" "$T/hwm-pristine.json"
+jq '.generations["src/a.c"]=10' "$T/hwm-pristine.json" > "$REC"; s0=$(cksum < "$REC")
+r "$GW" "$C" claim alice . src/a.c renew 600; c1=$RC; e1=$ERR; r "$GW" "$C" check alice . src/a.c
+[ $c1 -eq 1 ] && printf '%s' "$e1" | grep -q 'MALFORMED_LEASE: .*differs from the record.s generations counter' && [ $RC -eq 1 ] && [ "$(cksum < "$REC")" = "$s0" ] && ok "N25 enforcement: a live lease (generation 1) with counter 10: renewal and check exit 1, counter kept" || { why; bad "N25 enforced counter mismatch"; }
+H1="$T/hwm1"; mkrepo "$H1" -; R1="$H1/.git/crumb/v1/dirs/src.json"
+r "$H1" "$C" claim alice . src/a.c g 600; jq '.generations["src/a.c"]=10' "$R1" > "$T/r1.json" && cp "$T/r1.json" "$R1"
+r "$H1" "$C" claim alice . src/a.c renew 600; g1=$(gen); c10=$(jq -r '.generations["src/a.c"]' "$R1")
+r "$H1" "$C" close alice . src/a.c; r "$H1" "$C" claim bob . src/a.c next 600; g2=$(gen)
+[ "$g1" = 1 ] && [ "$c10" = 10 ] && [ "$g2" = 11 ] && ok "N25 layout 1: renewal keeps generation 1 and counter 10; the next acquisition is 11, never a reused 2" || bad "N25 high-water mark lowered (renew $g1 counter $c10 next $g2)"
+sed -e 's/"generation": 1$/"generation": 18446744073709551615/' -e 's/"src\/a.c": 1$/"src\/a.c": 18446744073709551615/' "$T/hwm-pristine.json" > "$REC"
+r "$GW" "$C" claim alice . src/a.c renew 600
+[ $RC -eq 0 ] && has 'generation 18446744073709551615$' && grep -q '"src/a.c": 18446744073709551615$' "$REC" && ok "N25 control: renewal at generation 2^64-1 keeps it" || { why; bad "N25 max renew"; }
+r "$GW" "$C" close alice . src/a.c; s0=$(cksum < "$REC"); r "$GW" "$C" claim bob . src/a.c next 600
+[ $RC -eq 1 ] && herr 'exhausted' && [ "$(cksum < "$REC")" = "$s0" ] && ok "N25 control: after 2^64-1 the counter is exhausted (exit 1), store unchanged, never wraps to 0 or 1" || { why; bad "N25 exhausted"; }
+
+# ---- N26 (review N1) git config crumb.enforce uses git's boolean conversion ----
+BO="$T/bool"; mkrepo "$BO" https://github.com/acme/bool.git; enroll "$BO" "$ROOT"; git -C "$BO" config --unset-all crumb.enforce
+printf '[crumb]\n\tenforce\n' >> "$BO/.git/config"
+r "$BO" "$C" claim alice . src/a.c x 0
+[ $RC -eq 1 ] && herr 'enforcement mode needs a positive ttl' && ok "N26 a valueless crumb.enforce key is true (git --bool): ttl 0 refused" || { why; bad "N26 valueless key ignored"; }
+git -C "$BO" config --unset-all crumb.enforce; git -C "$BO" config crumb.enforce maybe
+r "$BO" "$C" claim alice . src/a.c x 600
+[ $RC -eq 1 ] && herr 'crumb.enforce' && ok "N26 control: a non-boolean crumb.enforce is an error (exit 1), never absent" || { why; bad "N26 bad boolean"; }
+git -C "$BO" config crumb.enforce yes; r "$BO" "$C" claim alice . src/a.c x 0; c1=$RC
+git -C "$BO" config crumb.enforce off; r "$BO" "$C" claim alice . src/a.c x 0
+[ $c1 -eq 1 ] && [ $RC -eq 0 ] && ok "N26 control: yes enforces, off does not" || { why; bad "N26 yes/off ($c1)"; }
+git -C "$BO" config crumb.enforce true
+
+# ---- N27 (review N2) a repository id must start with an alphanumeric character (no '/single' alias of 'single') ----
+RI="$T/rid"; mkrepo "$RI" https://github.com/acme/rid.git; enroll "$RI" "$ROOT"
+r "$RI" env CRUMB_REPO_ID=single "$C" claim alice . src/a.c x 600; n=0
+for id in /single /acme/rid -single _single .single; do r "$RI" env CRUMB_REPO_ID="$id" "$C" check alice . src/a.c; [ $RC -eq 3 ] && herr REPO_ID_INVALID && n=$((n + 1)) || echo " repo id $id: rc=$RC $OUT"; done
+[ $n -eq 5 ] && ok "N27 repo ids /single, /acme/rid, -single, _single, .single: REPO_ID_INVALID (exit 3)" || bad "N27 leading non-alphanumeric repo id ($n of 5)"
+git -C "$RI" config crumb.repoId /single; r "$RI" "$C" claim bob . src/b.c x 600; c1=$RC; git -C "$RI" config --unset crumb.repoId
+r "$RI" env CRUMB_REPO_ID=single "$C" check alice . src/a.c
+[ $c1 -eq 3 ] && [ $RC -eq 0 ] && ok "N27 git config crumb.repoId /single refused (exit 3); control: CRUMB_REPO_ID=single still HELD" || { why; bad "N27 config repo id ($c1)"; }
+
+# ---- N28 (review B7) a repository-discovery failure is an error, never "outside git" (no .crumb.local fallback) ----
+# every coordination command in a repository whose .git/config git cannot read: exit 1 GIT_DISCOVERY_FAILED, nothing written
+disc_all() { # disc_all <repo> <label> [env...]: n = commands refused with exit 1 GIT_DISCOVERY_FAILED and no .crumb.local
+ dr=$1; dl=$2; shift 2; n=0
+ for cmd in "claim bob . src/a.c takeover 600" "update bob . focus 600" "whisper bob . - finding" "close alice . src/a.c modify msg" "check alice . src/a.c" "sniff bob ." "list ."; do
+ # shellcheck disable=SC2086
+ r "$dr" env "$@" "$C" $cmd
+ [ $RC -eq 1 ] && herr '^crumb: GIT_DISCOVERY_FAILED' && [ ! -e "$dr/.crumb.local" ] && n=$((n + 1)) || { echo " $dl: $cmd"; why; }
+ done
+}
+DB="$T/disc"; mkrepo "$DB" https://github.com/acme/disc.git; enroll "$DB" "$ROOT"
+r "$DB" "$C" claim alice . src/a.c live 600
+[ $RC -eq 0 ] && has 'generation 1$' && ok "N28 setup: alice holds src/a.c in a repository enforced only by git config" || { why; bad "N28 setup"; }
+cp "$DB/.git/config" "$T/disc-config"; s0=$(sum "$ROOT")
+printf '[broken\n' >> "$DB/.git/config"
+disc_all "$DB" malformed CRUMB_X=0
+[ $n -eq 7 ] && [ "$(sum "$ROOT")" = "$s0" ] && ok "N28 malformed .git/config: claim/update/whisper/close/check/sniff/list exit 1 GIT_DISCOVERY_FAILED, no .crumb.local, shared store byte-identical" || bad "N28 malformed config ($n of 7)"
+disc_all "$DB" malformed-env CRUMB_ENFORCE=1
+[ $n -eq 7 ] && [ "$(sum "$ROOT")" = "$s0" ] && ok "N28 malformed .git/config with CRUMB_ENFORCE=1: the same refusal (a discovery error, not ENFORCE_NO_REPOSITORY)" || bad "N28 malformed config, env enforce ($n of 7)"
+cp "$T/disc-config" "$DB/.git/config"
+r "$DB" "$C" check alice . src/a.c
+[ $RC -eq 0 ] && has '^HELD src/a.c by alice key src/a.c generation 1 ' && ! herr 'crumb.local' && ok "N28 control: config restored, alice's shared-store lease is intact (HELD generation 1, no stray .crumb.local)" || { why; bad "N28 restored"; }
+if [ "$(id -u)" = 0 ]; then
+ echo "NOT_RUN N28 unreadable .git/config (running as root: chmod 000 does not deny root)"
+else
+ chmod 000 "$DB/.git/config"; s0=$(sum "$ROOT")
+ disc_all "$DB" unreadable CRUMB_X=0; chmod 644 "$DB/.git/config"
+ [ $n -eq 7 ] && [ "$(sum "$ROOT")" = "$s0" ] && ok "N28 unreadable .git/config (chmod 000): all seven commands exit 1 GIT_DISCOVERY_FAILED, no .crumb.local, shared store byte-identical" || bad "N28 unreadable config ($n of 7)"
+fi
+PB="$T/disc-plain"; mkrepo "$PB" -; printf '[broken\n' >> "$PB/.git/config"
+r "$PB" "$C" claim alice . src/a.c x 600
+[ $RC -eq 1 ] && herr GIT_DISCOVERY_FAILED && [ ! -e "$PB/.crumb.local" ] && [ ! -e "$PB/.git/crumb" ] && ok "N28 malformed .git/config in a repository with no crumb configuration: exit 1, no .crumb.local, no store created (every mode)" || { why; bad "N28 plain malformed"; }
+GF="$T/disc-gitfile"; mkdir -p "$GF"; echo "gitdir: $T/nowhere" > "$GF/.git"
+r "$GF" "$C" claim alice . x.c x 600
+[ $RC -eq 1 ] && herr GIT_DISCOVERY_FAILED && [ ! -e "$GF/.crumb.local" ] && ok "N28 a .git file naming no repository: exit 1 GIT_DISCOVERY_FAILED, no .crumb.local" || { why; bad "N28 dangling gitdir"; }
+r "$DB/.git" "$C" claim alice . x.c x 600
+[ $RC -eq 1 ] && herr GIT_DISCOVERY_FAILED && [ ! -e "$DB/.git/.crumb.local" ] && ok "N28 inside .git (no work tree): exit 1 GIT_DISCOVERY_FAILED, no .crumb.local written into .git" || { why; bad "N28 inside .git"; }
+NR="$T/disc-norepo"; mkdir -p "$NR"
+r "$NR" "$C" claim alice . x.c x 600
+[ $RC -eq 0 ] && [ -f "$NR/.crumb.local" ] && ! herr GIT_DISCOVERY_FAILED && ok "N28 compatibility control: a genuine non-repository directory still takes the RFC-0001 .crumb.local fallback" || { why; bad "N28 non-repo control"; }
+mkdir -p "$DB/ceil"; r "$DB/ceil" env GIT_CEILING_DIRECTORIES="$DB" "$C" claim alice . x.c x 600
+[ $RC -eq 0 ] && [ -f "$DB/ceil/.crumb.local" ] && ok "N28 compatibility control: git's own discovery ends at GIT_CEILING_DIRECTORIES (\"not a git repository\"): fallback, despite a .git above" || { why; bad "N28 ceiling control"; }
+rm -f "$DB/ceil/.crumb.local"; rmdir "$DB/ceil"
+# re-review of B7: diagnostic text inside a file name or GIT_DIR must not count as "outside any repository"
+DN="$T/disc-name"; mkrepo "$DN" -; git -C "$DN" config crumb.repoId acme/discname; enroll "$DN" "$ROOT"
+r "$DN" "$C" claim alice . src/a.c first 600
+INC="$T/not a git repository (or any"; printf '[core]\n' > "$INC"; git -C "$DN" config include.path "$INC"
+r "$DN" "$C" check alice . src/a.c; r1=$RC
+printf '[broken\n' > "$INC"; s0=$(sum "$ROOT")
+r "$DN" "$C" claim bob . src/a.c takeover 600
+[ $r1 -eq 0 ] && [ $RC -eq 1 ] && herr GIT_DISCOVERY_FAILED && [ ! -e "$DN/.crumb.local" ] && [ "$(sum "$ROOT")" = "$s0" ] && ok "N28 a malformed included config whose file name contains git's non-repository words: exit 1 GIT_DISCOVERY_FAILED, no .crumb.local, store unchanged" || { why; bad "N28 diagnostic in a file name"; }
+printf '[core]\n' > "$INC"
+r "$DN" "$C" check alice . src/a.c --key src/a.c --generation 1
+[ $RC -eq 0 ] && ok "N28 control: include restored, alice still HELD at generation 1" || { why; bad "N28 include restored"; }
+l0=$(cksum < "$NR/.crumb.local")
+r "$NR" env GIT_DIR="$T/not a git repository (or any of the parent directories)" "$C" claim bob . z.c z 600
+[ $RC -eq 1 ] && herr GIT_DISCOVERY_FAILED && [ "$(cksum < "$NR/.crumb.local")" = "$l0" ] && ok "N28 an explicit GIT_DIR naming nothing (with the diagnostic words in its name): exit 1 GIT_DISCOVERY_FAILED, .crumb.local byte-identical" || { why; bad "N28 GIT_DIR words"; }
+r "$NR" env CRUMB_ENFORCE=1 "$C" claim bob . y.c y 600
+[ $RC -eq 1 ] && herr ENFORCE_NO_REPOSITORY && [ "$(cksum < "$NR/.crumb.local")" = "$l0" ] && ok "N28 control: a genuine non-repository under enforcement is still ENFORCE_NO_REPOSITORY, .crumb.local byte-identical" || { why; bad "N28 non-repo enforced"; }
+
+# ---- N29 (review B8) store-init proves the layout-1 record directories empty whatever the enforcement mode ----
+# A layout-1 root with alice's flat lease on src/a.c (dirs/src.json, agents/alice.json); each case hides the records
+# from a permissive scan. Refusal: exit 1, no LAYOUT; after the hiding is undone the records are byte-identical and
+# the lease still blocks bob.
+v1() { # v1 <name>: sets V (repo), W (its layout-1 root), w0 (record checksums)
+ V="$T/b8-$1"; W="$T/b8-$1-root"; mkrepo "$V" "https://github.com/acme/b8-$1.git"; git -C "$V" config crumb.coordinationRoot "$W"
+ (cd "$V" && "$C" claim alice . src/a.c "flat lease" 600 >/dev/null 2>&1); w0=$(sum "$W/dirs"; sum "$W/agents")
+}
+b8() { # b8 <label>: the refused init leaves no LAYOUT; once restored, the records are intact and still block bob
+ [ $RC -eq 1 ] && herr 'STORE_LAYOUT_V1_(UNPROVEN|DATA)' && [ ! -e "$W/LAYOUT" ] && ok "N29 $1: store-init exit 1, no LAYOUT" || { why; bad "N29 $1 refused"; }
+}
+b8after() {
+ r "$V" "$C" claim bob . src/a.c x
+ [ "$(sum "$W/dirs"; sum "$W/agents")" = "$w0" ] && [ $RC -eq 2 ] && [ ! -e "$W/LAYOUT" ] && ok "N29 $1: records byte-identical after restore, alice's lease still blocks bob (exit 2)" || { why; bad "N29 $1 intact"; }
+}
+if [ "$(id -u)" -eq 0 ]; then echo "NOT_RUN N29 permission cases (root bypasses mode bits)"; else
+ v1 unread; chmod 000 "$W/dirs" "$W/agents"; r "$V" "$C" store-init .
+ b8 "unreadable dirs/ and agents/"; chmod 755 "$W/dirs" "$W/agents"; b8after "unreadable dirs/ and agents/"
+ v1 subread; mkdir "$W/dirs/sub"; mv "$W/dirs/src.json" "$W/agents/alice.json" "$W/dirs/sub/"; chmod 300 "$W/dirs/sub"; r "$V" "$C" store-init .
+ b8 "records in an unreadable descendant directory"; chmod 755 "$W/dirs/sub"; mv "$W/dirs/sub/src.json" "$W/dirs/"; mv "$W/dirs/sub/alice.json" "$W/agents/"; rmdir "$W/dirs/sub"
+ b8after "records in an unreadable descendant directory"
+fi
+v1 link; mkdir "$T/b8-away"; mv "$W/dirs/src.json" "$W/agents/alice.json" "$T/b8-away/"; ln -s "$T/b8-away" "$W/dirs/hidden"
+r "$V" "$C" store-init .
+b8 "records behind a descendant symlink"; herr 'dirs/hidden is a symbolic link' || { why; bad "N29 link named"; }
+rm "$W/dirs/hidden"; mv "$T/b8-away/src.json" "$W/dirs/"; mv "$T/b8-away/alice.json" "$W/agents/"; b8after "records behind a descendant symlink"
+v1 toplink; mkdir "$T/b8-top"; mv "$W/dirs" "$W/agents" "$T/b8-top/"; ln -s "$T/b8-top/dirs" "$W/dirs"; ln -s "$T/b8-top/agents" "$W/agents"
+r "$V" "$C" store-init .
+b8 "dirs/ and agents/ are symbolic links"; rm "$W/dirs" "$W/agents"; mv "$T/b8-top/dirs" "$T/b8-top/agents" "$W/"; b8after "dirs/ and agents/ are symbolic links"
+v1 stray; echo x > "$W/continuations/partial.tmp"; mv "$W/dirs/src.json" "$W/agents/alice.json" "$T/b8-away/"
+r "$V" "$C" store-init .
+[ $RC -eq 1 ] && herr STORE_LAYOUT_V1_UNPROVEN && [ ! -e "$W/LAYOUT" ] && [ -f "$W/continuations/partial.tmp" ] && ok "N29 a non-record file under continuations/: STORE_LAYOUT_V1_UNPROVEN exit 1, no LAYOUT, file kept" || { why; bad "N29 stray file"; }
+rm "$W/continuations/partial.tmp"; rm -f "$T/b8-away/src.json" "$T/b8-away/alice.json"; mkdir -p "$W/dirs/src/deep"
+r "$V" "$C" store-init .
+[ $RC -eq 0 ] && [ "$(cat "$W/LAYOUT" 2>/dev/null)" = crumb-coord-layout/2 ] && [ ! -e "$W/dirs" ] && [ ! -e "$W/agents" ] && [ ! -e "$W/continuations" ] && [ -d "$W/repos" ] && ok "N29 control: a layout-1 root holding only empty real directories becomes layout 2 (empty trees removed)" || { why; bad "N29 emptied root"; }
+
+# ---- N30 (CodeQL path hardening) one checked opener: .crumb.local is never read through a final symlink ----
+# The RFC-0001 fallback state file and the layout-1 import read it with crumb_open (O_NOFOLLOW): a symbolic link or
+# FIFO there is refused (REFUSED_RECORD, exit 4) and nothing is written; a regular file still works.
+LN="$T/n30-local"; mkdir -p "$LN"; printf '{"schema_version":"1.0.0","locks":{}}\n' > "$T/n30-elsewhere.json"
+ln -s "$T/n30-elsewhere.json" "$LN/.crumb.local"; e0=$(cksum < "$T/n30-elsewhere.json")
+r "$LN" "$C" claim alice . x.c "through a link" 600
+[ $RC -eq 4 ] && herr 'REFUSED_RECORD: .*\.crumb\.local is a symbolic link' && [ -L "$LN/.crumb.local" ] && [ "$(cksum < "$T/n30-elsewhere.json")" = "$e0" ] && ok "N30 a symlinked .crumb.local outside any repository: claim refused (exit 4), the link and its target untouched" || { why; bad "N30 symlinked .crumb.local"; }
+r "$LN" "$C" list .
+[ $RC -eq 4 ] && herr 'REFUSED_RECORD: .*\.crumb\.local is a symbolic link' && ok "N30 crumb list does not read a symlinked .crumb.local either (exit 4)" || { why; bad "N30 list through a link"; }
+rm "$LN/.crumb.local"; mkfifo "$LN/.crumb.local"
+r "$LN" "$C" claim alice . x.c "fifo" 600
+[ $RC -eq 4 ] && herr 'REFUSED_RECORD: .*\.crumb\.local is a fifo' && [ -p "$LN/.crumb.local" ] && ok "N30 a FIFO .crumb.local is refused (exit 4), never opened for a blocking read" || { why; bad "N30 fifo .crumb.local"; }
+rm "$LN/.crumb.local"; cp "$T/n30-elsewhere.json" "$LN/.crumb.local"
+r "$LN" "$C" claim alice . x.c "regular file" 600
+[ $RC -eq 0 ] && [ -f "$LN/.crumb.local" ] && [ ! -L "$LN/.crumb.local" ] && grep -q '"x.c"' "$LN/.crumb.local" && ok "N30 control: a regular .crumb.local still takes the claim (exit 0)" || { why; bad "N30 regular .crumb.local"; }
+mkrepo "$T/n30-repo" https://github.com/acme/n30.git; ln -s "$T/n30-elsewhere.json" "$T/n30-repo/.crumb.local"
+r "$T/n30-repo" "$C" claim alice . src/a.c "import through a link" 600
+[ $RC -eq 4 ] && herr 'REFUSED_RECORD: .*\.crumb\.local is a symbolic link' && [ -z "$(find "$T/n30-repo/.git/crumb/v1" -name '*.json' 2>/dev/null)" ] && [ "$(cksum < "$T/n30-elsewhere.json")" = "$e0" ] && ok "N30 a layout-1 store never imports a symlinked .crumb.local (exit 4, no records written)" || { why; bad "N30 import through a link"; }
+
+# ---- N31 a configured root with a '..' component is canonicalised where it is resolved (no store path carries one) ----
+mkrepo "$T/n31" https://github.com/acme/n31.git; TP=$(cd "$T" && pwd -P)
+r "$T/n31" env CRUMB_COORD_ROOT="$T/n31-missing/../n31root" "$C" store-init .
+[ $RC -eq 0 ] && has "^STORE_INIT $TP/n31root layout crumb-coord-layout/2 " && [ -f "$T/n31root/LAYOUT" ] && [ ! -e "$T/n31-missing" ] && ok "N31 CRUMB_COORD_ROOT=<abs>/n31-missing/../n31root: store-init names the canonical root, n31-missing/ never created" || { why; bad "N31 env root with .."; }
+git -C "$T/n31" config crumb.coordinationRoot "$T/n31/src/../../n31root"
+r "$T/n31" "$C" claim alice . src/a.c "dotdot root" 600; r1=$RC
+r "$T/n31" env CRUMB_COORD_ROOT="$TP/n31root" "$C" check alice . src/a.c
+[ $r1 -eq 0 ] && [ $RC -eq 0 ] && has '^HELD src/a.c by alice ' && ok "N31 control: git config crumb.coordinationRoot <abs>/n31/src/../../n31root is the same store as the canonical root (alice HELD)" || { why; bad "N31 config root with .."; }
+ln -s "$T/n31root" "$T/n31link"; sid=$(cut -d' ' -f2 "$T/n31root/STORE_ID")
+r "$T/n31" env CRUMB_COORD_ROOT="$T/n31link" CRUMB_ENFORCE=1 CRUMB_EXPECT_STORE_ID="$sid" "$C" claim bob . src/b.c "linked root" 600
+[ $RC -eq 0 ] && has 'generation 1' && ok "N31 control: an enforced root named through a symbolic link still works (only a final link of a store file is refused)" || { why; bad "N31 linked root"; }
+
+echo "namespace/check/enforce: $( [ $fail -eq 0 ] && echo ALL PASS || echo FAILURES )"
+exit $fail
diff --git a/tools/crumb/test.sh b/tools/crumb/test.sh
index d4ae1e3..49ae3b8 100644
--- a/tools/crumb/test.sh
+++ b/tools/crumb/test.sh
@@ -303,6 +303,10 @@ else echo "NOT_RUN C3 differential (jq or crumb-compile.sh missing)"; fi
# Same scripted session in the same path with the pre-#234 tool (built from BASE) and this tool, unregistered and
# registered: stdout of claim/update/whisper/close/sniff/list and every dirs/ and agents/ record must match byte for
# byte once ISO timestamps and heartbeat ages are masked. Only STORE_ID (and the stderr dry-run line) is new.
+# crumb924 added lease generations (fencing tokens): the " generation N" suffix of CLAIMED, each lease's "generation"
+# and the record's "generations" map are masked too (nogen: jq prints these records in the tool's own layout, so the
+# rest is still compared byte for byte); test-namespace.sh covers generations themselves.
+nogen() { jq 'del(.generations) | if (.locks | type) == "object" then .locks |= map_values(del(.generation)) else . end' "$1"; }
BASE=e6e48a0
export GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_SYSTEM=/dev/null; unset CRUMB_COORD_ROOT CRUMB_EXPECT_STORE_ID CRUMB_STRICT_STORE_ID
if git -C "$HERE" cat-file -e "$BASE:tools/crumb/crumb.c" 2>/dev/null; then
@@ -317,9 +321,9 @@ if git -C "$HERE" cat-file -e "$BASE:tools/crumb/crumb.c" 2>/dev/null; then
"$1" update agent-a src "still on a"; "$1" whisper agent-a src agent-b "half done" high src/a.c
(cd "$T/same-wb" && "$1" sniff agent-b src); "$1" close agent-b src a.c; echo "rc=$?"
"$1" close agent-a src a.c modify "done"; (cd "$T/same-wb" && "$1" claim agent-b src a.c "my turn"); "$1" list .
- (cd "$T/same-wb" && "$1" sniff agent-b src); } 2>"$2/stderr" | sed -E 's/[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:]{8}Z/TS/g; s/heartbeat [0-9-]+s/heartbeat Ns/g' > "$2/stdout"
+ (cd "$T/same-wb" && "$1" sniff agent-b src); } 2>"$2/stderr" | sed -E 's/[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:]{8}Z/TS/g; s/heartbeat [0-9-]+s/heartbeat Ns/g; s/ generation [0-9]+$//' > "$2/stdout"
S=$(git rev-parse --absolute-git-dir)/crumb/v1
- (cd "$S" && find dirs agents -type f | sort | while read -r f; do echo "== $f"; sed -E 's/[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:]{8}Z/TS/g' "$f"; done) > "$2/records"
+ (cd "$S" && find dirs agents -type f | sort | while read -r f; do echo "== $f"; case $f in dirs/*) nogen "$f";; *) cat "$f";; esac | sed -E 's/[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:]{8}Z/TS/g'; done) > "$2/records"
[ -f "$S/STORE_ID" ] && cp "$S/STORE_ID" "$2/STORE_ID"
cd "$T" || exit 1; rm -rf "$T/same" "$T/same-wb"
}