From 14966f8941dc5786b050074db4aa21d0149dfb54 Mon Sep 17 00:00:00 2001 From: crumb924-crumb-c Date: Fri, 6 Nov 2026 17:45:06 -0600 Subject: [PATCH 01/13] crumb: repository namespaces (layout 2), crumb check, lease generations, enforcement mode - Store layout 2: /LAYOUT "crumb-coord-layout/2", records under /repos//{dirs,agents,continuations,ledger}; STORE_ID and .lock stay at the root. Created only by the new `crumb store-init` (refused while flat layout-1 records exist); layout-1 stores keep working unchanged. - Repository id: CRUMB_REPO_ID > git config crumb.repoId > origin URL normalised to /; never the path. Relative override roots are anchored at the worktree top-level and canonicalised. - `crumb check [--generation N]`: read-only under a shared lock on /.lock, ancestor-or-self coverage, exit 0/2/1/3/4, HELD/REFUSED. - Lease generation (fencing token) per key, kept on renewal, printed by claim; claim refuses overlap with another agent's lease on an ancestor or descendant. - Enforcement mode (--enforce, CRUMB_ENFORCE=1, git config crumb.enforce true): registered STORE_ID, layout 2 + repo id, verbatim agent ids, one live session per agent id, strict lease schema, no .crumb.local fallback, unreadable store directories are errors. CRUMB_TEST_NOW: test-only clock. - test.sh #234 differential masks the new generation fields. Agent: crumb924-crumb-c (Hermes worker subagent, claude-opus-5-5, anthropic) --- tools/crumb/crumb.c | 552 +++++++++++++++++++++++++++++++++++++++----- tools/crumb/test.sh | 8 +- 2 files changed, 498 insertions(+), 62 deletions(-) diff --git a/tools/crumb/crumb.c b/tools/crumb/crumb.c index 6766768..ac38d13 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 [--generation N] read-only: is target covered by agent's valid lease? * crumb --strict ... refuse an unregistered coordination store (also CRUMB_STRICT_STORE_ID=1) + * crumb --enforce ... 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 /. + * Test-only clock: CRUMB_TEST_NOW= replaces the wall clock (tests of the expiry boundary; never set it + * in production). */ #define _DEFAULT_SOURCE #define _POSIX_C_SOURCE 200809L @@ -289,7 +295,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 +314,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")); @@ -386,6 +427,23 @@ 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); + jset(gens, key, jnum_u64(g)); + return g; +} /* ---------- operations ---------- */ static int legacy_claim(const char *agent, const char *dir, const char *target, const char *intent, long ttl) { @@ -400,12 +458,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 +537,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, + * /repos/ 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; @@ -618,6 +680,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,6 +704,20 @@ 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) { + char *tmp = xmalloc(strlen(path) + 32); + sprintf(tmp, "%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]) { @@ -653,18 +730,10 @@ static void ensure_marker_locked(const char *store, char hex[33]) { 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 */ @@ -706,36 +775,181 @@ static char *session_id(const char *agent) { size_t n = strlen(agent) + strlen(h) + 2; char *s = xmalloc(n); snprintf(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: /LAYOUT holds exactly "crumb-coord-layout/2\n"; records live under /repos//; 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 / (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) return 0; + 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; +} +/* / 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 / 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 (realpath when it exists, else lexically), so the cwd never changes the store. */ +static char *root_canon(const char *v, const char *top) { + if (v[0] == '/') return xstrdup(v); + char *j = pjoin(top, v), r[PATH_MAX]; + if (realpath(j, r)) { free(j); return xstrdup(r); } + char *n = norm_path(j + 1); + if (!n) return j; + char *a = xmalloc(strlen(n) + 2); sprintf(a, "/%s", n); free(j); free(n); + return a; +} +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; } +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 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; + if (!*top || !realpath(top, r)) { + if (g_enforce) die("ENFORCE_NO_REPOSITORY: %s is not inside a git repository; enforcement mode has no .crumb.local fallback", abs); + return NULL; + } top = xstrdup(r); size_t tl = strlen(top); - if (strncmp(abs, top, tl) || (abs[tl] && abs[tl] != '/')) return NULL; + if (strncmp(abs, top, tl) || (abs[tl] && abs[tl] != '/')) { + if (g_enforce) die("ENFORCE_NO_REPOSITORY: %s is not inside its git top-level %s; enforcement mode has no .crumb.local fallback", abs, top); + return NULL; + } + if (!g_enforce) { char *ev = run_git(abs, "config --get crumb.enforce"); if (*ev && bool_word(ev, "git config crumb.enforce")) 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 / (or CRUMB_REPO_ID), or an origin remote URL host//", 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: / if that exists, else from the * repo root if that exists, else repo-relative as given when it contains '/', else /. * An absolute path inside this worktree is made repo-relative, so two worktrees agree. */ @@ -773,38 +987,86 @@ 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 /.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 = open(lp, (create ? O_RDWR | O_CREAT : O_RDONLY) | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC, 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; +} +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); } + t->fd = root_lock(p->root, 1); + 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, + * acquired_at YYYY-MM-DDTHH:MM:SSZ, ttl_seconds a positive integer, 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; 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 > (unsigned long long)LONG_MAX / 4 || (strict && !v)) return "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"; + 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 above the record's generations counter"); + free(nk); free(kd); + } +} 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) { if (!jget(j, "schema_version")) jset(j, "schema_version", jstr(SCHEMA)); if (!jget(j, "directory")) jset(j, "directory", jstr(label)); @@ -812,7 +1074,7 @@ 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; } @@ -823,27 +1085,39 @@ static char *dir_path(const Plane *p, const char *rel) { } 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 *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), *c = xmalloc(strlen(b) + 6); sprintf(c, "%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_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"); @@ -862,7 +1136,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,6 +1156,7 @@ 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; + 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 = slurp(lp); if (!txt) return; J *l = jparse(txt); @@ -927,11 +1202,32 @@ 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) */ +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"); + if (!r->existed || r->dead || !s) return 0; + char *me = session_id(agent); + if (!strcmp(s, me)) { free(me); return 0; } + printf("BLOCKED agent %s is live in session %s, not this session %s (an agent id names one session: use .)\n", agent, s, me); + free(me); + return 1; +} 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 +1238,36 @@ 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); 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 +1277,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 +1290,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 +1310,72 @@ 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 [--generation N] (crumb924; the pre-write guard the session bridge calls). + * Read-only: a shared fcntl lock on /.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 , no other agent holds a valid lease on target or + * an ancestor, and (when given) the nearest such lease has generation N. Exit 2 otherwise (REFUSED line). */ +static int cmd_check(const char *agent, const char *dir, const char *target, int has_want, unsigned long long want) { + 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); + 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 (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 +1385,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 +1394,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"); @@ -1633,8 +2014,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(env) : NULL); /* no repository: env-only identity */ printf("EXPLAIN %s\n repository path: %s\n", abs, rel); /* 1. nearest .crumb */ @@ -1734,6 +2114,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"); @@ -1767,11 +2148,14 @@ static char *cc_path(void) { size_t n = strlen(h) + 64; char *s = xmalloc(n); snprintf(s, n, "%s/.claude/skills/checkpoint/scripts/cc.sh", h); return s; } -static void cc_env(Plane *p) { /* records must land in /continuations */ +static void cc_env(Plane *p) { /* records must land in /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 { char *st = env_store(env); if (strcmp(st, env)) { 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); } } @@ -2277,6 +2661,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 +2681,55 @@ 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 [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 while the root holds flat (layout 1) records, 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 }; + for (int i = 0; flat[i]; i++) { + char *d = pjoin(p->root, flat[i]); + if (count_json(d)) die("STORE_LAYOUT_V1_DATA: %s holds layout-1 records; 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", d, p->root); + free(d); + } + static const char *empty[] = { "dirs", "agents", "continuations", "ledger", NULL }; + for (int i = 0; empty[i]; i++) { char *d = pjoin(p->root, empty[i]); rmdir(d); free(d); } /* empty ones only */ + 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 / 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] ...\n" + fputs("usage: crumb [--strict] [--enforce] ...\n" " seed [-n] [-v] write/refresh .crumb files (idempotent; -n dry run)\n" " backfill [--since ] [-n] reconstruct history from git + lane reports (run after seed)\n" " create [layer] new .crumb for one directory\n" @@ -2328,13 +2751,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// namespaces), deliberately\n" + " check [--generation N] 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 /.\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 +2795,8 @@ 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 == 5 && !strcmp(v[3], "--generation")))) return cmd_check(v[0], v[1], v[2], a == 5, a == 5 ? gen_arg(v[4]) : 0); 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.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" } From 0f2c9b8daaa3759aea577531800a29e66e83d66a Mon Sep 17 00:00:00 2001 From: crumb924-crumb-c Date: Fri, 6 Nov 2026 17:52:01 -0600 Subject: [PATCH 02/13] crumb: test-namespace.sh (75 checks), RFC-0002 sections 2.7/2.8, fail-closed dir sync - tools/crumb/test-namespace.sh, wired into `make test`: cross-repository, independent clones (8-way race), linked worktrees, overlap, generations and check --generation, expiry boundary via CRUMB_TEST_NOW, check absent/expired/held-by and read-only, agent id validation, aliases and duplicate sessions, malformed lease schema, chmod 000 store dir, STORE_ID mismatch, hostile record, legacy fallback refused, layout 1 never reinterpreted, repository id rules, relative root, concurrent claims. - RFC-0002 2.7 (layout 2, repository id, store-init, migration rule) and 2.8 (check, generations, overlap, enforcement mode, test clock); section 8 scope and section 9 test table updated; AGENT_WORKFLOW gains the enforced-repo workflow and onboarding/migration commands. - Enforcement mode: a failed directory open/fsync after a write is an error. Agent: crumb924-crumb-c (Hermes worker subagent, claude-opus-5-5, anthropic) --- docs/CRUMB_PROTOCOL_RFC_0002.md | 23 ++- docs/crumbs/AGENT_WORKFLOW.md | 16 ++ tools/crumb/Makefile | 1 + tools/crumb/crumb.c | 9 +- tools/crumb/test-namespace.sh | 274 ++++++++++++++++++++++++++++++++ 5 files changed, 320 insertions(+), 3 deletions(-) create mode 100644 tools/crumb/test-namespace.sh diff --git a/docs/CRUMB_PROTOCOL_RFC_0002.md b/docs/CRUMB_PROTOCOL_RFC_0002.md index 3b3d7b5..87fa47d 100644 --- a/docs/CRUMB_PROTOCOL_RFC_0002.md +++ b/docs/CRUMB_PROTOCOL_RFC_0002.md @@ -67,6 +67,24 @@ 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 `/` (`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.** `/STORE_ID` (unchanged, section 3.1), `/LAYOUT` holding exactly `crumb-coord-layout/2\n`, `/.lock` (one transaction lock for the whole root), records under `/repos//{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/.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), refuses with `STORE_LAYOUT_V1_DATA` (exit 1) while the root holds layout-1 records in `dirs/`, `agents/` or `continuations/`, then publishes `LAYOUT` once (`link(2)`, never replaced) and creates `repos/`. 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 exactly as before** (compatibility mode, the default for every existing store, including `/crumb/v1`): same records, same paths, same output apart from the lease generation (section 2.8). 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. +- **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. +- **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 `, `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//`); (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. `claim` prints `... generation ` at the end of its `CLAIMED` line. +- **Overlap.** `claim` refuses (exit 2, the usual `BLOCKED held by ...` line, suffixed `[overlapping lease on ]`) 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. +- **`crumb check [--generation N]`.** 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 `/.lock` (never created) for a consistent read; nothing is created, swept or pruned. `` 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 ``, no other agent holds a valid lease on the target or an ancestor, and, with `--generation N`, the nearest such lease has generation N: stdout `HELD by key generation expires `. Exit 2 otherwise, stdout `REFUSED ...` with reason `absent`, `expired`, `held-by ` or `generation !=`. 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 it writes, that the lease it was granted is still the current one. +- **Enforcement mode** (`--enforce`, `CRUMB_ENFORCE=1`, or `git config crumb.enforce true`; none of them can turn it off once another turned it on). 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); the strict lease schema (`holder` a non-empty string, `acquired_at` exactly `YYYY-MM-DDTHH:MM:SSZ`, `ttl_seconds` a positive integer, `generation` an integer >= 1, 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 a live agent's id from another session (`CRUMB_SESSION`, else `@`) is refused (`BLOCKED agent is live in session ...`, exit 2); `claim` needs a positive ttl. +- **Test clock.** `CRUMB_TEST_NOW=` 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,7 +101,7 @@ Two agents pointed at two different coordination roots each believe they hold th - **Marker.** `/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 `. 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 `. 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 ` suffix of `CLAIMED`, each lease's `generation`, the record's `generations` map). 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 ` 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. @@ -145,7 +163,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 +179,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-N17 | 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 | `tools/crumb/test-namespace.sh` | 75 checks (results in the merging PR; negative control against `c9dd6f37`: 66 of 75 fail, the 9 that pass are controls of unchanged behaviour) | 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..338eb0d 100644 --- a/docs/crumbs/AGENT_WORKFLOW.md +++ b/docs/crumbs/AGENT_WORKFLOW.md @@ -18,6 +18,22 @@ crumb close modify "" # after pushing ``` `` 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 ` before each write and blocks on anything but exit 0. So: +- Your `` is `.` (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 . "" `. 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 ` it prints. +- `crumb check . [--generation N]` answers `HELD ... generation expires