interplane.Get Omega
Read in your language

aien-architecture-mv

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

Brought by drakestapleton

branch main Branches Tags History

aien-architecture-mv / tools / crumb / crumb.c

3114 lines · 192316 bytes Raw Blame History
1/*
2 * crumb: RFC-0001 Crumb Protocol (v1.0.0) + RFC-0002 common coordination plane (v1.1.0) tool. Single file, C11, no dependencies.
3 * Spec: aien-spark/crumb-spec SPEC.md + ROLES.md (archived, pinned at 10b8251).
4 *
5 * crumb seed <root> [-n] [-v] write/refresh .crumb in every qualifying directory
6 * crumb create <dir> <name> <purpose> [layer]
7 * crumb claim <agent> <dir> <target> <intent> [ttl_seconds] scent + advisory lock
8 * crumb update <agent> <dir> <focus> [ttl_seconds] refresh scent
9 * crumb whisper <from> <dir> <to|-> <message> [priority] [target_file]
10 * crumb close <agent> <dir> <target> [action] [message] release lock, history vector
11 * crumb sniff <agent> <dir>
12 * crumb list [path]
13 * crumb validate [path]
14 * crumb store-id [dir] print the coordination store id (STORE_ID marker, shared with synapse-coord)
15 * crumb store-init [dir] deliberately create a layout-2 (repository-namespaced) coordination root
16 * crumb check <agent> <dir> <target> [--generation N] [--key K] read-only: is target covered by agent's valid lease?
17 * crumb --strict <command> ... refuse an unregistered coordination store (also CRUMB_STRICT_STORE_ID=1)
18 * crumb --enforce <command> ... fail-closed enforcement mode (also CRUMB_ENFORCE=1, git config crumb.enforce true)
19 * Registered store identity: CRUMB_EXPECT_STORE_ID, else `git config crumb.storeId` (aien-architecture#234).
20 * Repository identity (layout 2): CRUMB_REPO_ID, else `git config crumb.repoId`, else the origin URL as <owner>/<repo>.
21 * Test-only clock: CRUMB_TEST_NOW=<epoch seconds> replaces the wall clock (tests of the expiry boundary; never set it
22 * in production).
23 */
24#define _DEFAULT_SOURCE
25#define _POSIX_C_SOURCE 200809L
26#include <dirent.h>
27#include <errno.h>
28#include <stdint.h>
29#include <fcntl.h>
30#include <limits.h>
31#include <stdarg.h>
32#include <stdio.h>
33#include <stdlib.h>
34#include <string.h>
35#include <sys/stat.h>
36#include <sys/wait.h>
37#include <time.h>
38#include <unistd.h>
39
40#define SCHEMA "1.0.0"
41#define HISTORY_CAP 20
42#define SCENT_TTL 3600
43#define LOCK_TTL 1800
44#define MAX_TTL 315360000L /* 3650 days: the largest ttl any command writes and the strict reader accepts (crumb924 B5) */
45#define WHISPER_RETENTION (24 * 3600)
46
47static void die(const char *fmt, ...) {
48 va_list ap;
49 va_start(ap, fmt);
50 fprintf(stderr, "crumb: ");
51 vfprintf(stderr, fmt, ap);
52 fprintf(stderr, "\n");
53 va_end(ap);
54 exit(1);
55}
56static void *xmalloc(size_t n) { void *p = malloc(n ? n : 1); if (!p) die("out of memory"); return p; }
57static void *xrealloc(void *q, size_t n) { void *p = realloc(q, n ? n : 1); if (!p) die("out of memory"); return p; }
58static char *xstrdup(const char *s) { size_t n = strlen(s) + 1; char *p = xmalloc(n); memcpy(p, s, n); return p; }
59/* snprintf into a buffer of exactly size bytes, checked: an encoding error or a result that does not fit is an
60 * internal error (exit 1), never a silently truncated path. Every path the tool formats goes through a bounded write. */
61__attribute__((format(printf, 3, 4)))
62static void xsnprintf(char *dst, size_t size, const char *fmt, ...) {
63 va_list ap; va_start(ap, fmt);
64 int r = vsnprintf(dst, size, fmt, ap);
65 va_end(ap);
66 if (r < 0 || (size_t)r >= size) die("internal error: formatted string does not fit its %zu-byte buffer (format \"%s\")", size, fmt);
67}
68
69/* ---------- growable buffer ---------- */
70typedef struct { char *p; size_t n, cap; } Buf;
71static void bput(Buf *b, const char *s, size_t n) {
72 if (b->n + n + 1 > b->cap) { b->cap = (b->n + n + 1) * 2; b->p = xrealloc(b->p, b->cap); }
73 memcpy(b->p + b->n, s, n); b->n += n; b->p[b->n] = 0;
74}
75static void bstr(Buf *b, const char *s) { bput(b, s, strlen(s)); }
76
77/* ---------- minimal ordered JSON DOM (preserves unknown fields) ---------- */
78enum { JNULL, JTRUE, JFALSE, JNUM, JSTR, JARR, JOBJ };
79typedef struct J { int t; char *s; struct J **v; char **k; size_t n, cap; } J;
80
81static J *jnew(int t) { J *j = xmalloc(sizeof *j); memset(j, 0, sizeof *j); j->t = t; return j; }
82static J *jstr(const char *s) { J *j = jnew(JSTR); j->s = xstrdup(s); return j; }
83static J *jnum(long x) { char t[32]; snprintf(t, sizeof t, "%ld", x); J *j = jnew(JNUM); j->s = xstrdup(t); return j; }
84static void jgrow(J *a) { if (a->n == a->cap) { a->cap = a->cap ? a->cap * 2 : 4; a->v = xrealloc(a->v, a->cap * sizeof *a->v); if (a->t == JOBJ) a->k = xrealloc(a->k, a->cap * sizeof *a->k); } }
85static void jpush(J *a, J *v) { jgrow(a); a->v[a->n++] = v; }
86static J *jget(const J *o, const char *key) {
87 if (!o || o->t != JOBJ) return NULL;
88 for (size_t i = 0; i < o->n; i++) if (!strcmp(o->k[i], key)) return o->v[i];
89 return NULL;
90}
91static void jset(J *o, const char *key, J *v) {
92 for (size_t i = 0; i < o->n; i++) if (!strcmp(o->k[i], key)) { o->v[i] = v; return; }
93 jgrow(o); o->k[o->n] = xstrdup(key); o->v[o->n++] = v;
94}
95static void jdel(J *o, const char *key) {
96 for (size_t i = 0; i < o->n; i++) if (!strcmp(o->k[i], key)) {
97 memmove(o->k + i, o->k + i + 1, (o->n - i - 1) * sizeof *o->k);
98 memmove(o->v + i, o->v + i + 1, (o->n - i - 1) * sizeof *o->v);
99 o->n--; return;
100 }
101}
102static const char *jstrval(const J *o, const char *key) { J *v = jget(o, key); return v && v->t == JSTR ? v->s : NULL; }
103static J *jobj_of(J *o, const char *key) { /* get-or-create object member */
104 J *v = jget(o, key);
105 if (!v || v->t != JOBJ) { v = jnew(JOBJ); jset(o, key, v); }
106 return v;
107}
108static J *jarr_of(J *o, const char *key) {
109 J *v = jget(o, key);
110 if (!v || v->t != JARR) { v = jnew(JARR); jset(o, key, v); }
111 return v;
112}
113
114static void jescape(Buf *b, const char *s) {
115 bput(b, "\"", 1);
116 for (const unsigned char *p = (const unsigned char *)s; *p; p++) {
117 char t[8];
118 switch (*p) {
119 case '"': bstr(b, "\\\""); break;
120 case '\\': bstr(b, "\\\\"); break;
121 case '\n': bstr(b, "\\n"); break;
122 case '\r': bstr(b, "\\r"); break;
123 case '\t': bstr(b, "\\t"); break;
124 case '\b': bstr(b, "\\b"); break;
125 case '\f': bstr(b, "\\f"); break;
126 case 0x7f: bstr(b, "\\u007f"); break;
127 default:
128 if (*p < 0x20) { snprintf(t, sizeof t, "\\u%04x", *p); bstr(b, t); }
129 else bput(b, (const char *)p, 1);
130 }
131 }
132 bput(b, "\"", 1);
133}
134static void jprint(const J *j, Buf *b, int ind) {
135 switch (j->t) {
136 case JNULL: bstr(b, "null"); break;
137 case JTRUE: bstr(b, "true"); break;
138 case JFALSE: bstr(b, "false"); break;
139 case JNUM: bstr(b, j->s); break;
140 case JSTR: jescape(b, j->s); break;
141 case JARR:
142 if (!j->n) { bstr(b, "[]"); break; }
143 bstr(b, "[\n");
144 for (size_t i = 0; i < j->n; i++) {
145 for (int s = 0; s < ind + 2; s++) bput(b, " ", 1);
146 jprint(j->v[i], b, ind + 2);
147 bstr(b, i + 1 < j->n ? ",\n" : "\n");
148 }
149 for (int s = 0; s < ind; s++) bput(b, " ", 1);
150 bput(b, "]", 1); break;
151 case JOBJ:
152 if (!j->n) { bstr(b, "{}"); break; }
153 bstr(b, "{\n");
154 for (size_t i = 0; i < j->n; i++) {
155 for (int s = 0; s < ind + 2; s++) bput(b, " ", 1);
156 jescape(b, j->k[i]); bstr(b, ": ");
157 jprint(j->v[i], b, ind + 2);
158 bstr(b, i + 1 < j->n ? ",\n" : "\n");
159 }
160 for (int s = 0; s < ind; s++) bput(b, " ", 1);
161 bput(b, "}", 1); break;
162 }
163}
164static char *jdump(const J *j) { Buf b = {0}; jprint(j, &b, 0); bstr(&b, "\n"); return b.p; }
165
166typedef struct { const char *p; int depth; int err; } P;
167static void pws(P *p) { while (*p->p == ' ' || *p->p == '\t' || *p->p == '\n' || *p->p == '\r') p->p++; }
168static void putf8(Buf *b, unsigned c) {
169 if (c >= 0xD800 && c < 0xE000) c = 0xFFFD;
170 char t[4]; int n;
171 if (c < 0x80) { t[0] = (char)c; n = 1; }
172 else if (c < 0x800) { t[0] = (char)(0xC0 | c >> 6); t[1] = (char)(0x80 | (c & 63)); n = 2; }
173 else if (c < 0x10000) { t[0] = (char)(0xE0 | c >> 12); t[1] = (char)(0x80 | ((c >> 6) & 63)); t[2] = (char)(0x80 | (c & 63)); n = 3; }
174 else { t[0] = (char)(0xF0 | c >> 18); t[1] = (char)(0x80 | ((c >> 12) & 63)); t[2] = (char)(0x80 | ((c >> 6) & 63)); t[3] = (char)(0x80 | (c & 63)); n = 4; }
175 bput(b, t, (size_t)n);
176}
177static int hex4(const char *s, unsigned *out) {
178 unsigned v = 0;
179 for (int i = 0; i < 4; i++) {
180 char c = s[i]; v <<= 4;
181 if (c >= '0' && c <= '9') v |= (unsigned)(c - '0');
182 else if (c >= 'a' && c <= 'f') v |= (unsigned)(c - 'a' + 10);
183 else if (c >= 'A' && c <= 'F') v |= (unsigned)(c - 'A' + 10);
184 else return 0;
185 }
186 *out = v; return 1;
187}
188static char *pstring(P *p) {
189 Buf b = {0}; bstr(&b, "");
190 p->p++;
191 while (*p->p && *p->p != '"') {
192 if (*p->p == '\\') {
193 p->p++;
194 switch (*p->p) {
195 case 'n': bput(&b, "\n", 1); break;
196 case 't': bput(&b, "\t", 1); break;
197 case 'r': bput(&b, "\r", 1); break;
198 case 'b': bput(&b, "\b", 1); break;
199 case 'f': bput(&b, "\f", 1); break;
200 case '/': case '\\': case '"': bput(&b, p->p, 1); break;
201 case 'u': {
202 unsigned c, d;
203 if (!hex4(p->p + 1, &c)) { p->err = 1; return b.p; }
204 p->p += 4;
205 if (c >= 0xD800 && c < 0xDC00 && p->p[1] == '\\' && p->p[2] == 'u' && hex4(p->p + 3, &d) && d >= 0xDC00 && d < 0xE000) {
206 c = 0x10000 + ((c - 0xD800) << 10) + (d - 0xDC00); p->p += 6;
207 }
208 putf8(&b, c); break;
209 }
210 default: p->err = 1; return b.p;
211 }
212 p->p++;
213 } else bput(&b, p->p++, 1);
214 }
215 if (*p->p != '"') p->err = 1; else p->p++;
216 return b.p;
217}
218static J *pvalue(P *p) {
219 pws(p);
220 if (p->err || ++p->depth > 64) { p->err = 1; return NULL; }
221 J *r = NULL;
222 char c = *p->p;
223 if (c == '{') {
224 r = jnew(JOBJ); p->p++; pws(p);
225 if (*p->p == '}') p->p++;
226 else for (;;) {
227 pws(p);
228 if (*p->p != '"') { p->err = 1; break; }
229 char *k = pstring(p); pws(p);
230 if (*p->p != ':') { p->err = 1; break; }
231 p->p++;
232 J *v = pvalue(p); if (!v) break;
233 jset(r, k, v); pws(p);
234 if (*p->p == ',') { p->p++; continue; }
235 if (*p->p == '}') { p->p++; break; }
236 p->err = 1; break;
237 }
238 } else if (c == '[') {
239 r = jnew(JARR); p->p++; pws(p);
240 if (*p->p == ']') p->p++;
241 else for (;;) {
242 J *v = pvalue(p); if (!v) break;
243 jpush(r, v); pws(p);
244 if (*p->p == ',') { p->p++; continue; }
245 if (*p->p == ']') { p->p++; break; }
246 p->err = 1; break;
247 }
248 } else if (c == '"') { r = jnew(JSTR); r->s = pstring(p); }
249 else if (!strncmp(p->p, "true", 4)) { r = jnew(JTRUE); p->p += 4; }
250 else if (!strncmp(p->p, "false", 5)) { r = jnew(JFALSE); p->p += 5; }
251 else if (!strncmp(p->p, "null", 4)) { r = jnew(JNULL); p->p += 4; }
252 else if (c == '-' || (c >= '0' && c <= '9')) {
253 const char *s = p->p;
254 while (*p->p == '-' || *p->p == '+' || *p->p == '.' || *p->p == 'e' || *p->p == 'E' || (*p->p >= '0' && *p->p <= '9')) p->p++;
255 r = jnew(JNUM); r->s = xmalloc((size_t)(p->p - s) + 1); memcpy(r->s, s, (size_t)(p->p - s)); r->s[p->p - s] = 0;
256 { char *end; (void)strtod(r->s, &end); if (end == r->s || *end) p->err = 1; }
257 } else p->err = 1;
258 p->depth--;
259 return p->err ? NULL : r;
260}
261static J *jparse(const char *s) {
262 P p = { s, 0, 0 };
263 J *j = pvalue(&p);
264 if (!j) return NULL;
265 pws(&p);
266 return *p.p ? NULL : j;
267}
268
269/* ---------- files ---------- */
270/* The one file opener: every open(2)/fopen(3) of this tool goes through crumb_open or crumb_open_follow.
271 * - An empty path, or one with a ".." component, is refused before any open (exit 1, never treated as absent):
272 * every path the tool opens is built from a canonical directory (realpath; a configured root, HOME or git path
273 * with a ".." is canonicalised where it is resolved, canon_path), keys normalised by norm_path, readdir names
274 * (never "." or "..") and constant names, so a ".." here is a resolution bug and is never followed.
275 * - O_CLOEXEC always: no descriptor leaks into the git or cc.sh children.
276 * - O_NOFOLLOW (crumb_open) unless the call site must read through a final symbolic link (crumb_open_follow: the
277 * working tree's own files such as .crumb or .gitignore, which git can track as links; git's info/exclude; the
278 * operator's lane reports; /dev/urandom; a directory opened only to fsync it, whose path may name a linked root).
279 * - openat(AT_FDCWD, ...).
280 * crumb is a local CLI without a privilege boundary: the paths come from the operator's own configuration
281 * (CRUMB_COORD_ROOT, git config, argv). This opener does not change that trust model; it makes the rules uniform. */
282static int has_dotdot(const char *p) { /* 1 when some '/'-separated component of p is exactly ".." */
283 for (const char *s = p;;) {
284 const char *e = strchr(s, '/'); size_t n = e ? (size_t)(e - s) : strlen(s);
285 if (n == 2 && s[0] == '.' && s[1] == '.') return 1;
286 if (!e) return 0;
287 s = e + 1;
288 }
289}
290static int open_checked(const char *path, int flags, mode_t mode, int follow) {
291 if (!*path) die("PATH_REFUSED: empty path; refusing to open it");
292 if (has_dotdot(path)) die("PATH_REFUSED: %s has a '..' component; refusing to open it (crumb opens canonical paths only)", path);
293 return openat(AT_FDCWD, path, flags | O_CLOEXEC | (follow ? 0 : O_NOFOLLOW), mode);
294}
295static int crumb_open(const char *path, int flags, mode_t mode) { return open_checked(path, flags, mode, 0); }
296static int crumb_open_follow(const char *path, int flags, mode_t mode) { return open_checked(path, flags, mode, 1); }
297/* a working-tree file (follows a final symlink); NULL when it cannot be opened */
298static char *slurp(const char *path) {
299 int fd = crumb_open_follow(path, O_RDONLY, 0);
300 if (fd < 0) return NULL;
301 FILE *f = fdopen(fd, "rb");
302 if (!f) { close(fd); return NULL; }
303 Buf b = {0}; bstr(&b, "");
304 char t[4096]; size_t n;
305 while ((n = fread(t, 1, sizeof t, f)) > 0) bput(&b, t, n);
306 fclose(f);
307 return b.p;
308}
309/* Every file this tool creates is mode 0644 (minus umask), never 0666: fopen() would create it world-writable
310 * under a permissive umask (CodeQL cpp/world-writable-file-creation). append=1 opens git's info/exclude for appending
311 * (following a final link, as slurp read it); otherwise path is a fresh temp name and a planted link is refused. */
312static FILE *fcreate(const char *path, int append) {
313 int flags = O_WRONLY | O_CREAT | (append ? O_APPEND : O_TRUNC);
314 int fd = append ? crumb_open_follow(path, flags, 0644) : crumb_open(path, flags, 0644);
315 if (fd < 0) return NULL;
316 FILE *f = fdopen(fd, append ? "a" : "wb");
317 if (!f) close(fd);
318 return f;
319}
320static void spit(const char *path, const char *data) {
321 size_t tn = strlen(path) + 32; char *tmp = xmalloc(tn);
322 xsnprintf(tmp, tn, "%s.tmp%ld", path, (long)getpid());
323 FILE *f = fcreate(tmp, 0);
324 if (!f) die("cannot write %s: %s", tmp, strerror(errno));
325 if (fputs(data, f) < 0 || fclose(f) != 0) die("write failed: %s", tmp);
326 if (rename(tmp, path) != 0) die("rename failed: %s", path);
327}
328static char *pjoin(const char *a, const char *b) {
329 size_t n = strlen(a) + strlen(b) + 2; char *p = xmalloc(n);
330 xsnprintf(p, n, "%s/%s", a, b); return p;
331}
332/* Canonical form of an absolute path: realpath when it exists, else each leading part that exists is resolved with
333 * realpath and the rest is applied lexically (".." of a component that does not exist yet drops it; ".." at / stays
334 * at /, as the kernel does). The result has no "." or ".." component, so no path built on it carries one. */
335static char *canon_path(const char *abs) {
336 char r[PATH_MAX];
337 if (realpath(abs, r)) return xstrdup(r);
338 Buf b = {0}; bstr(&b, "");
339 char *cp = xstrdup(abs);
340 for (char *tok = strtok(cp, "/"); tok; tok = strtok(NULL, "/")) {
341 if (!strcmp(tok, ".")) continue;
342 if (!strcmp(tok, "..")) { char *s = strrchr(b.p, '/'); if (s) { *s = 0; b.n = (size_t)(s - b.p); } continue; }
343 bstr(&b, "/"); bstr(&b, tok);
344 if (realpath(b.p, r)) { b.n = 0; bstr(&b, strcmp(r, "/") ? r : ""); }
345 }
346 free(cp);
347 if (!b.n) bstr(&b, "/");
348 return b.p;
349}
350/* a path the operator configured (environment, HOME), relative ones anchored at the working directory: as given
351 * unless it has a ".." component, which is resolved by canon_path */
352static char *canon_dotdot(const char *v) {
353 if (!has_dotdot(v)) return xstrdup(v);
354 if (v[0] == '/') return canon_path(v);
355 char cwd[PATH_MAX]; if (!getcwd(cwd, sizeof cwd)) die("cannot resolve the working directory for %s: %s", v, strerror(errno));
356 char *j = pjoin(cwd, v), *c = canon_path(j); free(j); return c;
357}
358static char *absdir(const char *d) {
359 char r[PATH_MAX];
360 if (!realpath(d, r)) die("no such directory: %s", d);
361 struct stat st; if (stat(r, &st) || !S_ISDIR(st.st_mode)) die("not a directory: %s", d);
362 return xstrdup(r);
363}
364static const char *base_of(const char *p) { const char *s = strrchr(p, '/'); return s && s[1] ? s + 1 : p; }
365
366/* ---------- time ---------- */
367/* CRUMB_TEST_NOW (test-only, documented in RFC-0002 section 2.8): a fixed epoch second instead of the wall clock, so
368 * the lease expiry boundary can be tested exactly. Anything but decimal digits is refused. */
369static long now_epoch(void) {
370 const char *e = getenv("CRUMB_TEST_NOW");
371 if (!e || !*e) return (long)time(NULL);
372 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);
373 if (strlen(e) > 12) die("CRUMB_TEST_NOW is out of range: %s", e);
374 return atol(e);
375}
376static 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); }
377static void now_iso(char *out) { iso_of(now_epoch(), out); }
378static long parse_iso(const char *s) { /* tolerant: first 19 chars, treated as UTC; -1 on failure */
379 struct tm tm; memset(&tm, 0, sizeof tm);
380 int y, mo, d, h, mi, se;
381 if (!s || sscanf(s, "%d-%d-%dT%d:%d:%d", &y, &mo, &d, &h, &mi, &se) != 6) return -1;
382 tm.tm_year = y - 1900; tm.tm_mon = mo - 1; tm.tm_mday = d; tm.tm_hour = h; tm.tm_min = mi; tm.tm_sec = se;
383 return (long)timegm(&tm);
384}
385static long jlong(const J *o, const char *key, long dflt) { J *v = jget(o, key); return v && v->t == JNUM ? atol(v->s) : dflt; }
386/* strict forms (enforcement mode, crumb check): exactly YYYY-MM-DDTHH:MM:SSZ with fields in range; a decimal u64 */
387static int iso_strict(const char *s, long *out) {
388 if (!s || strlen(s) != 20) return 0;
389 for (int i = 0; i < 20; i++) {
390 char c = s[i], want = i == 4 || i == 7 ? '-' : i == 10 ? 'T' : i == 13 || i == 16 ? ':' : i == 19 ? 'Z' : 0;
391 if (want ? c != want : !(c >= '0' && c <= '9')) return 0;
392 }
393 int y, mo, d, h, mi, se;
394 if (sscanf(s, "%4d-%2d-%2dT%2d:%2d:%2d", &y, &mo, &d, &h, &mi, &se) != 6) return 0;
395 static const int mdays[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
396 if (y < 1970 || mo < 1 || mo > 12 || h > 23 || mi > 59 || se > 59 || d < 1) return 0;
397 int leap = (y % 4 == 0 && y % 100) || y % 400 == 0;
398 if (d > mdays[mo - 1] + (mo == 2 && leap)) return 0;
399 long v = parse_iso(s); if (v < 0) return 0;
400 *out = v; return 1;
401}
402static int u64_str(const char *s, unsigned long long *out) {
403 if (!s || !*s || strlen(s) > 20) return 0;
404 for (const char *p = s; *p; p++) if (*p < '0' || *p > '9') return 0;
405 if (s[0] == '0' && s[1]) return 0; /* no leading zeros: one spelling per value */
406 errno = 0; char *e; unsigned long long v = strtoull(s, &e, 10);
407 if (errno || *e) return 0;
408 *out = v; return 1;
409}
410static 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; }
411
412/* ---------- .crumb.local (ephemeral bus) ---------- */
413typedef struct { char *path, *dir, *before; J *root; } Local;
414
415static void sweep(J *root) { /* SPEC 5.4 */
416 long now = now_epoch();
417 J *sc = jget(root, "active_scents");
418 if (sc && sc->t == JOBJ) for (size_t i = sc->n; i-- > 0;) {
419 long u = parse_iso(jstrval(sc->v[i], "updated_at"));
420 if (u < 0 || now - u > jlong(sc->v[i], "ttl_seconds", SCENT_TTL)) jdel(sc, sc->k[i]);
421 }
422 J *lk = jget(root, "locks");
423 if (lk && lk->t == JOBJ) for (size_t i = lk->n; i-- > 0;) {
424 long u = parse_iso(jstrval(lk->v[i], "acquired_at"));
425 if (u < 0 || now - u > jlong(lk->v[i], "ttl_seconds", LOCK_TTL)) jdel(lk, lk->k[i]);
426 }
427 J *wh = jget(root, "whispers");
428 if (wh && wh->t == JARR) {
429 size_t m = 0;
430 for (size_t i = 0; i < wh->n; i++) {
431 long u = parse_iso(jstrval(wh->v[i], "timestamp"));
432 if (u >= 0 && now - u > WHISPER_RETENTION) continue;
433 wh->v[m++] = wh->v[i];
434 }
435 wh->n = m;
436 }
437}
438static char *read_bounded(const char *path, size_t cap, size_t *len);
439/* .crumb.local is this tool's own state file (RFC-0001 fallback), never a link it wrote: read with the store-record
440 * reader (crumb_open, O_NOFOLLOW), so a symbolic link, FIFO or other special file there is refused (REFUSED_RECORD,
441 * exit 4) instead of being read through. The cap only bounds a runaway file; crumb's own files stay far below it. */
442#define MAX_LOCAL_BYTES ((size_t)64 << 20)
443static char *read_local(const char *path) { return read_bounded(path, MAX_LOCAL_BYTES, NULL); }
444static Local local_open(const char *dir) {
445 Local l; l.dir = absdir(dir); l.path = pjoin(l.dir, ".crumb.local");
446 char *txt = read_local(l.path);
447 l.root = txt ? jparse(txt) : NULL;
448 if (txt && (!l.root || l.root->t != JOBJ)) die("%s is not valid JSON; fix or move it aside", l.path);
449 if (!l.root) l.root = jnew(JOBJ);
450 l.before = jdump(l.root); /* compare against the file as parsed, before any change */
451 if (!jget(l.root, "schema_version")) { /* adopt legacy/foreign file, keep every existing field */
452 J *n = jnew(JOBJ); jset(n, "schema_version", jstr(SCHEMA)); jset(n, "directory", jstr(l.dir));
453 for (size_t i = 0; i < l.root->n; i++) jset(n, l.root->k[i], l.root->v[i]);
454 l.root = n;
455 }
456 if (!jget(l.root, "directory")) jset(l.root, "directory", jstr(l.dir));
457 sweep(l.root);
458 return l;
459}
460static char *run_git(const char *root, const char *args);
461static void git_exclude_local(const char *dir) { /* keep .crumb.local out of `git status` even before .gitignore lands */
462 char *gp = run_git(dir, "rev-parse --git-path info/exclude");
463 if (!*gp) return;
464 char *full = gp[0] == '/' ? xstrdup(gp) : pjoin(dir, gp);
465 if (has_dotdot(full)) { char *c = canon_path(full); free(full); full = c; } /* git may print a path with ".." */
466 char *txt = slurp(full);
467 if (txt) { char *c = xstrdup(txt); for (char *l = strtok(c, "\n"); l; l = strtok(NULL, "\n")) if (!strcmp(l, ".crumb.local")) return; }
468 FILE *f = fcreate(full, 1); if (!f) return;
469 fputs(txt && *txt && txt[strlen(txt) - 1] != '\n' ? "\n.crumb.local\n" : ".crumb.local\n", f); fclose(f);
470}
471static void local_save(Local *l) {
472 char *now = jdump(l->root);
473 if (strcmp(now, l->before)) { spit(l->path, now); git_exclude_local(l->dir); }
474}
475static void history_add(J *root, const char *agent, const char *action, const char *target, const char *intent) {
476 char ts[21]; now_iso(ts);
477 J *h = jarr_of(root, "history"), *e = jnew(JOBJ);
478 jset(e, "agent", jstr(agent)); jset(e, "action", jstr(action)); jset(e, "target", jstr(target));
479 jset(e, "intent", jstr(intent)); jset(e, "vector", jstr("")); jset(e, "timestamp", jstr(ts));
480 jpush(h, e);
481 if (h->n > HISTORY_CAP) { size_t d = h->n - HISTORY_CAP; memmove(h->v, h->v + d, HISTORY_CAP * sizeof *h->v); h->n = HISTORY_CAP; }
482}
483static void whisper_add(J *root, const char *from, const char *to, const char *msg, const char *prio, const char *tf) {
484 char ts[21]; now_iso(ts);
485 J *w = jarr_of(root, "whispers"), *e = jnew(JOBJ);
486 jset(e, "from", jstr(from));
487 if (to && strcmp(to, "-")) jset(e, "to", jstr(to));
488 jset(e, "message", jstr(msg));
489 if (tf && *tf) jset(e, "target_file", jstr(tf));
490 jset(e, "timestamp", jstr(ts));
491 if (prio && *prio) jset(e, "priority", jstr(prio));
492 jpush(w, e);
493}
494static void scent_set(J *root, const char *agent, const char *focus, long ttl) {
495 char ts[21]; now_iso(ts);
496 J *s = jobj_of(root, "active_scents"), *e = jget(s, agent);
497 if (!e || e->t != JOBJ) { e = jnew(JOBJ); jset(s, agent, e); }
498 jset(e, "focus", jstr(focus)); jset(e, "updated_at", jstr(ts)); jset(e, "ttl_seconds", jnum(ttl));
499}
500static int has_lock_by(J *root, const char *agent) {
501 J *lk = jget(root, "locks");
502 if (!lk || lk->t != JOBJ) return 0;
503 for (size_t i = 0; i < lk->n; i++) { const char *h = jstrval(lk->v[i], "holder"); if (h && !strcmp(h, agent)) return 1; }
504 return 0;
505}
506/* ---------- lease generation (fencing token) ----------
507 * Per key, the generation strictly increases on every new acquisition (first claim, re-acquire after expiry, takeover
508 * after release); a renewal by the current valid holder keeps it. The highest generation ever issued for a key is kept
509 * in the record's "generations" map, which outlives the lease itself (close and expiry remove only the lease). */
510static 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; }
511static unsigned long long gen_next(J *rec, const char *path, const char *key, const J *cur, const char *agent) {
512 J *gens = jget(rec, "generations");
513 if (gens && gens->t != JOBJ) die("MALFORMED_RECORD: %s: \"generations\" is not an object; refusing (a reset counter would reuse fencing tokens)", path);
514 gens = jobj_of(rec, "generations");
515 unsigned long long last = jgen(gens, key), cg = cur ? jgen(cur, "generation") : 0;
516 if (cg > last) last = cg;
517 const char *h = cur ? jstrval(cur, "holder") : NULL;
518 unsigned long long g = cur && cg && h && !strcmp(h, agent) ? cg : last + 1;
519 if (!g) die("generation counter for %s is exhausted", key);
520 /* the high-water mark never decreases: a renewal keeps the lease's generation but never lowers a larger
521 * counter (crumb924 B6; enforcement mode refuses such a pair before this point, dir_record_strict) */
522 jset(gens, key, jnum_u64(g > last ? g : last));
523 return g;
524}
525
526/* ---------- operations ---------- */
527static int legacy_claim(const char *agent, const char *dir, const char *target, const char *intent, long ttl) {
528 Local l = local_open(dir);
529 J *lk = jget(l.root, "locks");
530 J *cur = lk ? jget(lk, target) : NULL;
531 if (cur) {
532 const char *h = jstrval(cur, "holder");
533 if (h && strcmp(h, agent)) { /* ROLES.md section 2: active lock on same target, must not proceed */
534 printf("BLOCKED %s held by %s since %s (%s)\n", target, h, jstrval(cur, "acquired_at") ? jstrval(cur, "acquired_at") : "?", jstrval(cur, "intent") ? jstrval(cur, "intent") : "");
535 return 2;
536 }
537 }
538 char ts[21]; now_iso(ts);
539 unsigned long long gen = gen_next(l.root, l.path, target, cur, agent);
540 J *e = cur && cur->t == JOBJ ? cur : jnew(JOBJ);
541 jset(e, "holder", jstr(agent)); jset(e, "intent", jstr(intent)); jset(e, "acquired_at", jstr(ts)); jset(e, "ttl_seconds", jnum(ttl));
542 jset(e, "generation", jnum_u64(gen));
543 jset(jobj_of(l.root, "locks"), target, e);
544 scent_set(l.root, agent, intent, SCENT_TTL > ttl ? SCENT_TTL : ttl);
545 local_save(&l);
546 printf("CLAIMED %s in %s as %s (ttl %lds) generation %llu\n", target, l.dir, agent, ttl, gen);
547 return 0;
548}
549static int legacy_update(const char *agent, const char *dir, const char *focus, long ttl) {
550 Local l = local_open(dir);
551 scent_set(l.root, agent, focus, ttl);
552 local_save(&l);
553 printf("SCENT %s in %s: %s (ttl %lds)\n", agent, l.dir, focus, ttl);
554 return 0;
555}
556static int legacy_whisper(const char *from, const char *dir, const char *to, const char *msg, const char *prio, const char *tf) {
557 if (prio && *prio && strcmp(prio, "low") && strcmp(prio, "normal") && strcmp(prio, "high") && strcmp(prio, "critical")) die("priority must be low|normal|high|critical");
558 Local l = local_open(dir);
559 whisper_add(l.root, from, to, msg, prio, tf);
560 local_save(&l);
561 printf("WHISPER %s -> %s in %s\n", from, to && strcmp(to, "-") ? to : "(broadcast)", l.dir);
562 return 0;
563}
564static int legacy_close(const char *agent, const char *dir, const char *target, const char *action, const char *msg) {
565 static const char *ok[] = { "create", "modify", "delete", "audit", "test", "build", NULL };
566 int good = 0; for (int i = 0; ok[i]; i++) if (!strcmp(ok[i], action)) good = 1;
567 if (!good) die("action must be create|modify|delete|audit|test|build");
568 Local l = local_open(dir);
569 J *lk = jget(l.root, "locks"), *cur = lk ? jget(lk, target) : NULL;
570 const char *intent = "";
571 if (cur) {
572 const char *h = jstrval(cur, "holder");
573 if (h && strcmp(h, agent)) { printf("REFUSED: %s is held by %s, not %s\n", target, h, agent); return 2; }
574 if (jstrval(cur, "intent")) intent = jstrval(cur, "intent");
575 }
576 history_add(l.root, agent, action, target, intent);
577 if (cur) jdel(lk, target);
578 if (!has_lock_by(l.root, agent)) { J *sc = jget(l.root, "active_scents"); if (sc) jdel(sc, agent); }
579 if (msg && *msg) whisper_add(l.root, agent, NULL, msg, "normal", target);
580 local_save(&l);
581 printf("CLOSED %s in %s by %s (%s)%s\n", target, l.dir, agent, action, cur ? "" : " [no lock was held]");
582 return 0;
583}
584static void show_local(const char *dir, J *root, const char *agent) {
585 J *sc = jget(root, "active_scents"), *lk = jget(root, "locks"), *wh = jget(root, "whispers");
586 if (sc && sc->t == JOBJ) for (size_t i = 0; i < sc->n; i++)
587 printf(" scent %-16s %s [%s, ttl %lds]\n", sc->k[i], jstrval(sc->v[i], "focus") ? jstrval(sc->v[i], "focus") : "", jstrval(sc->v[i], "updated_at") ? jstrval(sc->v[i], "updated_at") : "?", jlong(sc->v[i], "ttl_seconds", SCENT_TTL));
588 if (lk && lk->t == JOBJ) for (size_t i = 0; i < lk->n; i++)
589 printf(" lock %-16s held by %s: %s [%s]\n", lk->k[i], jstrval(lk->v[i], "holder") ? jstrval(lk->v[i], "holder") : "?", jstrval(lk->v[i], "intent") ? jstrval(lk->v[i], "intent") : "", jstrval(lk->v[i], "acquired_at") ? jstrval(lk->v[i], "acquired_at") : "?");
590 if (wh && wh->t == JARR) for (size_t i = 0; i < wh->n; i++) {
591 const char *to = jstrval(wh->v[i], "to"), *from = jstrval(wh->v[i], "from");
592 if (agent && to && strcmp(to, agent)) continue;
593 printf(" whisper %s -> %s: %s [%s%s%s]\n", from ? from : "?", to ? to : "all", jstrval(wh->v[i], "message") ? jstrval(wh->v[i], "message") : "", jstrval(wh->v[i], "timestamp") ? jstrval(wh->v[i], "timestamp") : "?", jstrval(wh->v[i], "priority") ? " " : "", jstrval(wh->v[i], "priority") ? jstrval(wh->v[i], "priority") : "");
594 }
595 (void)dir;
596}
597static int legacy_sniff(const char *agent, const char *dir) { /* SPEC 5.1 */
598 char *d = absdir(dir), *cp = pjoin(d, ".crumb");
599 char *txt = slurp(cp); J *c = txt ? jparse(txt) : NULL;
600 printf("sniff %s as %s\n", d, agent);
601 if (c) {
602 J *inv = jget(c, "invariants");
603 printf(" .crumb: %s | %s\n", jstrval(c, "name") ? jstrval(c, "name") : "?", jstrval(c, "purpose") ? jstrval(c, "purpose") : "(legacy format)");
604 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);
605 } else printf(" no .crumb here\n");
606 Local l = local_open(d);
607 show_local(d, l.root, agent);
608 return 0;
609}
610
611/* ---------- RFC-0002 common coordination plane ----------
612 * Inside a git repository all operational state lives in one store shared by every
613 * worktree: <git-common-dir>/crumb/v1/{dirs,agents,continuations,ledger}. Outside git the
614 * RFC-0001 .crumb.local behaviour above is used unchanged (legacy fallback). */
615static void mkdir_p(const char *path);
616
617typedef struct { char expect[33]; const char *source; int has_expect, warned; } Ident; /* registered store identity, see below */
618typedef struct { char *store, *top, *abs, *rel, *branch, *head, *base; Ident id; char *root, *repo_id; const char *repo_src; int layout; } Plane;
619/* root: the coordination root (STORE_ID, LAYOUT, .lock). store: where records live, the root itself in layout 1,
620 * <root>/repos/<repo-id> in layout 2 (NULL when layout 2 and no repository id resolved). */
621typedef struct { char *path; J *root; char *before; int agent, dead, existed; } Rec;
622typedef struct { Plane *p; Rec **r; size_t n, cap; int fd; } Txn;
623
624static char *run_git_full(const char *root, const char *args) {
625 Buf q = {0}; bstr(&q, "'");
626 for (const char *p = root; *p; p++) { if (*p == '\'') bstr(&q, "'\\''"); else bput(&q, p, 1); }
627 bstr(&q, "'");
628 size_t cn = q.n + strlen(args) + 32; char *cmd = xmalloc(cn);
629 snprintf(cmd, cn, "git -C %s %s 2>/dev/null", q.p, args);
630 FILE *f = popen(cmd, "r"); Buf b = {0}; bstr(&b, "");
631 if (!f) return b.p;
632 char t[4096]; size_t n;
633 while ((n = fread(t, 1, sizeof t, f)) > 0) bput(&b, t, n);
634 pclose(f);
635 return b.p;
636}
637static char *norm_path(const char *s) { /* collapse . .. // ; NULL if it escapes the root */
638 char *cp = xstrdup(s), **st = xmalloc((strlen(s) + 2) * sizeof *st); size_t n = 0;
639 for (char *tok = strtok(cp, "/"); tok; tok = strtok(NULL, "/")) {
640 if (!strcmp(tok, ".")) continue;
641 if (!strcmp(tok, "..")) { if (!n) return NULL; n--; continue; }
642 st[n++] = tok;
643 }
644 if (!n) return xstrdup(".");
645 Buf b = {0}; bstr(&b, "");
646 for (size_t i = 0; i < n; i++) { if (i) bstr(&b, "/"); bstr(&b, st[i]); }
647 return b.p;
648}
649static char *dir_of(const char *p) { char *c = xstrdup(p), *s = strrchr(c, '/'); if (s) *s = 0; else strcpy(c, "."); return c; }
650static char *key_dir(const char *key) { return strchr(key, '/') ? dir_of(key) : xstrdup("."); }
651static int exists_at(const char *top, const char *rel) { char *f = pjoin(top, rel); struct stat st; int r = lstat(f, &st) == 0; free(f); return r; }
652/* ---------- bounded store reads (aien-architecture#234; byte-compatible with synapse-coord record.rs, synapse#58) ----------
653 * Anyone who can write into the shared coordination store can plant a FIFO, a device, a symlink to /dev/zero or a huge
654 * file under a record name. Every read of a store file (dirs/ and agents/ records, continuations, STORE_ID, .lock) goes
655 * through read_bounded: lstat first (a non-regular name is never opened), then open O_NOFOLLOW|O_NONBLOCK|O_CLOEXEC and
656 * fstat the descriptor (catches a swap between the two), then read at most cap + 1 bytes. A refusal is fatal, named
657 * REFUSED_RECORD, exit EXIT_REFUSED, and leaves the file as found. Caps match synapse-coord. */
658#define MAX_RECORD_BYTES ((size_t)1 << 20) /* records: dirs/ and agents/ JSON, continuations */
659#define MAX_MARKER_BYTES ((size_t)4096) /* STORE_ID */
660#define EXIT_STORE_ID 3 /* store identity refusal: STORE_ID_MISSING/MISMATCH/UNREADABLE/CONFIG_INVALID, STORE_UNREGISTERED */
661#define EXIT_REFUSED 4 /* hostile store file: REFUSED_RECORD */
662static void die_x(int code, const char *fmt, ...) {
663 va_list ap;
664 va_start(ap, fmt);
665 fprintf(stderr, "crumb: ");
666 vfprintf(stderr, fmt, ap);
667 fprintf(stderr, "\n");
668 va_end(ap);
669 exit(code);
670}
671static const char *kind_of(mode_t m) {
672 if (S_ISLNK(m)) return "is a symbolic link";
673 if (S_ISFIFO(m)) return "is a fifo, not a regular file";
674 if (S_ISSOCK(m)) return "is a socket, not a regular file";
675 if (S_ISCHR(m)) return "is a char device, not a regular file";
676 if (S_ISBLK(m)) return "is a block device, not a regular file";
677 if (S_ISDIR(m)) return "is a directory, not a regular file";
678 return "is a special file, not a regular file";
679}
680static void refuse(const char *path, const char *why) {
681 die_x(EXIT_REFUSED, "REFUSED_RECORD: %s %s; refusing to read it (fix or move it aside)", path, why);
682}
683static void refuse_big(const char *path, size_t cap) {
684 char w[64]; snprintf(w, sizeof w, "is larger than %zu bytes", cap); refuse(path, w);
685}
686/* NULL when the name does not exist; *len gets the byte count (the buffer is also NUL-terminated). */
687static char *read_bounded(const char *path, size_t cap, size_t *len) {
688 struct stat st;
689 if (lstat(path, &st) != 0) {
690 if (errno == ENOENT) return NULL;
691 if (errno == ENOTDIR) refuse(path, "has a parent that is not a directory");
692 die("cannot stat %s: %s", path, strerror(errno));
693 }
694 if (!S_ISREG(st.st_mode)) refuse(path, kind_of(st.st_mode));
695 int fd = crumb_open(path, O_RDONLY | O_NONBLOCK, 0);
696 if (fd < 0) {
697 if (errno == ENOENT) return NULL;
698 if (errno == ELOOP) refuse(path, "is a symbolic link");
699 die("cannot open %s: %s", path, strerror(errno));
700 }
701 if (fstat(fd, &st) != 0) die("cannot stat %s: %s", path, strerror(errno));
702 if (!S_ISREG(st.st_mode)) refuse(path, kind_of(st.st_mode));
703 if ((uintmax_t)st.st_size > (uintmax_t)cap) refuse_big(path, cap);
704 Buf b = {0}; bstr(&b, "");
705 char t[4096];
706 while (b.n <= cap) {
707 size_t want = cap + 1 - b.n; if (want > sizeof t) want = sizeof t;
708 ssize_t r = read(fd, t, want);
709 if (r < 0) { if (errno == EINTR) continue; die("read failed: %s: %s", path, strerror(errno)); }
710 if (r == 0) break;
711 bput(&b, t, (size_t)r);
712 }
713 close(fd);
714 if (b.n > cap) refuse_big(path, cap);
715 if (len) *len = b.n;
716 return b.p;
717}
718/* Refuse a store path whose directory components below the store root are not all real directories: a write
719 * through a symlinked directory would land outside the store, and a read would load a record the listing never
720 * shows (collect_json does not follow symlinked directories). Missing components are fine (created later). */
721static void check_real_parents(const char *store, const char *path) {
722 size_t sl = strlen(store);
723 if (strncmp(path, store, sl) || path[sl] != '/') refuse(path, "is outside the coordination store");
724 char *c = dir_of(path);
725 if (strlen(c) > sl) for (char *s = c + sl + 1;;) {
726 char *slash = strchr(s, '/'); if (slash) *slash = 0;
727 struct stat st;
728 if (lstat(c, &st) != 0) { if (errno == ENOENT) break; die("cannot stat %s: %s", c, strerror(errno)); }
729 if (S_ISLNK(st.st_mode)) refuse(c, "is a symbolic link");
730 if (!S_ISDIR(st.st_mode)) refuse(c, "is not a directory");
731 if (!slash) break;
732 *slash = '/'; s = slash + 1;
733 }
734 free(c);
735}
736/* A fresh temp file: whatever has that name is unlinked first, never opened; O_EXCL|O_NOFOLLOW so the write can
737 * neither block on a planted FIFO nor follow a planted link. */
738static int create_temp(const char *tmp) {
739 if (unlink(tmp) != 0 && errno != ENOENT) die("cannot remove stale %s: %s", tmp, strerror(errno));
740 int fd = crumb_open(tmp, O_WRONLY | O_CREAT | O_EXCL, 0644);
741 if (fd < 0) die("cannot write %s: %s", tmp, strerror(errno));
742 return fd;
743}
744static void write_all(int fd, const char *data, size_t len, const char *path) {
745 size_t off = 0;
746 while (off < len) { ssize_t w = write(fd, data + off, len - off); if (w < 0) { if (errno == EINTR) continue; die("write failed: %s", path); } off += (size_t)w; }
747}
748/* ---------- registered store identity (aien-architecture#234; byte-compatible with synapse-coord identity.rs, synapse#15) ----------
749 * <store>/STORE_ID holds one line, "crumb-coord-store-id/1 <32 lowercase hex>\n" (128 bits from /dev/urandom).
750 * Expected id: CRUMB_EXPECT_STORE_ID (non-empty) else `git config crumb.storeId`. Three modes:
751 * registered an expected id is configured: before any operation, and again under the lock of a mutation, the
752 * marker must exist and match (STORE_ID_MISSING / STORE_ID_MISMATCH, exit 3). Never creates a marker.
753 * compatibility nothing configured (default, dry run): works as before; the first mutation creates the marker
754 * exactly as synapse-coord ensure_store_id does (under the lock, tmp + fsync + link(2), never
755 * replacing one), and a one-line STORE_UNREGISTERED warning on stderr names the id to register.
756 * strict --strict or CRUMB_STRICT_STORE_ID=1: an unregistered root is refused (STORE_UNREGISTERED, exit 3).
757 * Outside a git repository (RFC-0001 .crumb.local fallback) there is no coordination store and nothing changes. */
758#define STORE_ID_FILE "STORE_ID"
759#define STORE_ID_FORMAT "crumb-coord-store-id/1"
760static int g_strict; /* --strict or CRUMB_STRICT_STORE_ID=1 */
761static int g_enforce; /* --enforce, CRUMB_ENFORCE=1 or git config crumb.enforce true: fail closed everywhere (implies strict) */
762static int hex_id_ok(const char *s, size_t n) {
763 if (n != 32) return 0;
764 for (size_t i = 0; i < n; i++) if (!((s[i] >= '0' && s[i] <= '9') || (s[i] >= 'a' && s[i] <= 'f'))) return 0;
765 return 1;
766}
767/* 1 and hex filled when <store>/STORE_ID is a valid v1 marker, 0 when absent; any other content is refused. */
768static int read_marker(const char *store, char hex[33]) {
769 char *mp = pjoin(store, STORE_ID_FILE); size_t n = 0;
770 char *b = read_bounded(mp, MAX_MARKER_BYTES, &n);
771 if (!b) { free(mp); return 0; }
772 const char *why = NULL;
773 const char *sp = n ? memchr(b, ' ', n - 1) : NULL;
774 size_t fl = strlen(STORE_ID_FORMAT);
775 if (!n || b[n - 1] != '\n') why = "no trailing newline (torn or foreign file)";
776 else if (!sp) why = "expected `<format> <id>`";
777 else if ((size_t)(sp - b) != fl || memcmp(b, STORE_ID_FORMAT, fl)) why = "unsupported format";
778 else if (!hex_id_ok(sp + 1, n - 1 - fl - 1)) why = "bad id";
779 if (why) die_x(EXIT_STORE_ID, "STORE_ID_UNREADABLE: %s is not a store identity marker: %s; refusing (never rewritten)", mp, why);
780 memcpy(hex, sp + 1, 32); hex[32] = 0;
781 free(b); free(mp);
782 return 1;
783}
784static void fsync_dir(const char *dir);
785/* Publish a new store marker file at path: tmp, fsync, link(2) (never replaces an existing file), dir fsync. */
786static void publish_once(const char *dir, const char *path, const char *data, size_t len) {
787 size_t tn = strlen(path) + 32; char *tmp = xmalloc(tn);
788 xsnprintf(tmp, tn, "%s.tmp%ld", path, (long)getpid());
789 int fd = create_temp(tmp);
790 write_all(fd, data, len, tmp);
791 if (fsync(fd) != 0) die("fsync failed: %s", tmp);
792 if (close(fd) != 0) die("close failed: %s", tmp);
793 int lr = link(tmp, path), le = errno;
794 unlink(tmp);
795 if (lr != 0 && le != EEXIST) die("cannot publish %s: %s", path, strerror(le));
796 fsync_dir(dir);
797 free(tmp);
798}
799/* Create the marker if absent; call only while holding the store's fcntl lock. link(2) never replaces an existing
800 * file, so even a writer outside the lock cannot overwrite a marker. A crash before the link leaves only a tmp file. */
801static void ensure_marker_locked(const char *store, char hex[33]) {
802 if (read_marker(store, hex)) return;
803 unsigned char rb[16]; size_t got = 0;
804 int rf = crumb_open_follow("/dev/urandom", O_RDONLY, 0);
805 if (rf < 0) die("cannot open /dev/urandom: %s", strerror(errno));
806 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; }
807 close(rf);
808 char line[64]; int ll = snprintf(line, sizeof line, "%s ", STORE_ID_FORMAT);
809 for (size_t i = 0; i < sizeof rb; i++) ll += snprintf(line + ll, sizeof line - (size_t)ll, "%02x", rb[i]);
810 line[ll++] = '\n'; line[ll] = 0;
811 char *mp = pjoin(store, STORE_ID_FILE);
812 publish_once(store, mp, line, (size_t)ll);
813 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);
814 free(mp);
815}
816/* Ident (expected store id, its source, warned-once flag) is declared with Plane above. */
817static Ident ident_resolve(const char *gitdir) { /* gitdir NULL: no repository, environment only */
818 Ident id; memset(&id, 0, sizeof id);
819 const char *e = getenv("CRUMB_EXPECT_STORE_ID"); char *v = NULL;
820 if (e && *e) { v = xstrdup(e); id.source = "CRUMB_EXPECT_STORE_ID"; }
821 else if (gitdir) { char *c = run_git(gitdir, "config --get crumb.storeId"); if (*c) { v = c; id.source = "git config crumb.storeId"; } }
822 if (!v) return id;
823 if (!hex_id_ok(v, strlen(v))) die_x(EXIT_STORE_ID, "STORE_ID_CONFIG_INVALID: %s is \"%s\"; expected 32 lowercase hex characters (the id `crumb store-id` prints)", id.source, v);
824 memcpy(id.expect, v, 33); id.has_expect = 1;
825 return id;
826}
827static void ident_warn(Ident *id, const char *store, const char *hex) {
828 if (id->warned) return;
829 id->warned = 1;
830 fprintf(stderr, "crumb: warning: STORE_UNREGISTERED (dry run): coordination store %s is store %s but no store id is registered; register it: git config crumb.storeId %s (strict mode, --strict or CRUMB_STRICT_STORE_ID=1, refuses unregistered stores)\n", store, hex, hex);
831}
832/* locked = 0: before any operation (read-only); locked = 1: inside a mutation, holding the store lock. */
833static void ident_gate(Ident *id, const char *store, int locked) {
834 char hex[33];
835 if (id->has_expect) {
836 if (!read_marker(store, hex))
837 die_x(EXIT_STORE_ID, "STORE_ID_MISSING: coordination store %s has no %s marker; refusing (registered store %s via %s: check CRUMB_COORD_ROOT / crumb.coordinationRoot)", store, STORE_ID_FILE, id->expect, id->source);
838 if (strcmp(hex, id->expect))
839 die_x(EXIT_STORE_ID, "STORE_ID_MISMATCH: coordination store %s is store %s, expected %s (%s); refusing (split coordination roots)", store, hex, id->expect, id->source);
840 return;
841 }
842 if (g_strict && !locked)
843 die_x(EXIT_STORE_ID, "STORE_UNREGISTERED: coordination store %s has no registered store id (strict mode); register it: git config crumb.storeId <id> (from `crumb store-id`) or set CRUMB_EXPECT_STORE_ID", store);
844 if (locked) { ensure_marker_locked(store, hex); ident_warn(id, store, hex); }
845 else if (read_marker(store, hex)) ident_warn(id, store, hex);
846}
847/* stable session id, never a PID alone: CRUMB_SESSION if set, else agent@host */
848static char *session_id(const char *agent) {
849 const char *e = getenv("CRUMB_SESSION");
850 if (e && *e) return xstrdup(e);
851 char h[256]; if (gethostname(h, sizeof h) != 0) strcpy(h, "unknown-host");
852 h[sizeof h - 1] = 0;
853 size_t n = strlen(agent) + strlen(h) + 2; char *s = xmalloc(n); xsnprintf(s, n, "%s@%s", agent, h); return s;
854}
855
856/* ---------- repository namespaces (store layout 2) and enforcement mode (crumb924) ----------
857 * Layout 1 (flat, the default and every store created before layout 2): records directly under the coordination root.
858 * Layout 2: <root>/LAYOUT holds exactly "crumb-coord-layout/2\n"; records live under <root>/repos/<repo-id>/; STORE_ID
859 * and .lock stay at the root. A root becomes layout 2 only through `crumb store-init` (refused while flat records
860 * exist), so a flat store is never reinterpreted. Repository id: CRUMB_REPO_ID, else git config crumb.repoId, else the
861 * origin remote URL normalised to <owner>/<repo> (lowercase); never the filesystem path. */
862#define LAYOUT_FILE "LAYOUT"
863#define LAYOUT_V2 "crumb-coord-layout/2\n"
864static void collect_json(const char *dir, char ***out, size_t *n);
865static int id_char(char c, int agent) {
866 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '_' || c == '-' || (agent && c == '@');
867}
868static int alnum_c(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'); }
869/* ^[A-Za-z0-9][A-Za-z0-9_.@-]{0,159}$ (layout 2 and enforcement mode: used verbatim as the record name, no aliases) */
870static int agent_ok(const char *a) {
871 size_t n = strlen(a);
872 if (n < 1 || n > 160 || !alnum_c(a[0])) return 0;
873 for (size_t i = 0; i < n; i++) if (!id_char(a[i], 1)) return 0;
874 return 1;
875}
876static void agent_require(const Plane *p, const char *agent) { /* p NULL: before resolution (enforcement only) */
877 if (!(g_enforce || (p && p->layout == 2)) || agent_ok(agent)) return;
878 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");
879}
880/* ^[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
881 * (dirs, agents, continuations, ledger), or namespace X/dirs would nest inside namespace X. */
882static int repo_id_ok(const char *s) {
883 size_t n = strlen(s);
884 if (n < 1 || n > 200 || !alnum_c(s[0])) return 0; /* a leading '/' (empty first component) would alias "x" (N2) */
885 const char *sl = strchr(s, '/');
886 if (sl && strchr(sl + 1, '/')) return 0;
887 for (const char *c = s; *c; c++) {
888 if (*c == '/') continue;
889 if ((c == s || c[-1] == '/') && !alnum_c(*c)) return 0;
890 if (!id_char(*c, 0)) return 0;
891 }
892 if (sl) {
893 const char *b = sl + 1;
894 if (!*b || !strcmp(b, "dirs") || !strcmp(b, "agents") || !strcmp(b, "continuations") || !strcmp(b, "ledger")) return 0;
895 }
896 return 1;
897}
898/* <owner>/<repo> from git@host:o/r(.git), ssh://[user@]host[:port]/o/r(.git), https://host/o/r(.git)(/); NULL for a
899 * local path or file:// URL (a path is never an identity) or anything not exactly two path components. */
900static char *repo_id_from_url(const char *url) {
901 const char *path = NULL, *se = strstr(url, "://");
902 if (se) {
903 if (!strncmp(url, "file:", 5)) return NULL;
904 const char *h = se + 3, *slash = strchr(h, '/');
905 if (!slash || slash == h) return NULL;
906 path = slash + 1;
907 } else {
908 const char *colon = strchr(url, ':'), *slash = strchr(url, '/');
909 if (!colon || colon == url || (slash && slash < colon)) return NULL; /* local path, not scp-like */
910 path = colon + 1;
911 }
912 char *c = xstrdup(path); size_t n = strlen(c);
913 while (n && c[n - 1] == '/') c[--n] = 0;
914 if (n > 4 && !strcmp(c + n - 4, ".git")) c[n -= 4] = 0;
915 while (n && c[n - 1] == '/') c[--n] = 0;
916 char *s = c; while (*s == '/') s++;
917 for (char *q = s; *q; q++) if (*q >= 'A' && *q <= 'Z') *q = (char)(*q - 'A' + 'a');
918 if (!strchr(s, '/') || !repo_id_ok(s)) return NULL;
919 return xstrdup(s);
920}
921static char *repo_id_resolve(const char *abs, const char **src) {
922 const char *e = getenv("CRUMB_REPO_ID"); char *v = NULL;
923 if (e && *e) { v = xstrdup(e); *src = "CRUMB_REPO_ID"; }
924 else { char *c = run_git(abs, "config --get crumb.repoId"); if (*c) { v = c; *src = "git config crumb.repoId"; } }
925 if (v) {
926 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);
927 return v;
928 }
929 char *url = run_git(abs, "config --get remote.origin.url");
930 *src = "origin remote URL";
931 return *url ? repo_id_from_url(url) : NULL;
932}
933/* 1: no LAYOUT marker (flat); 2: exactly LAYOUT_V2; anything else is refused (exit 3; hostile file exit 4) */
934static int read_layout(const char *root) {
935 char *lp = pjoin(root, LAYOUT_FILE); size_t n = 0;
936 char *b = read_bounded(lp, MAX_MARKER_BYTES, &n);
937 if (!b) { free(lp); return 1; }
938 if (n != strlen(LAYOUT_V2) || memcmp(b, LAYOUT_V2, n))
939 die_x(EXIT_STORE_ID, "STORE_LAYOUT_UNSUPPORTED: %s is not \"crumb-coord-layout/2\"; refusing (never rewritten)", lp);
940 free(b); free(lp);
941 return 2;
942}
943/* A relative CRUMB_COORD_ROOT / crumb.coordinationRoot is anchored at the worktree top-level, not the process cwd,
944 * and canonicalised (canon_path: realpath of what exists, the rest lexically), so the cwd never changes the store.
945 * An absolute root is used exactly as given unless it has a ".." component, which is canonicalised the same way:
946 * no store path ever carries a "..", and crumb_open refuses one. */
947static char *root_canon(const char *v, const char *top) {
948 if (v[0] == '/' && !has_dotdot(v)) return xstrdup(v);
949 char *j = v[0] == '/' ? xstrdup(v) : pjoin(top, v), *c = canon_path(j);
950 free(j);
951 return c;
952}
953static int bool_word(const char *v, const char *what) { /* git-style boolean; anything else is refused */
954 if (!strcmp(v, "1") || !strcmp(v, "true") || !strcmp(v, "yes") || !strcmp(v, "on")) return 1;
955 if (!*v || !strcmp(v, "0") || !strcmp(v, "false") || !strcmp(v, "no") || !strcmp(v, "off")) return 0;
956 die("%s is \"%s\"; expected true or false", what, v);
957 return 0;
958}
959static void enforce_on(void) { g_enforce = 1; g_strict = 1; }
960/* git config crumb.enforce, read with git's own boolean conversion (`git config --bool --get`: a valueless key, yes,
961 * on, 1, any non-zero integer are true). 1 true, 0 false, -1 absent (git exit 1); any other outcome (a value git
962 * refuses as a boolean, git failing to run) is an error, never "absent" (crumb924 N1). */
963static int git_config_bool(const char *dir, const char *key) {
964 Buf q = {0}; bstr(&q, "'");
965 for (const char *p = dir; *p; p++) { if (*p == '\'') bstr(&q, "'\\''"); else bput(&q, p, 1); }
966 bstr(&q, "'");
967 size_t cn = q.n + strlen(key) + 64; char *cmd = xmalloc(cn);
968 snprintf(cmd, cn, "git -C %s config --bool --get %s 2>/dev/null", q.p, key);
969 FILE *f = popen(cmd, "r");
970 if (!f) die("cannot run git to read git config %s: %s", key, strerror(errno));
971 char t[64]; size_t n = fread(t, 1, sizeof t - 1, f); t[n] = 0;
972 int st = pclose(f), rc = st != -1 && WIFEXITED(st) ? WEXITSTATUS(st) : -1;
973 free(cmd); free(q.p);
974 while (n && (t[n - 1] == '\n' || t[n - 1] == '\r')) t[--n] = 0;
975 if (rc == 1 && !n) return -1;
976 if (rc == 0 && !strcmp(t, "true")) return 1;
977 if (rc == 0 && !strcmp(t, "false")) return 0;
978 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);
979 return 0;
980}
981static char *ns_path(const char *root, const char *repo_id) { char *r = pjoin(root, "repos"), *s = pjoin(r, repo_id); free(r); return s; }
982
983static char *shq(const char *s);
984/* run a git command in dir under the C locale: stdout (trailing newlines stripped) and the exit status (-1 when git
985 * could not be run or did not exit); stderr is captured into *err when err is non-NULL, else discarded */
986static char *git_rc(const char *dir, const char *args, int *rc, char **err) {
987 char *q = shq(dir); size_t cn = strlen(q) + strlen(args) + 96; char *cmd = xmalloc(cn);
988 if (err) snprintf(cmd, cn, "LC_ALL=C LANGUAGE=C git -C %s %s 2>&1 >/dev/null", q, args);
989 else snprintf(cmd, cn, "LC_ALL=C LANGUAGE=C git -C %s %s 2>/dev/null", q, args);
990 FILE *f = popen(cmd, "r"); Buf b = {0}; bstr(&b, "");
991 *rc = -1;
992 if (f) {
993 char t[4096]; size_t n;
994 while ((n = fread(t, 1, sizeof t, f)) > 0) bput(&b, t, n);
995 int st = pclose(f); *rc = st != -1 && WIFEXITED(st) ? WEXITSTATUS(st) : -1;
996 }
997 free(cmd); free(q);
998 while (b.n && (b.p[b.n - 1] == '\n' || b.p[b.n - 1] == '\r')) b.p[--b.n] = 0;
999 if (err) { *err = b.p; return xstrdup(""); }
1000 return b.p;
1001}
1002static int has_git_ancestor(const char *abs) { /* a .git entry (directory, gitdir file or link) in abs or above */
1003 char *d = xstrdup(abs);
1004 for (;;) {
1005 char *g = pjoin(*d ? d : "/", ".git"); struct stat st; int hit = lstat(g, &st) == 0; free(g);
1006 if (hit) { free(d); return 1; }
1007 char *s = strrchr(d, '/'); if (!s || !*d) break;
1008 *s = 0;
1009 }
1010 free(d); return 0;
1011}
1012/* git's own end-of-discovery diagnostic (LC_ALL=C), matched as the WHOLE stderr, never as a substring: git names
1013 * files in other diagnostics ("bad config line 1 in file <path>"), so a path containing the words must not turn a
1014 * configuration error into "outside any repository" (re-review of B7). The two forms git prints: */
1015static int git_nonrepo_diagnostic(const char *err) {
1016 if (!strcmp(err, "fatal: not a git repository (or any of the parent directories): .git")) return 1;
1017 const char *head = "fatal: not a git repository (or any parent up to mount point ",
1018 *tail = ")\nStopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).";
1019 size_t hl = strlen(head), tl = strlen(tail), n = strlen(err);
1020 return n > hl + tl && !strncmp(err, head, hl) && !strcmp(err + n - tl, tail) && !memchr(err + hl, '\n', n - hl - tl);
1021}
1022/* Repository discovery (crumb924 B7). Returns the canonical work-tree top level, or NULL only when the directory is
1023 * positively established to be outside any repository: git's own discovery ran to its end (its whole stderr is
1024 * 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
1025 * any ancestor. Every other failure (a malformed or unreadable .git/config, a .git file or GIT_DIR naming nothing,
1026 * dubious ownership, git not runnable inside a repository, a top level that does not contain the directory) is
1027 * GIT_DISCOVERY_FAILED (exit 1) in every mode, before anything is written: whether enforcement is configured cannot
1028 * be known, so the .crumb.local fallback is never taken on a discovery error. */
1029static char *git_discover(const char *abs) {
1030 int rc; char *top = git_rc(abs, "rev-parse --show-toplevel", &rc, NULL), r[PATH_MAX];
1031 if (rc == 0 && *top) {
1032 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));
1033 free(top); top = xstrdup(r);
1034 size_t tl = strlen(top);
1035 if (strncmp(abs, top, tl) || (abs[tl] && abs[tl] != '/'))
1036 die("GIT_DISCOVERY_FAILED: %s is not inside its git top level %s; refusing (no .crumb.local fallback on a discovery error)", abs, top);
1037 return top;
1038 }
1039 free(top);
1040 char *err = NULL; int rc2; git_rc(abs, "rev-parse --show-toplevel", &rc2, &err);
1041 const char *gd = getenv("GIT_DIR");
1042 int nonrepo = (rc == 128 && rc2 == 128 && !(gd && *gd) && git_nonrepo_diagnostic(err))
1043 || (rc != 0 && !(gd && *gd) && !has_git_ancestor(abs));
1044 if (nonrepo) { free(err); return NULL; }
1045 char *nl = strchr(err, '\n'); if (nl && !strncmp(err, "warning:", 8) && nl[1]) memmove(err, nl + 1, strlen(nl + 1) + 1);
1046 if ((nl = strchr(err, '\n'))) *nl = 0;
1047 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);
1048 return NULL;
1049}
1050static Plane *plane_find(const char *dir) { /* resolve the coordination root; no identity check yet */
1051 char *abs = absdir(dir), *top = git_discover(abs), r[PATH_MAX];
1052 if (!top) {
1053 if (g_enforce) die("ENFORCE_NO_REPOSITORY: %s is not inside a git repository; enforcement mode has no .crumb.local fallback", abs);
1054 return NULL;
1055 }
1056 size_t tl = strlen(top);
1057 if (!g_enforce && git_config_bool(abs, "crumb.enforce") == 1) enforce_on();
1058 Plane *p = xmalloc(sizeof *p); memset(p, 0, sizeof *p);
1059 p->abs = abs; p->top = top; p->rel = abs[tl] ? xstrdup(abs + tl + 1) : xstrdup(".");
1060 const char *env = getenv("CRUMB_COORD_ROOT");
1061 if (env && *env) p->root = root_canon(env, top);
1062 else { char *cfg = run_git(abs, "config --get crumb.coordinationRoot"); if (*cfg) p->root = root_canon(cfg, top); }
1063 if (!p->root) {
1064 char *cd = run_git(abs, "rev-parse --git-common-dir");
1065 if (!*cd) die("inside a git repository (%s) but cannot resolve its common directory; set CRUMB_COORD_ROOT", top);
1066 char *full = cd[0] == '/' ? cd : pjoin(abs, cd);
1067 if (!realpath(full, r)) die("cannot resolve git common directory %s; set CRUMB_COORD_ROOT", full);
1068 p->root = pjoin(r, "crumb/v1");
1069 }
1070 p->branch = run_git(abs, "symbolic-ref --short -q HEAD"); if (!*p->branch) p->branch = xstrdup("(detached)");
1071 p->head = run_git(abs, "rev-parse --short=12 HEAD");
1072 p->base = run_git(abs, "merge-base HEAD origin/main"); if (strlen(p->base) > 12) p->base[12] = 0;
1073 p->id = ident_resolve(abs);
1074 p->layout = read_layout(p->root);
1075 if (p->layout == 2 || g_enforce) p->repo_id = repo_id_resolve(abs, &p->repo_src);
1076 p->store = p->layout == 1 ? xstrdup(p->root) : p->repo_id ? ns_path(p->root, p->repo_id) : NULL;
1077 return p;
1078}
1079static 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; }
1080/* the conditions every coordination command needs on top of the store identity (enforcement mode fails closed) */
1081static void plane_require(Plane *p) {
1082 if (g_enforce && p->layout != 2)
1083 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);
1084 if (p->layout != 2) return;
1085 if (!p->repo_id)
1086 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);
1087 char *fd = pjoin(p->root, "dirs"), *fa = pjoin(p->root, "agents");
1088 if (count_json(fd) + count_json(fa)) {
1089 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);
1090 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);
1091 }
1092 free(fd); free(fa);
1093 char *lp = pjoin(p->abs, ".crumb.local"); struct stat st;
1094 if (lstat(lp, &st) == 0) fprintf(stderr, "crumb: warning: %s is ignored: a layout-2 store never imports .crumb.local\n", lp);
1095 free(lp);
1096}
1097/* every coordination command: resolve the root, then check its identity before touching anything in it */
1098static Plane *plane_resolve(const char *dir) {
1099 Plane *p = plane_find(dir);
1100 if (p) { ident_gate(&p->id, p->root, 0); plane_require(p); }
1101 return p;
1102}
1103/* no repository (explain, checkpoint/resume with only CRUMB_COORD_ROOT): the records base of that root, after the
1104 * env-only identity check; a layout-2 root needs CRUMB_REPO_ID (there is no git config or origin to read) */
1105static char *env_store(const char *root) {
1106 Ident id = ident_resolve(NULL); ident_gate(&id, root, 0);
1107 if (read_layout(root) != 2) return xstrdup(root);
1108 const char *r = getenv("CRUMB_REPO_ID");
1109 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);
1110 if (!repo_id_ok(r)) die_x(EXIT_STORE_ID, "REPO_ID_INVALID: CRUMB_REPO_ID is \"%s\"", r);
1111 return ns_path(root, r);
1112}
1113/* repository-relative key for a target: <dir>/<target> if that exists, else <target> from the
1114 * repo root if that exists, else repo-relative as given when it contains '/', else <dir>/<target>.
1115 * An absolute path inside this worktree is made repo-relative, so two worktrees agree. */
1116static char *target_key(const Plane *p, const char *target, const char *rel) {
1117 if (target[0] == '/') {
1118 size_t tl = strlen(p->top);
1119 if (strncmp(target, p->top, tl) || target[tl] != '/') die("target %s is outside the repository %s", target, p->top);
1120 char *k = norm_path(target + tl + 1);
1121 if (!k) die("target %s escapes the repository", target);
1122 return k;
1123 }
1124 char *c1 = norm_path(strcmp(rel, ".") ? pjoin(rel, target) : target), *c2 = norm_path(target);
1125 if (c1 && strcmp(c1, ".") && exists_at(p->top, c1)) return c1;
1126 if (c2 && strcmp(c2, ".") && exists_at(p->top, c2)) return c2;
1127 if (strchr(target, '/') && c2) return c2;
1128 if (c1) return c1;
1129 if (c2) return c2;
1130 die("target %s escapes the repository", target);
1131 return NULL;
1132}
1133/* directory fsync after a rename or link; best effort normally, fatal in enforcement mode (EINVAL: the filesystem
1134 * cannot sync directories, which is not a failure to persist) */
1135static void fsync_dir(const char *dir) {
1136 int fd = crumb_open_follow(dir, O_RDONLY | O_DIRECTORY, 0);
1137 if (fd < 0) { if (g_enforce) die("cannot open directory %s to sync it: %s", dir, strerror(errno)); return; }
1138 if (fsync(fd) != 0 && g_enforce && errno != EINVAL) die("fsync of directory %s failed: %s", dir, strerror(errno));
1139 close(fd);
1140}
1141static void durable_write(const char *store, const char *path, const char *data) { /* tmp, fsync, rename, fsync dir */
1142 size_t len = strlen(data);
1143 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);
1144 check_real_parents(store, path);
1145 struct stat st; /* never rename over a planted FIFO, socket, device, symlink or directory */
1146 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));
1147 char *dd = dir_of(path); mkdir_p(dd);
1148 size_t tn = strlen(path) + 32; char *tmp = xmalloc(tn);
1149 xsnprintf(tmp, tn, "%s.tmp%ld", path, (long)getpid());
1150 int fd = create_temp(tmp);
1151 write_all(fd, data, len, tmp);
1152 if (fsync(fd) != 0) die("fsync failed: %s", tmp);
1153 if (close(fd) != 0) die("close failed: %s", tmp);
1154 if (rename(tmp, path) != 0) die("rename failed: %s", path);
1155 fsync_dir(dd);
1156}
1157/* fcntl lock on <root>/.lock. create: open O_CREAT, exclusive lock (mutations); else shared lock on an existing lock
1158 * file and -1 when there is none (crumb check: creates nothing). A planted FIFO, device, symlink or directory is refused. */
1159static int root_lock(const char *root, int create) {
1160 char *lp = pjoin(root, ".lock");
1161 struct stat st; /* the lock file is a store file too: a planted FIFO, device, symlink or directory is refused */
1162 if (lstat(lp, &st) == 0) { if (!S_ISREG(st.st_mode)) refuse(lp, kind_of(st.st_mode)); }
1163 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)); }
1164 int fd = crumb_open(lp, (create ? O_RDWR | O_CREAT : O_RDONLY) | O_NONBLOCK, 0644);
1165 if (fd < 0) {
1166 if (!create && errno == ENOENT) { free(lp); return -1; }
1167 if (errno == ELOOP) refuse(lp, "is a symbolic link");
1168 if (errno == EISDIR) refuse(lp, "is a directory, not a regular file");
1169 die("cannot open %s: %s", lp, strerror(errno));
1170 }
1171 if (fstat(fd, &st) != 0) die("cannot stat %s: %s", lp, strerror(errno));
1172 if (!S_ISREG(st.st_mode)) refuse(lp, kind_of(st.st_mode));
1173 struct flock fl; memset(&fl, 0, sizeof fl); fl.l_type = create ? F_WRLCK : F_RDLCK; fl.l_whence = SEEK_SET;
1174 while (fcntl(fd, F_SETLKW, &fl) != 0) if (errno != EINTR) die("cannot lock %s: %s", lp, strerror(errno));
1175 free(lp);
1176 return fd;
1177}
1178/* A root that any command has initialized or written: layout 2 (store-init creates .lock with LAYOUT), enforcement,
1179 * or a layout-1 root holding a marker or record directories (every first mutation creates .lock before them). Only a
1180 * never-used compatibility root may lack .lock; for crumb check that is plain absence (crumb924 B4). */
1181static int store_used(const Plane *p) {
1182 if (p->layout == 2 || g_enforce) return 1;
1183 static const char *names[] = { STORE_ID_FILE, LAYOUT_FILE, "dirs", "agents", NULL };
1184 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; }
1185 return 0;
1186}
1187static Txn *txn_begin(Plane *p, int mutate) {
1188 Txn *t = xmalloc(sizeof *t); memset(t, 0, sizeof *t); t->p = p; t->fd = -1;
1189 if (!mutate) return t;
1190 mkdir_p(p->root);
1191 t->fd = root_lock(p->root, 1); /* the lock exists before any record directory (crumb check relies on it, B4) */
1192 static const char *sub[] = { "dirs", "agents", "continuations", "ledger", NULL };
1193 for (int i = 0; sub[i]; i++) { char *d = pjoin(p->store, sub[i]); mkdir_p(d); free(d); }
1194 ident_gate(&p->id, p->root, 1); /* under the lock: re-check the registered id, or create the marker once */
1195 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);
1196 return t;
1197}
1198/* Strict lease schema (enforcement mode always; crumb check for the leases it judges): holder a non-empty string,
1199 * session a non-empty string, acquired_at YYYY-MM-DDTHH:MM:SSZ, ttl_seconds an integer in 1..MAX_TTL (what claim
1200 * accepts), generation an integer >= 1. Lenient (check
1201 * outside enforcement mode, layout-1 stores written by older tools): a parseable acquired_at, ttl_seconds >= 0 (default
1202 * LOCK_TTL when absent, as the sweep does), generation optional (0 when absent). Returns NULL or what is wrong. */
1203typedef struct { const char *holder, *session; long acq, ttl; unsigned long long gen; } Lease;
1204static const char *lease_parse(const J *e, int strict, Lease *l) {
1205 memset(l, 0, sizeof *l);
1206 if (!e || e->t != JOBJ) return "is not an object";
1207 J *h = jget(e, "holder"); if (!h || h->t != JSTR || !*h->s) return "holder is not a non-empty string";
1208 l->holder = h->s;
1209 J *a = jget(e, "acquired_at");
1210 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";
1211 J *t = jget(e, "ttl_seconds"); unsigned long long v = LOCK_TTL;
1212 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"; }
1213 l->ttl = (long)v;
1214 J *g = jget(e, "generation");
1215 if (g ? g->t != JNUM || !u64_str(g->s, &l->gen) || (strict && !l->gen) : strict) return "generation is not an integer >= 1";
1216 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; }
1217 return NULL;
1218}
1219static void malformed(const char *path, const char *key, const char *why) {
1220 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);
1221}
1222/* enforcement mode: a dir record must be exactly what this tool writes before anything is swept or decided */
1223static void dir_record_strict(const char *path, const J *j, const char *label) {
1224 J *lk = jget(j, "locks"), *gens = jget(j, "generations");
1225 if (lk && lk->t != JOBJ) die("MALFORMED_RECORD: %s: \"locks\" is not an object; refusing", path);
1226 if (gens && gens->t != JOBJ) die("MALFORMED_RECORD: %s: \"generations\" is not an object; refusing", path);
1227 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]); }
1228 if (lk) for (size_t i = 0; i < lk->n; i++) {
1229 Lease l; const char *why = lease_parse(lk->v[i], 1, &l);
1230 if (why) malformed(path, lk->k[i], why);
1231 char *nk = norm_path(lk->k[i]), *kd = nk ? key_dir(nk) : NULL;
1232 if (!nk || strcmp(nk, lk->k[i]) || strcmp(kd, label)) malformed(path, lk->k[i], "is not a normalised key of this directory record");
1233 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)");
1234 free(nk); free(kd);
1235 }
1236}
1237/* enforcement mode: an existing agent record must be what agent_set writes, or session ownership cannot be judged
1238 * (crumb924 B3: a malformed session is an error, never "no session") */
1239static void agent_record_strict(const char *path, const J *j) {
1240 const char *why = NULL; J *s = jget(j, "session"), *u = jget(j, "updated_at"), *t = jget(j, "ttl_seconds"), *a = jget(j, "agent");
1241 long acq; unsigned long long v;
1242 if (!a || a->t != JSTR || !*a->s) why = "agent is not a non-empty string";
1243 else if (!s || s->t != JSTR || !*s->s) why = "session is not a non-empty string";
1244 else if (!u || u->t != JSTR || !iso_strict(u->s, &acq)) why = "updated_at is not a YYYY-MM-DDTHH:MM:SSZ timestamp";
1245 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";
1246 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);
1247}
1248static Rec *rec_load(Txn *t, const char *path, int agent, const char *label) {
1249 for (size_t i = 0; i < t->n; i++) if (!strcmp(t->r[i]->path, path)) return t->r[i];
1250 Rec *r = xmalloc(sizeof *r); memset(r, 0, sizeof *r);
1251 if (t->n == t->cap) { t->cap = t->cap ? t->cap * 2 : 16; t->r = xrealloc(t->r, t->cap * sizeof *t->r); }
1252 t->r[t->n++] = r;
1253 r->path = xstrdup(path); r->agent = agent;
1254 check_real_parents(t->p->root, path); /* never read through a symlinked directory (listing does not follow one) */
1255 size_t len = 0; char *txt = read_bounded(path, MAX_RECORD_BYTES, &len); J *j = txt && strlen(txt) == len ? jparse(txt) : NULL;
1256 if (txt && (!j || j->t != JOBJ)) die("%s is not valid JSON; fix or move it aside", path);
1257 r->existed = txt != NULL;
1258 if (!j) j = jnew(JOBJ);
1259 if (!agent && g_enforce) dir_record_strict(path, j, label);
1260 if (agent && g_enforce && r->existed) agent_record_strict(path, j);
1261 if (!agent) {
1262 if (!jget(j, "schema_version")) jset(j, "schema_version", jstr(SCHEMA));
1263 if (!jget(j, "directory")) jset(j, "directory", jstr(label));
1264 }
1265 r->root = j; r->before = jdump(j);
1266 if (agent) {
1267 long u = parse_iso(jstrval(j, "updated_at"));
1268 if (r->existed && (u < 0 || now_epoch() - u > jlong(j, "ttl_seconds", SCENT_TTL))) r->dead = 1;
1269 } else sweep(j);
1270 return r;
1271}
1272/* Directory record path. "." is dirs/_root.json in both layouts. Layout 2 (crumb924 B2): a first component that
1273 * starts with '_' gets one more '_' (`_root/x` -> dirs/__root/x.json, `_root` -> dirs/__root.json), so no repository
1274 * directory can map onto dirs/_root.json or dirs/_root/ and every record name maps back to exactly one key directory
1275 * (dir_label). Layout 1 keeps its historical mapping (where `_root` shares the root record) byte for byte. */
1276static char *dir_path(const Plane *p, const char *rel) {
1277 if (!strcmp(rel, ".")) return pjoin(p->store, "dirs/_root.json");
1278 char *a = pjoin(p->store, "dirs"), *b, *c;
1279 if (p->layout == 2 && rel[0] == '_') { size_t bn = strlen(a) + strlen(rel) + 3; b = xmalloc(bn); xsnprintf(b, bn, "%s/_%s", a, rel); }
1280 else b = pjoin(a, rel);
1281 size_t cn = strlen(b) + 6; c = xmalloc(cn);
1282 xsnprintf(c, cn, "%s.json", b); free(a); free(b); return c;
1283}
1284/* the key directory a record name under dirs/ (without .json) stands for; NULL when no key maps to that name */
1285static char *dir_label(const Plane *p, const char *name) {
1286 if (!strcmp(name, "_root")) return xstrdup(".");
1287 if (p->layout != 2 || name[0] != '_') return xstrdup(name);
1288 return name[1] == '_' ? xstrdup(name + 1) : NULL;
1289}
1290static Rec *dir_rec(Txn *t, const char *rel) { return rec_load(t, dir_path(t->p, rel), 0, rel); }
1291static char *agent_path(const Plane *p, const char *agent) {
1292 char *n = xstrdup(agent); /* layout 1: legacy sanitising (aliases possible); layout 2: the validated id verbatim */
1293 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 = '_';
1294 char *a = pjoin(p->store, "agents"), *b = pjoin(a, n); size_t cn = strlen(b) + 6; char *c = xmalloc(cn);
1295 xsnprintf(c, cn, "%s.json", b); return c;
1296}
1297static Rec *agent_rec(Txn *t, const char *agent) { return rec_load(t, agent_path(t->p, agent), 1, NULL); }
1298/* Record names under dir, recursively, without opening any entry: lstat, so real subdirectories are walked and
1299 * symlinked directories are not (no escape from the store, no symlink loop). Every other name ending in .json is
1300 * returned whatever its type; read_bounded then refuses a non-regular one without opening it. A missing top
1301 * directory is empty state. Any other failure to list (permissions, I/O, a vanished subdirectory) is fatal in
1302 * enforcement mode and a stderr warning otherwise: it is never silently treated as empty. */
1303static void walk_fail(const char *what, const char *path) {
1304 if (g_enforce) die("STORE_UNREADABLE: cannot %s %s: %s; refusing (enforcement mode never treats unreadable state as empty)", what, path, strerror(errno));
1305 fprintf(stderr, "crumb: warning: cannot %s %s: %s; records under it are ignored (enforcement mode refuses this)\n", what, path, strerror(errno));
1306}
1307static void collect_json_at(const char *dir, char ***out, size_t *n, int top) {
1308 DIR *d = opendir(dir);
1309 if (!d) { if (!(top && errno == ENOENT)) walk_fail("open directory", dir); return; }
1310 struct dirent *e;
1311 for (;;) {
1312 errno = 0;
1313 if (!(e = readdir(d))) { if (errno) walk_fail("read directory", dir); break; }
1314 if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue;
1315 char *full = pjoin(dir, e->d_name); struct stat st;
1316 int ls = lstat(full, &st);
1317 if (ls != 0 && g_enforce) walk_fail("stat", full);
1318 if (ls == 0 && S_ISLNK(st.st_mode)) { /* never followed; in enforcement mode never skipped either (crumb924 B1) */
1319 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)");
1320 size_t l = strlen(e->d_name);
1321 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; }
1322 }
1323 if (ls == 0 && S_ISDIR(st.st_mode)) collect_json_at(full, out, n, 0);
1324 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; } }
1325 free(full);
1326 }
1327 closedir(d);
1328}
1329static void collect_json(const char *dir, char ***out, size_t *n) { collect_json_at(dir, out, n, 1); }
1330static void txn_prune(Txn *t) { /* load every record: expired entries drop out (written back on commit) */
1331 char **f = NULL; size_t n = 0;
1332 char *dd = pjoin(t->p->store, "dirs"), *ad = pjoin(t->p->store, "agents");
1333 collect_json(dd, &f, &n);
1334 size_t pl = strlen(dd) + 1;
1335 for (size_t i = 0; i < n; i++) {
1336 char *rel = xstrdup(f[i] + pl); rel[strlen(rel) - 5] = 0;
1337 char *label = dir_label(t->p, rel);
1338 if (!label) { /* layout 2: a '_' name no key maps to (an older layout-2 build wrote it, or it was planted) */
1339 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]);
1340 fprintf(stderr, "crumb: warning: %s is not a directory record name of layout 2; it is ignored (enforcement mode refuses this)\n", f[i]);
1341 free(rel); continue;
1342 }
1343 rec_load(t, f[i], 0, label);
1344 free(rel);
1345 }
1346 char **g = NULL; size_t m = 0;
1347 collect_json(ad, &g, &m);
1348 for (size_t i = 0; i < m; i++) rec_load(t, g[i], 1, NULL);
1349}
1350static void txn_end(Txn *t, int commit) {
1351 if (commit) for (size_t i = 0; i < t->n; i++) {
1352 Rec *r = t->r[i];
1353 if (r->dead) { if (unlink(r->path) == 0) { char *d = dir_of(r->path); fsync_dir(d); free(d); } continue; }
1354 char *now = jdump(r->root);
1355 if (strcmp(now, r->before)) durable_write(t->p->root, r->path, now);
1356 }
1357 if (t->fd >= 0) close(t->fd); /* releases the OS lock */
1358}
1359static J *jclone(const J *j) { char *s = jdump(j); J *c = jparse(s); free(s); return c ? c : jnew(JNULL); }
1360static void agent_set(Txn *t, const char *agent, const char *focus, long ttl) {
1361 Plane *p = t->p; char ts[21]; now_iso(ts);
1362 Rec *r = agent_rec(t, agent); r->dead = 0;
1363 J *e = jnew(JOBJ);
1364 jset(e, "agent", jstr(agent)); jset(e, "session", jstr(session_id(agent))); jset(e, "focus", jstr(focus)); jset(e, "dir", jstr(p->rel));
1365 jset(e, "worktree", jstr(p->top)); jset(e, "branch", jstr(p->branch)); jset(e, "head", jstr(p->head)); jset(e, "base", jstr(p->base));
1366 jset(e, "updated_at", jstr(ts)); jset(e, "ttl_seconds", jnum(ttl));
1367 r->root = e;
1368}
1369static int agent_has_lock(Txn *t, const char *agent) {
1370 for (size_t i = 0; i < t->n; i++) if (!t->r[i]->agent && has_lock_by(t->r[i]->root, agent)) return 1;
1371 return 0;
1372}
1373static void import_legacy(Txn *t) { /* one-time merge of this worktree's .crumb.local into the shared store */
1374 Plane *p = t->p;
1375 if (p->layout == 2) return; /* layout 2 never imports .crumb.local (plane_require warns when one is present) */
1376 char *lp = pjoin(p->abs, ".crumb.local"), *txt = read_local(lp);
1377 if (!txt) return;
1378 J *l = jparse(txt);
1379 if (!l || l->t != JOBJ) die("%s is not valid JSON; fix or move it aside", lp);
1380 Rec *dr = dir_rec(t, p->rel);
1381 J *mk = jarr_of(dr->root, "legacy_imported");
1382 for (size_t i = 0; i < mk->n; i++) if (mk->v[i]->t == JSTR && !strcmp(mk->v[i]->s, p->top)) return;
1383 sweep(l);
1384 J *lk = jget(l, "locks");
1385 if (lk && lk->t == JOBJ) for (size_t i = 0; i < lk->n; i++) {
1386 char *key = target_key(p, lk->k[i], p->rel), *td = key_dir(key);
1387 J *dst = jobj_of(dir_rec(t, td)->root, "locks");
1388 if (jget(dst, key)) continue; /* never override newer shared state */
1389 J *e = jclone(lk->v[i]);
1390 jset(e, "target", jstr(key)); jset(e, "worktree", jstr(p->top)); jset(e, "imported_from", jstr(p->top));
1391 jset(dst, key, e);
1392 }
1393 J *sc = jget(l, "active_scents");
1394 if (sc && sc->t == JOBJ) for (size_t i = 0; i < sc->n; i++) {
1395 Rec *ar = agent_rec(t, sc->k[i]);
1396 if (jget(ar->root, "updated_at") && !ar->dead) continue;
1397 J *e = jnew(JOBJ);
1398 jset(e, "agent", jstr(sc->k[i])); jset(e, "focus", jstr(jstrval(sc->v[i], "focus") ? jstrval(sc->v[i], "focus") : ""));
1399 jset(e, "dir", jstr(p->rel)); jset(e, "worktree", jstr(p->top)); jset(e, "branch", jstr("")); jset(e, "head", jstr("")); jset(e, "base", jstr(""));
1400 jset(e, "updated_at", jstr(jstrval(sc->v[i], "updated_at") ? jstrval(sc->v[i], "updated_at") : ""));
1401 jset(e, "ttl_seconds", jnum(jlong(sc->v[i], "ttl_seconds", SCENT_TTL))); jset(e, "imported_from", jstr(p->top));
1402 ar->root = e; ar->dead = 0;
1403 }
1404 J *wh = jget(l, "whispers");
1405 if (wh && wh->t == JARR) for (size_t i = 0; i < wh->n; i++) {
1406 J *e = jclone(wh->v[i]); jset(e, "imported_from", jstr(p->top)); jpush(jarr_of(dr->root, "whispers"), e);
1407 }
1408 J *hi = jget(l, "history");
1409 if (hi && hi->t == JARR && hi->n) {
1410 J *h = jarr_of(dr->root, "history");
1411 for (size_t i = 0; i < hi->n; i++) { J *e = jclone(hi->v[i]); jset(e, "imported_from", jstr(p->top)); jpush(h, e); }
1412 if (h->n > HISTORY_CAP) { size_t d = h->n - HISTORY_CAP; memmove(h->v, h->v + d, HISTORY_CAP * sizeof *h->v); h->n = HISTORY_CAP; }
1413 }
1414 jpush(mk, jstr(p->top));
1415}
1416static const char *sv(const J *o, const char *k) { const char *s = jstrval(o, k); return s ? s : ""; }
1417static void print_lock(const char *key, const J *e) {
1418 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"),
1419 jstrval(e, "imported_from") ? " imported from " : "", jstrval(e, "imported_from") ? jstrval(e, "imported_from") : "");
1420}
1421/* anc is k itself or one of its ancestor keys ("." is the whole repository) */
1422static int key_covers(const char *anc, const char *k) {
1423 if (!strcmp(anc, ".") || !strcmp(anc, k)) return 1;
1424 size_t n = strlen(anc);
1425 return !strncmp(k, anc, n) && k[n] == '/';
1426}
1427/* enforcement mode: an agent id names exactly one live session; a second session presenting it is refused (exit 2).
1428 * Live means a live heartbeat from another session, or a live lease of this id recorded by another session: the
1429 * heartbeat can expire long before the lease, and the lease's session decides who may renew or close it (crumb924 B3).
1430 * Every dir record is loaded and swept (txn_prune) before this runs, so the leases left are the live ones. */
1431static int agent_in_use(Txn *t, const char *agent) {
1432 if (!g_enforce) return 0;
1433 Rec *r = agent_rec(t, agent);
1434 const char *s = jstrval(r->root, "session");
1435 char *me = session_id(agent);
1436 if (r->existed && !r->dead && s && strcmp(s, me)) {
1437 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);
1438 free(me); return 1;
1439 }
1440 for (size_t i = 0; i < t->n; i++) if (!t->r[i]->agent) {
1441 J *lk = jget(t->r[i]->root, "locks");
1442 if (lk && lk->t == JOBJ) for (size_t k = 0; k < lk->n; k++) {
1443 const char *h = jstrval(lk->v[k], "holder"), *ls = jstrval(lk->v[k], "session");
1444 if (!h || strcmp(h, agent)) continue;
1445 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 */
1446 if (strcmp(ls, me)) {
1447 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 : "?");
1448 free(me); return 1;
1449 }
1450 }
1451 }
1452 free(me);
1453 return 0;
1454}
1455static int cmd_claim(const char *agent, const char *dir, const char *target, const char *intent, long ttl) {
1456 Plane *p = plane_resolve(dir);
1457 if (!p) return legacy_claim(agent, dir, target, intent, ttl);
1458 agent_require(p, agent);
1459 if (g_enforce && ttl <= 0) die("enforcement mode needs a positive ttl (got %ld)", ttl);
1460 char *key = target_key(p, target, p->rel), *td = key_dir(key);
1461 Txn *t = txn_begin(p, 1); txn_prune(t); import_legacy(t);
1462 if (agent_in_use(t, agent)) { txn_end(t, 0); return 2; }
1463 Rec *tr = dir_rec(t, td);
1464 J *cur = jget(jobj_of(tr->root, "locks"), key);
1465 if (cur) {
1466 const char *h = jstrval(cur, "holder");
1467 if (h && strcmp(h, agent)) {
1468 printf("BLOCKED %s held by %s on branch %s (worktree %s) since %s (%s)\n", key, h, sv(cur, "branch"), sv(cur, "worktree"), sv(cur, "acquired_at"), sv(cur, "intent"));
1469 txn_end(t, 1);
1470 return 2;
1471 }
1472 }
1473 /* no overlap: another agent's valid lease on an ancestor or a descendant of key blocks too (expired ones are pruned) */
1474 for (size_t i = 0; i < t->n; i++) if (!t->r[i]->agent) {
1475 J *lk = jget(t->r[i]->root, "locks");
1476 if (lk && lk->t == JOBJ) for (size_t k = 0; k < lk->n; k++) {
1477 const char *h = jstrval(lk->v[k], "holder");
1478 if (!h || !strcmp(h, agent) || !(key_covers(lk->k[k], key) || key_covers(key, lk->k[k]))) continue;
1479 J *o = lk->v[k];
1480 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]);
1481 txn_end(t, 1);
1482 return 2;
1483 }
1484 }
1485 char ts[21]; now_iso(ts);
1486 unsigned long long gen = gen_next(tr->root, tr->path, key, cur, agent);
1487 J *e = jnew(JOBJ);
1488 jset(e, "holder", jstr(agent)); jset(e, "session", jstr(session_id(agent))); jset(e, "target", jstr(key)); jset(e, "intent", jstr(intent));
1489 jset(e, "worktree", jstr(p->top)); jset(e, "branch", jstr(p->branch)); jset(e, "head", jstr(p->head)); jset(e, "base", jstr(p->base));
1490 jset(e, "acquired_at", jstr(ts)); jset(e, "ttl_seconds", jnum(ttl)); jset(e, "generation", jnum_u64(gen));
1491 jset(jobj_of(tr->root, "locks"), key, e);
1492 agent_set(t, agent, intent, SCENT_TTL > ttl ? SCENT_TTL : ttl);
1493 txn_end(t, 1);
1494 printf("CLAIMED %s in %s as %s on %s (ttl %lds) generation %llu\n", key, p->top, agent, p->branch, ttl, gen);
1495 return 0;
1496}
1497static int cmd_update(const char *agent, const char *dir, const char *focus, long ttl) {
1498 Plane *p = plane_resolve(dir);
1499 if (!p) return legacy_update(agent, dir, focus, ttl);
1500 agent_require(p, agent);
1501 if (g_enforce && ttl <= 0) die("enforcement mode needs a positive ttl (got %ld)", ttl); /* the strict agent record reader refuses ttl 0 */
1502 Txn *t = txn_begin(p, 1); txn_prune(t); import_legacy(t);
1503 if (agent_in_use(t, agent)) { txn_end(t, 0); return 2; }
1504 agent_set(t, agent, focus, ttl);
1505 txn_end(t, 1);
1506 printf("SCENT %s in %s: %s (ttl %lds)\n", agent, p->abs, focus, ttl);
1507 return 0;
1508}
1509static int cmd_whisper(const char *from, const char *dir, const char *to, const char *msg, const char *prio, const char *tf) {
1510 if (prio && *prio && strcmp(prio, "low") && strcmp(prio, "normal") && strcmp(prio, "high") && strcmp(prio, "critical")) die("priority must be low|normal|high|critical");
1511 Plane *p = plane_resolve(dir);
1512 if (!p) return legacy_whisper(from, dir, to, msg, prio, tf);
1513 agent_require(p, from);
1514 Txn *t = txn_begin(p, 1); txn_prune(t); import_legacy(t);
1515 whisper_add(dir_rec(t, p->rel)->root, from, to, msg, prio, tf);
1516 txn_end(t, 1);
1517 printf("WHISPER %s -> %s in %s\n", from, to && strcmp(to, "-") ? to : "(broadcast)", p->abs);
1518 return 0;
1519}
1520static int cmd_close(const char *agent, const char *dir, const char *target, const char *action, const char *msg) {
1521 static const char *ok[] = { "create", "modify", "delete", "audit", "test", "build", NULL };
1522 int good = 0; for (int i = 0; ok[i]; i++) if (!strcmp(ok[i], action)) good = 1;
1523 if (!good) die("action must be create|modify|delete|audit|test|build");
1524 Plane *p = plane_resolve(dir);
1525 if (!p) return legacy_close(agent, dir, target, action, msg);
1526 agent_require(p, agent);
1527 char *key = target_key(p, target, p->rel), *td = key_dir(key);
1528 Txn *t = txn_begin(p, 1); txn_prune(t); import_legacy(t);
1529 if (agent_in_use(t, agent)) { txn_end(t, 0); return 2; }
1530 Rec *tr = dir_rec(t, td);
1531 J *lk = jobj_of(tr->root, "locks"), *cur = jget(lk, key);
1532 const char *intent = "";
1533 if (cur) {
1534 const char *h = jstrval(cur, "holder");
1535 if (h && strcmp(h, agent)) { printf("REFUSED: %s is held by %s, not %s\n", key, h, agent); txn_end(t, 1); return 2; }
1536 if (jstrval(cur, "intent")) intent = jstrval(cur, "intent");
1537 }
1538 history_add(tr->root, agent, action, key, intent);
1539 if (cur) jdel(lk, key);
1540 if (!agent_has_lock(t, agent)) agent_rec(t, agent)->dead = 1;
1541 if (msg && *msg) whisper_add(tr->root, agent, NULL, msg, "normal", key);
1542 txn_end(t, 1);
1543 printf("CLOSED %s in %s by %s (%s)%s\n", key, p->top, agent, action, cur ? "" : " [no lock was held]");
1544 return 0;
1545}
1546/* check <agent> <dir> <target> [--generation N] (crumb924; the pre-write guard the session bridge calls).
1547 * Read-only: a shared fcntl lock on <root>/.lock (never created) for a consistent read; nothing is created, swept,
1548 * pruned or written. The leases on target and on every ancestor key (up to "." = the whole repository) are judged
1549 * with the strict schema in enforcement mode (lenient otherwise; malformed = exit 1 either way). Exit 0 only when a
1550 * valid lease on target or an ancestor is held by exactly <agent>, no other agent holds a valid lease on target or
1551 * an ancestor, and (when given) the nearest such lease has generation N and key K. Generations are counted per key,
1552 * so a bare number is ambiguous across keys (an ancestor lease can carry the same number later); a writer that
1553 * re-checks a token passes both --key and --generation, exactly as printed on the HELD line. Exit 2 otherwise. */
1554static int cmd_check(const char *agent, const char *dir, const char *target, int has_want, unsigned long long want, const char *want_key) {
1555 Plane *p = plane_resolve(dir);
1556 if (!p) die("check needs a git repository: %s", dir);
1557 agent_require(p, agent);
1558 char *key = target_key(p, target, p->rel);
1559 int fd = root_lock(p->root, 0);
1560 if (fd < 0 && store_used(p)) /* crumb924 B4: an initialized store without its lock is broken, not empty */
1561 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" : "");
1562 ident_gate(&p->id, p->root, 0); /* again under the lock: the root may have been swapped meanwhile */
1563 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);
1564 long now = now_epoch();
1565 const char *mine_key = NULL, *other_key = NULL, *exp_key = NULL; Lease mine, other, gone;
1566 memset(&mine, 0, sizeof mine); memset(&other, 0, sizeof other); memset(&gone, 0, sizeof gone);
1567 char *k = xstrdup(key), *loaded_path = NULL; J *rec = NULL;
1568 for (;;) {
1569 char *kd = key_dir(k), *path = dir_path(p, kd);
1570 if (!loaded_path || strcmp(loaded_path, path)) {
1571 check_real_parents(p->root, path);
1572 size_t len = 0; char *txt = read_bounded(path, MAX_RECORD_BYTES, &len);
1573 rec = txt && strlen(txt) == len ? jparse(txt) : NULL;
1574 if (txt && (!rec || rec->t != JOBJ)) die("%s is not valid JSON; fix or move it aside", path);
1575 if (rec && g_enforce) dir_record_strict(path, rec, kd);
1576 J *lk0 = jget(rec, "locks");
1577 if (lk0 && lk0->t != JOBJ) die("MALFORMED_RECORD: %s: \"locks\" is not an object; refusing", path);
1578 loaded_path = path;
1579 }
1580 J *e = jget(jget(rec, "locks"), k);
1581 if (e) {
1582 Lease l; const char *why = lease_parse(e, g_enforce, &l);
1583 if (why) malformed(loaded_path, k, why);
1584 int valid = now - l.acq <= l.ttl; /* now - acquired_at == ttl is still valid; ttl + 1 is expired */
1585 if (!valid) { if (!exp_key) { exp_key = xstrdup(k); gone = l; } }
1586 else if (!strcmp(l.holder, agent)) { if (!mine_key) { mine_key = xstrdup(k); mine = l; } }
1587 else if (!other_key) { other_key = xstrdup(k); other = l; }
1588 }
1589 if (!strcmp(k, ".")) break;
1590 char *up = strchr(k, '/') ? dir_of(k) : xstrdup(".");
1591 free(k); k = up; free(kd);
1592 }
1593 if (fd >= 0) close(fd);
1594 char ex[21];
1595 if (other_key) {
1596 iso_of(other.acq + other.ttl, ex);
1597 printf("REFUSED held-by %s %s key %s generation %llu expires %s\n", other.holder, key, other_key, other.gen, ex);
1598 return 2;
1599 }
1600 if (mine_key) {
1601 iso_of(mine.acq + mine.ttl, ex);
1602 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; }
1603 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; }
1604 printf("HELD %s by %s key %s generation %llu expires %s\n", key, agent, mine_key, mine.gen, ex);
1605 return 0;
1606 }
1607 if (exp_key) {
1608 iso_of(gone.acq + gone.ttl, ex);
1609 printf("REFUSED expired %s key %s holder %s generation %llu expired %s\n", key, exp_key, gone.holder, gone.gen, ex);
1610 return 2;
1611 }
1612 printf("REFUSED absent %s (no lease on it or any ancestor)\n", key);
1613 return 2;
1614}
1615static void print_agent(const J *e, const char *name) {
1616 long u = parse_iso(jstrval(e, "updated_at")), age = u < 0 ? -1 : now_epoch() - u;
1617 printf(" agent %-16s branch %s focus: %s heartbeat %lds ago [%s]\n", name, sv(e, "branch"), sv(e, "focus"), age, sv(e, "worktree"));
1618}
1619static int cmd_sniff(const char *agent, const char *dir) { /* SPEC 5.1 + RFC-0002 */
1620 Plane *p = plane_resolve(dir);
1621 if (!p) {
1622 int r = legacy_sniff(agent, dir);
1623 printf("shared coordination: none (not a git repository)\n");
1624 return r;
1625 }
1626 agent_require(p, agent);
1627 char *cp = pjoin(p->abs, ".crumb"), *txt = slurp(cp); J *c = txt ? jparse(txt) : NULL;
1628 printf("sniff %s as %s\n", p->abs, agent);
1629 if (c) {
1630 J *inv = jget(c, "invariants");
1631 printf(" .crumb: %s | %s\n", jstrval(c, "name") ? jstrval(c, "name") : "?", jstrval(c, "purpose") ? jstrval(c, "purpose") : "(legacy format)");
1632 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);
1633 } else printf(" no .crumb here\n");
1634 Txn *t = txn_begin(p, 0); txn_prune(t); import_legacy(t); /* read side: merged in memory, never saved */
1635 printf("shared coordination: ACTIVE\n common root: %s\n", p->root);
1636 if (p->layout == 2) printf(" repository: %s (layout 2, id from %s)\n", p->repo_id, p->repo_src);
1637 printf(" this worktree: %s [%s %s]\nACTIVE AGENTS\n", p->top, p->branch, p->head);
1638 int any = 0;
1639 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; }
1640 if (!any) printf(" (none)\n");
1641 printf("LOCKS\n"); any = 0;
1642 for (size_t i = 0; i < t->n; i++) if (!t->r[i]->agent) {
1643 J *lk = jget(t->r[i]->root, "locks");
1644 if (lk && lk->t == JOBJ) for (size_t k = 0; k < lk->n; k++) { print_lock(lk->k[k], lk->v[k]); any = 1; }
1645 }
1646 if (!any) printf(" (none)\n");
1647 printf("OTHER WORKTREES\n");
1648 char *wl = run_git_full(p->abs, "worktree list --porcelain"), *save = NULL;
1649 int shown = 0;
1650 for (char *ln = strtok_r(wl, "\n", &save); ln; ) {
1651 if (strncmp(ln, "worktree ", 9)) { ln = strtok_r(NULL, "\n", &save); continue; }
1652 char *wt = xstrdup(ln + 9), *br = xstrdup("(detached)");
1653 while ((ln = strtok_r(NULL, "\n", &save)) && strncmp(ln, "worktree ", 9)) if (!strncmp(ln, "branch refs/heads/", 18)) br = xstrdup(ln + 18);
1654 char rp[PATH_MAX];
1655 if (strcmp(wt, p->top) && !(realpath(wt, rp) && !strcmp(rp, p->top))) {
1656 printf(" %s [%s]: ", wt, br); shown = 1;
1657 int na = 0;
1658 for (size_t i = 0; i < t->n; i++) if (t->r[i]->agent && !t->r[i]->dead && !strcmp(sv(t->r[i]->root, "worktree"), wt)) { printf("%s%s", na++ ? ", " : "agent ", sv(t->r[i]->root, "agent")); }
1659 if (!na) printf("no agents");
1660 int nc = 0;
1661 for (size_t i = 0; i < t->n; i++) if (!t->r[i]->agent) {
1662 J *lk = jget(t->r[i]->root, "locks");
1663 if (lk && lk->t == JOBJ) for (size_t k = 0; k < lk->n; k++) {
1664 const char *kk = lk->k[k];
1665 int in = !strcmp(p->rel, ".") || (!strncmp(kk, p->rel, strlen(p->rel)) && kk[strlen(p->rel)] == '/');
1666 if (in && !strcmp(sv(lk->v[k], "worktree"), wt)) printf("%s%s", nc++ ? ", " : "; CONFLICT: ", kk);
1667 }
1668 }
1669 if (!nc) printf("; conflicts: none");
1670 printf("\n");
1671 }
1672 }
1673 if (!shown) printf(" (none)\n");
1674 printf("WHISPERS\n");
1675 J *wh = jget(dir_rec(t, p->rel)->root, "whispers"); any = 0;
1676 if (wh && wh->t == JARR) for (size_t i = 0; i < wh->n; i++) {
1677 const char *to = jstrval(wh->v[i], "to"), *from = jstrval(wh->v[i], "from");
1678 if (to && strcmp(to, agent)) continue;
1679 printf(" whisper %s -> %s: %s [%s%s%s]\n", from ? from : "?", to ? to : "all", sv(wh->v[i], "message"), sv(wh->v[i], "timestamp"), jstrval(wh->v[i], "priority") ? " " : "", sv(wh->v[i], "priority")); any = 1;
1680 }
1681 if (!any) printf(" (none)\n");
1682 txn_end(t, 0);
1683 return 0;
1684}
1685static int g_skip_local;
1686static int shared_list(Plane *p) { /* returns number of directories shown */
1687 Txn *t = txn_begin(p, 0); txn_prune(t);
1688 int n = 0;
1689 for (size_t i = 0; i < t->n; i++) if (!t->r[i]->agent) {
1690 const char *rel = sv(t->r[i]->root, "directory");
1691 if (strcmp(p->rel, ".") && strncmp(rel, p->rel, strlen(p->rel))) continue;
1692 J *lk = jget(t->r[i]->root, "locks"), *wh = jget(t->r[i]->root, "whispers");
1693 if (!((lk && lk->n) || (wh && wh->n))) continue;
1694 n++; printf("%s\n", rel);
1695 if (lk && lk->t == JOBJ) for (size_t k = 0; k < lk->n; k++) print_lock(lk->k[k], lk->v[k]);
1696 show_local(rel, t->r[i]->root, NULL);
1697 }
1698 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"));
1699 txn_end(t, 0);
1700 return n;
1701}
1702
1703/* ---------- tree walk ---------- */
1704static int skip_name(const char *n) {
1705 return n[0] == '.' || !strcmp(n, "target") || !strcmp(n, "node_modules") || !strcmp(n, "build") || !strcmp(n, "dist") || !strcmp(n, "vendor") || !strcmp(n, "evidence") || !strcmp(n, "__pycache__");
1706}
1707static int is_src(const char *n) {
1708 static const char *ext[] = { "c", "h", "cc", "cpp", "hpp", "S", "s", "rs", "mojo", "sh", NULL };
1709 const char *dot = strrchr(n, '.');
1710 if (!dot || dot == n) return !strcmp(n, "Makefile");
1711 for (int i = 0; ext[i]; i++) if (!strcmp(dot + 1, ext[i])) return 1;
1712 return 0;
1713}
1714static int cmpp(const void *a, const void *b) { return strcmp(*(char *const *)a, *(char *const *)b); }
1715static int nested_repo(const char *path) { char *g = pjoin(path, ".git"); struct stat st; int r = lstat(g, &st) == 0; free(g); return r; }
1716
1717typedef struct Node { char *path, *rel, *name; char **files; size_t nf; struct Node **sub; size_t ns; int src; } Node;
1718static char **g_ign; static size_t g_nign;
1719static void load_ignore(const char *root) { /* <root>/.crumbignore: one relative directory per line, '#' comments */
1720 char *p = pjoin(root, ".crumbignore"), *txt = slurp(p);
1721 if (!txt) return;
1722 for (char *l = strtok(txt, "\n"); l; l = strtok(NULL, "\n")) {
1723 size_t n = strlen(l); while (n && (l[n - 1] == '/' || l[n - 1] == '\r' || l[n - 1] == ' ')) l[--n] = 0;
1724 if (!n || l[0] == '#') continue;
1725 g_ign = xrealloc(g_ign, (g_nign + 1) * sizeof *g_ign); g_ign[g_nign++] = xstrdup(l);
1726 }
1727}
1728static int ignored_rel(const char *rel) {
1729 for (size_t i = 0; i < g_nign; i++) if (!strcmp(rel, g_ign[i])) return 1;
1730 return 0;
1731}
1732/* D10: a .crumbignore entry excludes that directory and everything below it from compile/verify/status.
1733 Its files still count toward the enclosing crumb's source tree (so a change there is still noticed upstairs),
1734 but no .crumb under it is ever read as a child or rewritten. Needed for trees guarded by immutability
1735 checks (omega evidence/, physics nvrm and m16). */
1736static int ignored_subtree(const char *rel) {
1737 for (size_t i = 0; i < g_nign; i++) {
1738 size_t n = strlen(g_ign[i]);
1739 if (!strncmp(rel, g_ign[i], n) && (rel[n] == 0 || rel[n] == '/')) return 1;
1740 }
1741 return 0;
1742}
1743static void reset_ignore(void) { for (size_t i = 0; i < g_nign; i++) free(g_ign[i]); free(g_ign); g_ign = NULL; g_nign = 0; }
1744
1745/* Traversal policy for compile/verify/status (issue sovereign-core#355). ONE function decides whether a directory
1746 * takes part, and find_crumbs, the children list and the tracked-crumb pass all call it, so the three commands cannot
1747 * disagree. A directory is excluded when it is (a) under a .crumbignore entry (D10), (b) a directory git itself
1748 * ignores and that holds no tracked file (build output such as target/ listed in .gitignore), or (c) a conventional
1749 * generated-output directory (target, node_modules, __pycache__) that holds no tracked file. A directory with any
1750 * tracked file is real source and always takes part (except via .crumbignore), so no integrity check is weakened. */
1751static char *shq(const char *s); static char *cap_cmd(const char *cmd, size_t *len); /* defined with the compiler below */
1752static char **g_trk; static size_t g_ntrk; /* tracked paths (git ls-files) */
1753static char **g_gign; static size_t g_ngign; /* wholly untracked+ignored directories, "dir/" */
1754static void policy_load(const char *top) {
1755 for (size_t i = 0; i < g_ntrk; i++) free(g_trk[i]);
1756 for (size_t i = 0; i < g_ngign; i++) free(g_gign[i]);
1757 free(g_trk); free(g_gign); g_trk = NULL; g_gign = NULL; g_ntrk = g_ngign = 0;
1758 char *tq = shq(top), cmd[PATH_MAX + 96]; size_t n; char *raw;
1759 snprintf(cmd, sizeof cmd, "git -C %s ls-files -z 2>/dev/null", tq);
1760 raw = cap_cmd(cmd, &n);
1761 for (char *s = raw; s < raw + n; s += strlen(s) + 1) { g_trk = xrealloc(g_trk, (g_ntrk + 1) * sizeof *g_trk); g_trk[g_ntrk++] = xstrdup(s); }
1762 snprintf(cmd, sizeof cmd, "git -C %s ls-files -z --others --ignored --exclude-standard --directory 2>/dev/null", tq);
1763 raw = cap_cmd(cmd, &n);
1764 for (char *s = raw; s < raw + n; s += strlen(s) + 1) {
1765 size_t l = strlen(s); if (!l || s[l - 1] != '/') continue; /* directories only */
1766 g_gign = xrealloc(g_gign, (g_ngign + 1) * sizeof *g_gign); g_gign[g_ngign++] = xstrdup(s);
1767 }
1768}
1769static int tracked_under(const char *rel) {
1770 size_t n = strlen(rel);
1771 for (size_t i = 0; i < g_ntrk; i++) if (!strncmp(g_trk[i], rel, n) && g_trk[i][n] == '/') return 1;
1772 return 0;
1773}
1774static int skip_generated_dir(const char *rel) { /* rel: repo-relative directory, no trailing slash */
1775 if (ignored_subtree(rel)) return 1;
1776 const char *b = strrchr(rel, '/'); b = b ? b + 1 : rel;
1777 if (!strcmp(b, ".git")) return 1;
1778 if (tracked_under(rel)) return 0;
1779 size_t n = strlen(rel);
1780 for (size_t i = 0; i < g_ngign; i++) if (strlen(g_gign[i]) == n + 1 && !strncmp(g_gign[i], rel, n)) return 1;
1781 return !strcmp(b, "target") || !strcmp(b, "node_modules") || !strcmp(b, "__pycache__");
1782}
1783static Node *scan(const char *path, const char *rel, int isroot) {
1784 Node *n = xmalloc(sizeof *n); memset(n, 0, sizeof *n);
1785 n->path = xstrdup(path); n->rel = xstrdup(rel); n->name = xstrdup(base_of(path));
1786 DIR *d = opendir(path);
1787 if (!d) return n;
1788 char **names = NULL; size_t cnt = 0, cap = 0; struct dirent *e;
1789 while ((e = readdir(d))) {
1790 if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue;
1791 if (cnt == cap) { cap = cap ? cap * 2 : 32; names = xrealloc(names, cap * sizeof *names); }
1792 names[cnt++] = xstrdup(e->d_name);
1793 }
1794 closedir(d);
1795 qsort(names, cnt, sizeof *names, cmpp);
1796 (void)isroot;
1797 for (size_t i = 0; i < cnt; i++) {
1798 char *full = pjoin(path, names[i]); struct stat st;
1799 if (lstat(full, &st) == 0) {
1800 if (S_ISDIR(st.st_mode)) {
1801 if (!skip_name(names[i]) && !nested_repo(full)) {
1802 char *r = !strcmp(rel, ".") ? xstrdup(names[i]) : pjoin(rel, names[i]);
1803 if (!ignored_rel(r)) {
1804 n->sub = xrealloc(n->sub, (n->ns + 1) * sizeof *n->sub);
1805 n->sub[n->ns++] = scan(full, r, 0);
1806 }
1807 }
1808 } else if (S_ISREG(st.st_mode) && strcmp(names[i], ".crumb") && strcmp(names[i], ".crumb.local") && names[i][0] != '.') {
1809 n->files = xrealloc(n->files, (n->nf + 1) * sizeof *n->files);
1810 n->files[n->nf++] = xstrdup(names[i]);
1811 if (is_src(names[i])) n->src = 1;
1812 }
1813 }
1814 free(full);
1815 }
1816 return n;
1817}
1818static int qualifies(const Node *n, int depth) { return depth <= 1 || n->nf > 0; }
1819
1820static char *run_git(const char *root, const char *args) {
1821 Buf q = {0}; bstr(&q, "'");
1822 for (const char *p = root; *p; p++) { if (*p == '\'') bstr(&q, "'\\''"); else bput(&q, p, 1); }
1823 bstr(&q, "'");
1824 size_t cn = q.n + strlen(args) + 32; char *cmd = xmalloc(cn);
1825 snprintf(cmd, cn, "git -C %s %s 2>/dev/null", q.p, args);
1826 FILE *f = popen(cmd, "r"); if (!f) return xstrdup("");
1827 char t[512]; size_t n = fread(t, 1, sizeof t - 1, f); t[n] = 0; pclose(f);
1828 while (n && (t[n - 1] == '\n' || t[n - 1] == '\r')) t[--n] = 0;
1829 return xstrdup(t);
1830}
1831
1832typedef struct { int created, updated, unchanged, legacy, skipped_bad; int dry, verbose; J *git; } Stats;
1833
1834static void seed_node(const Node *n, int depth, const char *anc_name, const char *anc_path, Stats *st) {
1835 int q = qualifies(n, depth);
1836 const char *next_name = anc_name, *next_path = anc_path;
1837 char *selfname = NULL, *nextpath = NULL;
1838 if (q) {
1839 char *cp = pjoin(n->path, ".crumb"), *txt = slurp(cp);
1840 J *c = txt ? jparse(txt) : NULL;
1841 const char *state = "unchanged";
1842 if (txt && (!c || c->t != JOBJ)) { st->skipped_bad++; printf("BAD-JSON %s (left untouched)\n", cp); goto after; }
1843 if (c && jget(c, "version") && !jget(c, "schema_version")) { /* pre-RFC Atlas/spark-crumbs format */
1844 st->legacy++; if (st->verbose) printf("legacy %s (left untouched)\n", cp); goto after;
1845 }
1846 char *before = c ? jdump(c) : xstrdup("");
1847 int fresh = !c; if (!c) c = jnew(JOBJ);
1848 char auto_purpose[PATH_MAX + 96];
1849 if (depth == 0) snprintf(auto_purpose, sizeof auto_purpose, "Repository root %s. Purpose not yet described by a human.", n->name);
1850 else snprintf(auto_purpose, sizeof auto_purpose, "Directory %s. Purpose not yet described by a human.", n->rel);
1851 J *oldext = jget(c, "extensions"), *seed = oldext ? jget(oldext, "seed") : NULL;
1852 const char *prev_auto = seed ? jstrval(seed, "purpose_auto") : NULL;
1853 if (!jget(c, "schema_version")) jset(c, "schema_version", jstr(SCHEMA));
1854 if (!jget(c, "name")) jset(c, "name", jstr(depth == 0 ? n->name : n->rel));
1855 if (!jget(c, "layer")) jset(c, "layer", jstr(depth == 0 ? "root" : n->rel));
1856 J *ext = NULL;
1857 const char *pur = jstrval(c, "purpose");
1858 if (!pur || (prev_auto && !strcmp(pur, prev_auto))) jset(c, "purpose", jstr(auto_purpose)); /* hand-written purpose is never touched */
1859 if (depth > 0 && !jget(c, "above")) {
1860 J *a = jnew(JOBJ); jset(a, "name", jstr(anc_name)); jset(a, "path", jstr(anc_path)); jset(c, "above", a);
1861 }
1862 if (n->ns) {
1863 J *b = jarr_of(c, "below");
1864 for (size_t i = 0; i < n->ns; i++) {
1865 int have = 0;
1866 for (size_t k = 0; k < b->n; k++) { const char *nm = b->v[k]->t == JSTR ? b->v[k]->s : jstrval(b->v[k], "name"); if (nm && !strcmp(nm, n->sub[i]->name)) have = 1; }
1867 if (!have) { J *e = jnew(JOBJ); jset(e, "name", jstr(n->sub[i]->name)); jset(e, "role", jstr("")); jpush(b, e); }
1868 }
1869 }
1870 ext = jobj_of(c, "extensions");
1871 J *ns = jnew(JOBJ); /* tool-owned block; everything else in the file is the humans' */
1872 jset(ns, "purpose_auto", jstr(auto_purpose));
1873 J *fl = jnew(JARR);
1874 for (size_t i = 0; i < n->nf && i < 50; i++) jpush(fl, jstr(n->files[i]));
1875 jset(ns, "files", fl);
1876 if (depth == 0 && st->git) jset(ns, "git", st->git);
1877 jset(ext, "seed", ns);
1878 if (!jget(ext, "owner_lane")) jset(ext, "owner_lane", jstr(""));
1879 char *after_txt = jdump(c);
1880 if (fresh) { st->created++; state = "created"; }
1881 else if (strcmp(before, after_txt)) { st->updated++; state = "updated"; }
1882 else st->unchanged++;
1883 if (strcmp(state, "unchanged")) { if (!st->dry) spit(cp, after_txt); if (st->verbose || st->dry) printf("%-8s %s\n", state, cp); }
1884 else if (st->verbose) printf("%-8s %s\n", state, cp);
1885 }
1886after:
1887 if (q) { selfname = depth == 0 ? n->name : n->rel; next_name = selfname; next_path = ".."; }
1888 else { nextpath = pjoin(anc_path, ".."); next_path = nextpath; }
1889 for (size_t i = 0; i < n->ns; i++) seed_node(n->sub[i], depth + 1, next_name, next_path, st);
1890}
1891static void ensure_gitignore(const char *root, Stats *st) {
1892 char *g = pjoin(root, ".gitignore"), *txt = slurp(g);
1893 if (!nested_repo(root)) return;
1894 if (txt) { for (char *l = strtok(xstrdup(txt), "\n"); l; l = strtok(NULL, "\n")) if (!strcmp(l, ".crumb.local") || !strcmp(l, "/.crumb.local") || !strcmp(l, "**/.crumb.local")) return; }
1895 printf("gitignore: adding .crumb.local to %s\n", g);
1896 if (st->dry) return;
1897 Buf b = {0}; bstr(&b, txt ? txt : "");
1898 if (b.n && b.p[b.n - 1] != '\n') bstr(&b, "\n");
1899 bstr(&b, ".crumb.local\n");
1900 spit(g, b.p);
1901}
1902static int cmd_seed(const char *root, int dry, int verbose) {
1903 char *r = absdir(root);
1904 Stats st; memset(&st, 0, sizeof st); st.dry = dry; st.verbose = verbose;
1905 if (nested_repo(r)) {
1906 J *g = jnew(JOBJ);
1907 jset(g, "remote", jstr(run_git(r, "remote get-url origin")));
1908 jset(g, "branch", jstr(run_git(r, "branch --show-current")));
1909 jset(g, "head", jstr(run_git(r, "rev-parse --short HEAD")));
1910 st.git = g;
1911 }
1912 load_ignore(r);
1913 Node *tree = scan(r, ".", 1);
1914 seed_node(tree, 0, tree->name, "..", &st);
1915 ensure_gitignore(r, &st);
1916 printf("seed %s%s: created %d, updated %d, unchanged %d, legacy-skipped %d, bad-json %d\n", r, dry ? " (dry run)" : "", st.created, st.updated, st.unchanged, st.legacy, st.skipped_bad);
1917 return 0;
1918}
1919static int cmd_create(const char *dir, const char *name, const char *purpose, const char *layer) {
1920 char *d = absdir(dir), *cp = pjoin(d, ".crumb");
1921 struct stat s; if (stat(cp, &s) == 0) { printf("EXISTS %s (use seed to refresh, edit by hand to change fields)\n", cp); return 2; }
1922 J *c = jnew(JOBJ);
1923 jset(c, "schema_version", jstr(SCHEMA)); jset(c, "name", jstr(name));
1924 if (layer && *layer) jset(c, "layer", jstr(layer));
1925 jset(c, "purpose", jstr(purpose));
1926 spit(cp, jdump(c));
1927 printf("CREATED %s\n", cp);
1928 return 0;
1929}
1930
1931typedef struct { int n_crumb, n_local, bad; } Tot;
1932static void walk_list(const char *path, const char *rel, int depth, int validate, Tot *t) {
1933 char *cp = pjoin(path, ".crumb"), *lp = pjoin(path, ".crumb.local"), *txt = slurp(cp);
1934 if (txt) {
1935 t->n_crumb++;
1936 J *c = jparse(txt);
1937 if (validate) {
1938 if (!c || c->t != JOBJ) { printf("INVALID %s: not a JSON object\n", cp); t->bad++; }
1939 else if (jget(c, "version") && !jget(c, "schema_version")) printf("LEGACY %s (pre-RFC format, not validated)\n", cp);
1940 else {
1941 const char *sv = jstrval(c, "schema_version");
1942 if (!sv || strcmp(sv, SCHEMA) || !jstrval(c, "name") || !jstrval(c, "purpose")) { printf("INVALID %s: needs schema_version \"%s\", name, purpose\n", cp, SCHEMA); t->bad++; }
1943 }
1944 }
1945 }
1946 if (!validate && !g_skip_local && read_local(lp)) {
1947 Local l = local_open(path); /* read side: sweep applied in memory, never saved */
1948 J *sc = jget(l.root, "active_scents"), *lk = jget(l.root, "locks"), *wh = jget(l.root, "whispers");
1949 if ((sc && sc->n) || (lk && lk->n) || (wh && wh->n)) { t->n_local++; printf("%s\n", rel); show_local(path, l.root, NULL); }
1950 }
1951 DIR *d = opendir(path); if (!d) return;
1952 char **names = NULL; size_t cnt = 0, cap = 0; struct dirent *e;
1953 while ((e = readdir(d))) {
1954 if (e->d_name[0] == '.' || skip_name(e->d_name)) continue;
1955 if (cnt == cap) { cap = cap ? cap * 2 : 32; names = xrealloc(names, cap * sizeof *names); }
1956 names[cnt++] = xstrdup(e->d_name);
1957 }
1958 closedir(d);
1959 qsort(names, cnt, sizeof *names, cmpp);
1960 for (size_t i = 0; i < cnt; i++) {
1961 char *full = pjoin(path, names[i]); struct stat st;
1962 if (lstat(full, &st) == 0 && S_ISDIR(st.st_mode) && !nested_repo(full)) {
1963 char *r = !strcmp(rel, ".") ? xstrdup(names[i]) : pjoin(rel, names[i]);
1964 walk_list(full, r, depth + 1, validate, t);
1965 }
1966 }
1967}
1968
1969
1970/* ---------- backfill: reconstruct history that crumbs would have recorded ---------- */
1971#include <ctype.h>
1972#include <glob.h>
1973#define LEDGER_CAP 20 /* entries (commits) kept in the committed .crumb extensions.provenance */
1974#define DOC_CAP 200 /* commits per directory in docs/crumbs/BACKFILL.md */
1975
1976typedef struct { char hash[41]; char *date, *author, *subj; long pr; } Commit;
1977typedef struct { char *rel; int *c; size_t n, cap; } DirAcc;
1978typedef struct { char *lane, *note, *ref; long pr; char *repo, *sha; int id; } LaneRef;
1979
1980static Commit *g_commits; static size_t g_nc, g_ncap;
1981static DirAcc **g_dirs; static size_t g_ndirs, g_dcap;
1982static LaneRef *g_lr; static size_t g_nlr, g_lrcap;
1983
1984static DirAcc *dir_acc(const char *rel) {
1985 for (size_t i = 0; i < g_ndirs; i++) if (!strcmp(g_dirs[i]->rel, rel)) return g_dirs[i];
1986 if (g_ndirs == g_dcap) { g_dcap = g_dcap ? g_dcap * 2 : 256; g_dirs = xrealloc(g_dirs, g_dcap * sizeof *g_dirs); }
1987 DirAcc *d = xmalloc(sizeof *d); memset(d, 0, sizeof *d); d->rel = xstrdup(rel);
1988 return g_dirs[g_ndirs++] = d;
1989}
1990static void dir_add(const char *rel, size_t ci) {
1991 DirAcc *d = dir_acc(rel);
1992 if (d->n && d->c[d->n - 1] == (int)ci) return;
1993 if (d->n == d->cap) { d->cap = d->cap ? d->cap * 2 : 8; d->c = xrealloc(d->c, d->cap * sizeof *d->c); }
1994 d->c[d->n++] = (int)ci;
1995}
1996static long pr_of(const char *subj) {
1997 const char *p = NULL, *q = subj;
1998 while ((q = strstr(q, "(#"))) { p = q; q += 2; }
1999 if (p && isdigit((unsigned char)p[2])) return atol(p + 2);
2000 if (!strncmp(subj, "Merge pull request #", 20)) return atol(subj + 20);
2001 return 0;
2002}
2003static void load_commits(const char *root, const char *since) {
2004 Buf q = {0}; bstr(&q, "'");
2005 for (const char *p = root; *p; p++) { if (*p == '\'') bstr(&q, "'\\''"); else bput(&q, p, 1); }
2006 bstr(&q, "'");
2007 Buf cmd = {0}; bstr(&cmd, "git -c core.quotepath=false -C "); bstr(&cmd, q.p);
2008 bstr(&cmd, " log --first-parent -m --name-only --format=%x01%H%x1f%cI%x1f%an%x1f%s");
2009 if (since && strchr(since, '\'')) die("--since must not contain a quote");
2010 if (since) { bstr(&cmd, " --since='"); bstr(&cmd, since); bstr(&cmd, "'"); }
2011 bstr(&cmd, " 2>/dev/null");
2012 FILE *f = popen(cmd.p, "r"); if (!f) return;
2013 char *line = NULL; size_t lc = 0; ssize_t len; long cur = -1;
2014 while ((len = getline(&line, &lc, f)) > 0) {
2015 while (len && (line[len - 1] == '\n' || line[len - 1] == '\r')) line[--len] = 0;
2016 if (line[0] == 1) {
2017 cur = -1;
2018 if (g_nc == g_ncap) { g_ncap = g_ncap ? g_ncap * 2 : 256; g_commits = xrealloc(g_commits, g_ncap * sizeof *g_commits); }
2019 Commit *c = &g_commits[g_nc]; memset(c, 0, sizeof *c);
2020 char *h = line + 1, *d = strchr(h, 31); if (!d) continue; *d++ = 0;
2021 char *a = strchr(d, 31); if (!a) continue; *a++ = 0;
2022 char *s = strchr(a, 31); if (!s) continue; *s++ = 0;
2023 snprintf(c->hash, sizeof c->hash, "%s", h);
2024 c->date = xstrdup(d); c->author = xstrdup(a); c->subj = xstrdup(s); c->pr = pr_of(s);
2025 cur = (long)g_nc++;
2026 } else if (len && cur >= 0) {
2027 char *dir = xstrdup(line);
2028 for (;;) { /* every ancestor directory of the file, root last */
2029 char *sl = strrchr(dir, '/');
2030 if (!sl) { dir_add(".", (size_t)cur); break; }
2031 *sl = 0; dir_add(dir, (size_t)cur);
2032 }
2033 free(dir);
2034 }
2035 }
2036 pclose(f); free(line);
2037}
2038static const char *repo_alias(const char *tok, size_t n) {
2039 static const struct { const char *a, *full; } al[] = { {"omega","omega"}, {"aienos","aienos"}, {"arch","aien-architecture"}, {"aien-architecture","aien-architecture"}, {"physics","physics"}, {NULL,NULL} };
2040 for (int i = 0; al[i].a; i++) if (strlen(al[i].a) == n && !strncmp(tok, al[i].a, n)) return al[i].full;
2041 return NULL;
2042}
2043static void lr_add(const char *lane, const char *note, const char *ref, long pr, const char *repo, const char *sha, int id) {
2044 if (g_nlr == g_lrcap) { g_lrcap = g_lrcap ? g_lrcap * 2 : 128; g_lr = xrealloc(g_lr, g_lrcap * sizeof *g_lr); }
2045 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;
2046}
2047static void parse_lane_file(const char *path) {
2048 int lfd = crumb_open_follow(path, O_RDONLY, 0); if (lfd < 0) return; /* the operator's own report (may be a link) */
2049 FILE *f = fdopen(lfd, "r"); if (!f) { close(lfd); return; }
2050 const char *bn = base_of(path), *fl = strstr(bn, "lane"); char filelane[24] = "";
2051 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; }
2052 char *line = NULL; size_t lc = 0; ssize_t len; static int idc = 0; int id;
2053 while ((len = getline(&line, &lc, f)) > 0) {
2054 while (len && (line[len - 1] == '\n' || line[len - 1] == '\r')) line[--len] = 0;
2055 char lane[24] = ""; const char *L = strstr(line, "Lane ");
2056 if (L && isdigit((unsigned char)L[5])) { int k = 0; const char *p = L + 5; while (isdigit((unsigned char)*p) && k < 8) lane[k++] = *p++; lane[k] = 0; }
2057 if (!lane[0]) snprintf(lane, sizeof lane, "%s", filelane);
2058 if (!lane[0]) continue;
2059 char lname[32]; snprintf(lname, sizeof lname, "lane%s", lane);
2060 char note[200]; const char *s = line; while (*s == '-' || *s == ' ' || *s == '*') s++;
2061 snprintf(note, sizeof note, "%s", s);
2062 id = ++idc;
2063 for (const char *p = line; *p; p++) {
2064 if (*p == '#' && isdigit((unsigned char)p[1]) && p > line) { /* explicit repo#N only; bare #N is ambiguous */
2065 const char *e = p; if (e > line + 1 && e[-1] == ' ') e--; const char *rp = e;
2066 while (e > line && (isalnum((unsigned char)e[-1]) || e[-1] == '-')) e--;
2067 const char *full = repo_alias(e, (size_t)(rp - e));
2068 if (full) lr_add(lname, note, bn, atol(p + 1), full, NULL, id);
2069 }
2070 if (isxdigit((unsigned char)*p) && (p == line || !isalnum((unsigned char)p[-1]))) {
2071 const char *e = p; int dig = 0, let = 0;
2072 while (isxdigit((unsigned char)*e) && !isupper((unsigned char)*e)) { if (isdigit((unsigned char)*e)) dig = 1; else let = 1; e++; }
2073 if (e == p) e = p + 1;
2074 size_t n = (size_t)(e - p);
2075 if (!isalnum((unsigned char)*e) && n >= 7 && n <= 40 && dig && let) { char sh[41]; memcpy(sh, p, n); sh[n] = 0; lr_add(lname, note, bn, 0, NULL, sh, id); }
2076 p = e - 1;
2077 }
2078 }
2079 }
2080 fclose(f); free(line);
2081}
2082static void load_lane_reports(const char *home) {
2083 char pat[PATH_MAX]; glob_t g;
2084 snprintf(pat, sizeof pat, "%s/handoffs/2026-10-01-push-lane*-report.md", home);
2085 if (!glob(pat, 0, NULL, &g)) { for (size_t i = 0; i < g.gl_pathc; i++) parse_lane_file(g.gl_pathv[i]); globfree(&g); }
2086 snprintf(pat, sizeof pat, "%s/handoffs/2026-10-01-next-major-push-orchestrator.md", home);
2087 parse_lane_file(pat);
2088}
2089static int lr_matches(const LaneRef *r, const Commit *c, const char *repo) {
2090 if (r->sha) return !strncmp(c->hash, r->sha, strlen(r->sha));
2091 return r->pr && c->pr == r->pr && r->repo && !strcmp(r->repo, repo);
2092}
2093static J *git_entry(const Commit *c) {
2094 J *e = jnew(JOBJ); char sh[8]; memcpy(sh, c->hash, 7); sh[7] = 0;
2095 jset(e, "source", jstr("backfill-git")); jset(e, "sha", jstr(sh)); jset(e, "timestamp", jstr(c->date));
2096 jset(e, "author", jstr(c->author)); jset(e, "subject", jstr(c->subj));
2097 if (c->pr) jset(e, "pr", jnum(c->pr));
2098 return e;
2099}
2100static J *lane_entry(const LaneRef *r, const Commit *c) {
2101 J *e = jnew(JOBJ); char sh[8]; memcpy(sh, c->hash, 7); sh[7] = 0;
2102 jset(e, "source", jstr("backfill-lane-report")); jset(e, "lane", jstr(r->lane)); jset(e, "sha", jstr(sh));
2103 if (c->pr) jset(e, "pr", jnum(c->pr));
2104 jset(e, "note", jstr(r->note)); jset(e, "ref", jstr(r->ref));
2105 return e;
2106}
2107static void mkdir_p(const char *path) {
2108 char *p = xstrdup(path);
2109 for (char *s = p + 1; *s; s++) if (*s == '/') { *s = 0; mkdir(p, 0777); *s = '/'; }
2110 mkdir(p, 0777); free(p);
2111}
2112typedef struct { Buf doc; int dirs, updated, unchanged, git_entries, lane_entries, truncated_dirs; } BfStats;
2113
2114static void backfill_node(const Node *n, int depth, const char *repo, BfStats *st, int dry) {
2115 if (qualifies(n, depth)) {
2116 char *cp = pjoin(n->path, ".crumb"), *txt = slurp(cp);
2117 J *c = txt ? jparse(txt) : NULL;
2118 if (c && c->t == JOBJ && jget(c, "schema_version")) {
2119 DirAcc *d = NULL;
2120 for (size_t i = 0; i < g_ndirs; i++) if (!strcmp(g_dirs[i]->rel, n->rel)) d = g_dirs[i];
2121 char *before = jdump(c);
2122 J *ext = jget(c, "extensions"), *led = jnew(JARR), *prov = jnew(JOBJ);
2123 if (!ext || ext->t != JOBJ) ext = jobj_of(c, "extensions");
2124 size_t total = d ? d->n : 0; int doc_lines = 0;
2125 Buf sec = {0}; bstr(&sec, "");
2126 for (size_t k = 0; d && k < d->n && k < DOC_CAP; k++) {
2127 const Commit *cm = &g_commits[d->c[k]];
2128 if (k < LEDGER_CAP) { jpush(led, git_entry(cm)); st->git_entries++; }
2129 char ln[700]; snprintf(ln, sizeof ln, "- %.10s %.7s%s%s %s: %s [backfill-git]\n", cm->date, cm->hash, cm->pr ? " #" : "", "", cm->author, cm->subj);
2130 if (cm->pr) snprintf(ln, sizeof ln, "- %.10s %.7s #%ld %s: %s [backfill-git]\n", cm->date, cm->hash, cm->pr, cm->author, cm->subj);
2131 bstr(&sec, ln); doc_lines++;
2132 for (size_t r = 0; r < g_nlr; r++) {
2133 if (!lr_matches(&g_lr[r], cm, repo)) continue;
2134 int dup = 0; for (size_t r2 = 0; r2 < r; r2++) if (g_lr[r2].id == g_lr[r].id && lr_matches(&g_lr[r2], cm, repo)) dup = 1;
2135 if (dup) continue;
2136 if (k < LEDGER_CAP) { jpush(led, lane_entry(&g_lr[r], cm)); st->lane_entries++; }
2137 snprintf(ln, sizeof ln, " - %s (%s): %.160s [backfill-lane-report]\n", g_lr[r].lane, g_lr[r].ref, g_lr[r].note);
2138 bstr(&sec, ln);
2139 }
2140 }
2141 jset(prov, "source", jstr("backfill"));
2142 jset(prov, "total_commits", jnum((long)total));
2143 jset(prov, "ledger_cap", jnum(LEDGER_CAP));
2144 jset(prov, "entries", led);
2145 if (total > DOC_CAP) st->truncated_dirs++;
2146 if (total) jset(ext, "provenance", prov); else jdel(ext, "provenance");
2147 if (doc_lines) {
2148 char hd[PATH_MAX + 64]; snprintf(hd, sizeof hd, "\n## %s\n\n%zu commit(s) touched this tree%s\n\n", n->rel, total, total > DOC_CAP ? "; showing newest 200 (older truncated)" : "");
2149 bstr(&st->doc, hd); bstr(&st->doc, sec.p);
2150 }
2151 st->dirs++;
2152 char *after = jdump(c);
2153 if (strcmp(before, after)) { st->updated++; if (!dry) spit(cp, after); } else st->unchanged++;
2154 }
2155 }
2156 for (size_t i = 0; i < n->ns; i++) backfill_node(n->sub[i], depth + 1, repo, st, dry);
2157}
2158static int cmd_backfill(const char *root, const char *since, int dry) {
2159 char *r = absdir(root);
2160 char *home = getenv("HOME"); home = home ? canon_dotdot(home) : xstrdup("");
2161 load_ignore(r);
2162 Node *tree = scan(r, ".", 1);
2163 char *remote = run_git(r, "remote get-url origin"), *repo = xstrdup(base_of(remote));
2164 size_t rl = strlen(repo); if (rl > 4 && !strcmp(repo + rl - 4, ".git")) repo[rl - 4] = 0;
2165 if (!nested_repo(r)) { /* not a repo: only lane reports, recorded on the root directory */
2166 load_lane_reports(home);
2167 char *cp = pjoin(r, ".crumb"), *txt = slurp(cp); J *c = txt ? jparse(txt) : NULL;
2168 if (!c || !jget(c, "schema_version")) { printf("backfill %s: no spec-format .crumb at root (run seed or create first)\n", r); return 1; }
2169 char *before = jdump(c); J *ext = jobj_of(c, "extensions"), *prov = jnew(JOBJ), *led = jnew(JARR);
2170 glob_t g; char pat[PATH_MAX]; snprintf(pat, sizeof pat, "%s/2026-10-01-push-lane*-report.md", r);
2171 int cnt = 0;
2172 if (!glob(pat, 0, NULL, &g)) for (size_t i = 0; i < g.gl_pathc; i++) {
2173 struct stat s; if (stat(g.gl_pathv[i], &s)) continue;
2174 const char *bn = base_of(g.gl_pathv[i]), *l = strstr(bn, "lane"); char lane[32]; snprintf(lane, sizeof lane, "lane%d", l ? atoi(l + 4) : 0);
2175 char ts[21]; struct tm tm; gmtime_r(&s.st_mtime, &tm); strftime(ts, sizeof ts, "%Y-%m-%dT%H:%M:%SZ", &tm);
2176 J *e = jnew(JOBJ); jset(e, "source", jstr("backfill-lane-report")); jset(e, "lane", jstr(lane)); jset(e, "ref", jstr(bn)); jset(e, "timestamp", jstr(ts));
2177 jpush(led, e); cnt++;
2178 }
2179 jset(prov, "source", jstr("backfill")); jset(prov, "entries", led); jset(ext, "provenance", prov);
2180 char *after = jdump(c);
2181 if (strcmp(before, after) && !dry) spit(cp, after);
2182 printf("backfill %s (not a git repo): %d lane report(s) recorded, %s\n", r, cnt, strcmp(before, after) ? "changed" : "unchanged");
2183 return 0;
2184 }
2185 load_commits(r, since);
2186 load_lane_reports(home);
2187 BfStats st; memset(&st, 0, sizeof st);
2188 Buf hd = {0}; bstr(&hd, "# Crumb backfill (generated by `crumb backfill`, do not edit by hand)\n\nHistory that crumbs would have recorded, reconstructed from git first-parent history and from the 2026-10-01 lane reports. Every entry is marked `backfill-git` or `backfill-lane-report`: none of it is a live whisper. A commit is listed under every directory it touched, newest first, up to 200 per directory. Lane entries are report lines that mention a commit or PR (mentions, not verified authorship); they attach only where a report names `<repo>#<PR>` or a commit SHA that exists here.\n");
2189 st.doc = hd;
2190 backfill_node(tree, 0, repo, &st, dry);
2191 char *docp = pjoin(r, "docs/crumbs/BACKFILL.md");
2192 char *old = slurp(docp);
2193 if (!old || strcmp(old, st.doc.p)) { if (!dry) { char *dd = pjoin(r, "docs/crumbs"); mkdir_p(dd); spit(docp, st.doc.p); } printf("BACKFILL.md: %s (%zu bytes)\n", old ? "updated" : "created", st.doc.n); }
2194 else printf("BACKFILL.md: unchanged\n");
2195 printf("backfill %s (%s, %zu commits%s): %d crumb dirs, updated %d, unchanged %d, ledger git entries %d, lane entries %d, dirs truncated in doc %d\n", r, repo, g_nc, since ? ", since given" : "", st.dirs, st.updated, st.unchanged, st.git_entries, st.lane_entries, st.truncated_dirs);
2196 return 0;
2197}
2198static void usage(void);
2199/* ---------- RFC-0002 section 7: crumb explain ---------- */
2200#define EXPL_COMMITS 10
2201#define EXPL_WHISPERS 5
2202static void print_strs(const char *label, const J *a, int max) { /* array of strings, or a single string */
2203 if (!a) return;
2204 if (a->t == JSTR) { printf(" %s: %s\n", label, a->s); return; }
2205 if (a->t != JARR) return;
2206 for (size_t i = 0; i < a->n && (int)i < max; i++) {
2207 if (a->v[i]->t == JSTR) printf(" %s: %s\n", label, a->v[i]->s);
2208 else { char *d = jdump(a->v[i]); d[strcspn(d, "\n")] = 0; printf(" %s: %s\n", label, d); }
2209 }
2210}
2211static J *load_crumb(const char *dir) { char *cp = pjoin(dir, ".crumb"), *txt = slurp(cp); J *c = txt ? jparse(txt) : NULL; return c && c->t == JOBJ ? c : NULL; }
2212/* does a continuation path entry (e.g. "tools/crumb/", "repo tools/crumb/.crumb") mention rel? */
2213static int path_mentions(const char *entry, const char *rel) {
2214 if (!strcmp(rel, ".")) return 1;
2215 size_t rl = strlen(rel);
2216 for (const char *s = entry; (s = strstr(s, rel)); s++) {
2217 int before = s == entry || s[-1] == ' ' || s[-1] == '/' || s[-1] == '"';
2218 char a = s[rl];
2219 int after = !a || a == '/' || a == ' ' || a == '"';
2220 if (before && after) return 1;
2221 }
2222 /* entry is an ancestor of rel (owner of the parent directory) */
2223 size_t el = strlen(entry);
2224 while (el && entry[el - 1] == '/') el--;
2225 return el > 0 && el < rl && !strncmp(entry, rel, el) && rel[el] == '/';
2226}
2227static int cont_matches(const J *c, const char *rel) {
2228 J *co = jget(c, "coordination");
2229 static const char *keys[] = { "scope", "owned", "owned_paths", NULL };
2230 if (!co || co->t != JOBJ) return 0;
2231 for (int k = 0; keys[k]; k++) {
2232 J *a = jget(co, keys[k]);
2233 if (a && a->t == JARR) for (size_t i = 0; i < a->n; i++) if (a->v[i]->t == JSTR && path_mentions(a->v[i]->s, rel)) return 1;
2234 }
2235 return 0;
2236}
2237static const char *cont_when(const J *c) {
2238 J *id = jget(c, "identity");
2239 const char *s = id ? jstrval(id, "sealed_at") : NULL;
2240 if (!s && id) s = jstrval(id, "created_at");
2241 return s ? s : "";
2242}
2243static char *shq(const char *s);
2244static int cmd_explain(const char *target) {
2245 char r[PATH_MAX];
2246 if (!realpath(target, r)) die("no such file or directory: %s", target);
2247 struct stat st; if (stat(r, &st)) die("cannot stat %s", target);
2248 char *abs = xstrdup(r), *dir = S_ISDIR(st.st_mode) ? xstrdup(r) : dir_of(r);
2249 Plane *p = plane_resolve(dir);
2250 const char *env = getenv("CRUMB_COORD_ROOT");
2251 char *top = p ? p->top : NULL, *rel = NULL;
2252 if (p) {
2253 size_t tl = strlen(top);
2254 rel = abs[tl] ? xstrdup(abs + tl + 1) : xstrdup(".");
2255 } else rel = xstrdup(base_of(abs));
2256 char *store = p ? p->store : (env && *env ? env_store(canon_dotdot(env)) : NULL); /* no repository: env-only identity */
2257 printf("EXPLAIN %s\n repository path: %s\n", abs, rel);
2258
2259 /* 1. nearest .crumb */
2260 printf("== NEAREST CRUMB ==\n");
2261 char *d = xstrdup(dir), *nearest = NULL; J *nc = NULL;
2262 for (;;) {
2263 if ((nc = load_crumb(d))) { nearest = xstrdup(d); break; }
2264 if (top && !strcmp(d, top)) break;
2265 char *up = dir_of(d); if (!strcmp(up, d) || !strcmp(up, ".")) break;
2266 if (!*up) { free(up); up = xstrdup("/"); if (!strcmp(d, "/")) break; }
2267 free(d); d = up;
2268 }
2269 if (nc) {
2270 printf(" file: %s/.crumb\n name: %s\n layer: %s\n purpose: %s\n", nearest, sv(nc, "name"), sv(nc, "layer"), sv(nc, "purpose"));
2271 J *inv = jget(nc, "invariants"); if (inv) print_strs("invariant", inv, 50); else printf(" invariant: (none)\n");
2272 J *ex = jget(nc, "exports"); if (ex) print_strs("export", ex, 50); else printf(" export: (none)\n");
2273 J *rl = jget(nc, "related"); if (rl) print_strs("related", rl, 50); else printf(" related: (none)\n");
2274 } else printf(" (no .crumb found at or above this path)\n");
2275
2276 /* 2. inherited invariants */
2277 printf("== INHERITED INVARIANTS ==\n");
2278 int any = 0;
2279 if (nearest) {
2280 char *u = dir_of(nearest);
2281 while (strcmp(u, nearest) && strcmp(u, ".")) {
2282 if (top && strlen(u) < strlen(top)) break;
2283 J *pc = load_crumb(u);
2284 if (pc) { J *inv = jget(pc, "invariants"); if (inv && inv->t == JARR) for (size_t i = 0; i < inv->n; i++) if (inv->v[i]->t == JSTR) { printf(" from %s/.crumb: %s\n", u, inv->v[i]->s); any = 1; } }
2285 if (top && !strcmp(u, top)) break;
2286 char *nx = dir_of(u); if (!strcmp(nx, u)) break; u = nx;
2287 }
2288 }
2289 if (!any) printf(" (none)\n");
2290
2291 /* 3. shared coordination */
2292 printf("== SHARED COORDINATION ==\n");
2293 if (p) {
2294 Txn *t = txn_begin(p, 0); txn_prune(t);
2295 char *dr = !strcmp(rel, ".") ? xstrdup(".") : (S_ISDIR(st.st_mode) ? xstrdup(rel) : dir_of(rel));
2296 any = 0;
2297 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; }
2298 if (!any) printf(" agents: (none)\n");
2299 any = 0;
2300 for (size_t i = 0; i < t->n; i++) if (!t->r[i]->agent) {
2301 J *lk = jget(t->r[i]->root, "locks");
2302 if (lk && lk->t == JOBJ) for (size_t k = 0; k < lk->n; k++) {
2303 const char *kk = lk->k[k]; char *kd = key_dir(kk);
2304 if (!strcmp(dr, ".") || !strcmp(kd, dr) || path_mentions(kk, rel)) { print_lock(kk, lk->v[k]); any = 1; }
2305 }
2306 }
2307 if (!any) printf(" locks: (none)\n");
2308 J *wh = jget(dir_rec(t, dr)->root, "whispers"); any = 0;
2309 if (wh && wh->t == JARR) for (size_t i = wh->n > EXPL_WHISPERS ? wh->n - EXPL_WHISPERS : 0; i < wh->n; i++) {
2310 printf(" whisper %s -> %s: %s [%s]\n", sv(wh->v[i], "from"), jstrval(wh->v[i], "to") ? jstrval(wh->v[i], "to") : "all", sv(wh->v[i], "message"), sv(wh->v[i], "timestamp")); any = 1;
2311 }
2312 if (!any) printf(" whispers: (none)\n");
2313 txn_end(t, 0);
2314 } else if (store) printf(" coordination root %s (no repository)\n", store);
2315 else printf(" shared coordination: none (not a git repository)\n");
2316
2317 /* 4. commits */
2318 printf("== RECENT COMMITS ==\n");
2319 if (p) {
2320 char *quoted = shq(rel);
2321 size_t qlen = strlen(quoted) + 64;
2322 char *q = xmalloc(qlen);
2323 snprintf(q, qlen, "log --oneline -%d -- %s", EXPL_COMMITS, quoted);
2324 char *lg = run_git_full(top, q);
2325 free(q); free(quoted);
2326 if (*lg) { for (char *s = strtok(lg, "\n"); s; s = strtok(NULL, "\n")) printf(" %s\n", s); } else printf(" (no commits touch this path)\n");
2327 } else printf(" (not a git repository)\n");
2328 if (nc) {
2329 J *ex = jget(nc, "extensions"), *pv = ex && ex->t == JOBJ ? jget(ex, "provenance") : NULL, *en = pv && pv->t == JOBJ ? jget(pv, "entries") : NULL;
2330 if (en && en->t == JARR) for (size_t i = 0; i < en->n && i < EXPL_COMMITS; i++) {
2331 const char *sh = jstrval(en->v[i], "sha"); int dup = 0;
2332 for (size_t j = 0; sh && j < i; j++) if (!strcmp(sv(en->v[j], "sha"), sh)) dup = 1;
2333 if (sh && !dup) printf(" named in .crumb: %s %s\n", sh, sv(en->v[i], "subject"));
2334 }
2335 }
2336
2337 /* 5. evidence references */
2338 printf("== EVIDENCE REFERENCES ==\n");
2339 any = 0;
2340 if (nc) {
2341 J *ex = jget(nc, "extensions");
2342 if (ex && ex->t == JOBJ) {
2343 J *ev = jget(ex, "evidence");
2344 if (ev) { print_strs("crumb evidence", ev, 20); any = 1; }
2345 J *pv = jget(ex, "provenance"), *en = pv && pv->t == JOBJ ? jget(pv, "entries") : NULL;
2346 if (en && en->t == JARR) for (size_t i = 0; i < en->n && i < EXPL_COMMITS; i++) { long pr = jlong(en->v[i], "pr", 0); int dup = 0; for (size_t j = 0; j < i; j++) if (jlong(en->v[j], "pr", 0) == pr) dup = 1; if (pr && !dup) { printf(" crumb pr: #%ld (%s)\n", pr, sv(en->v[i], "sha")); any = 1; } }
2347 }
2348 }
2349 /* 6. continuations */
2350 J *best = NULL; char *bestf = NULL; int nmatch = 0;
2351 if (store) {
2352 char **f = NULL; size_t n = 0; char *cd = pjoin(store, "continuations");
2353 collect_json(cd, &f, &n);
2354 for (size_t i = 0; i < n; i++) {
2355 char *txt = read_bounded(f[i], MAX_RECORD_BYTES, NULL); J *c = txt ? jparse(txt) : NULL;
2356 if (g_enforce && (!c || c->t != JOBJ)) die("%s is not valid JSON; refusing (enforcement mode never skips unreadable state)", f[i]);
2357 if (!c || c->t != JOBJ || !jget(c, "identity") || !cont_matches(c, rel)) continue;
2358 nmatch++;
2359 J *ev = jget(c, "evidence");
2360 if (ev && ev->t == JOBJ) {
2361 static const char *ek[] = { "commits", "prs", "receipts", NULL };
2362 for (int k = 0; ek[k]; k++) { J *a = jget(ev, ek[k]); if (a && a->t == JARR) for (size_t j = 0; j < a->n && j < 10; j++) if (a->v[j]->t == JSTR) { printf(" continuation %s %s: %s\n", sv(jget(c, "identity"), "checkpoint_id"), ek[k], a->v[j]->s); any = 1; } }
2363 J *ts = jget(ev, "tests");
2364 if (ts && ts->t == JARR) for (size_t j = 0; j < ts->n && j < 10; j++) { printf(" continuation test: %s -> %s\n", sv(ts->v[j], "name"), sv(ts->v[j], "result")); any = 1; }
2365 }
2366 if (!best || strcmp(cont_when(c), cont_when(best)) > 0) { best = c; bestf = f[i]; }
2367 }
2368 }
2369 if (!any) printf(" (none)\n");
2370 printf("== NEWEST CONTINUATION ==\n");
2371 if (!best) printf(" (none touches this path)\n");
2372 else {
2373 J *id = jget(best, "identity"), *st2 = jget(best, "state"), *items = st2 && st2->t == JOBJ ? jget(st2, "items") : st2;
2374 printf(" id: %s sealed: %s by: %s (%d matching, showing 1)\n file: %s\n reason: %s\n", sv(id, "checkpoint_id"), cont_when(best), sv(id, "created_by"), nmatch, bestf, sv(id, "reason"));
2375 J *rv = jget(best, "revalidation"); if (rv) printf(" revalidation: %s\n", sv(rv, "status"));
2376 if (items && items->t == JARR) for (size_t i = 0; i < items->n; i++) printf(" [%s] %s\n", sv(items->v[i], "tag"), sv(items->v[i], "claim"));
2377 }
2378 return 0;
2379}
2380
2381/* ---------- RFC-0002 section 7: checkpoint / resume (thin wrappers around cc.sh) ---------- */
2382static char *cc_path(void) {
2383 const char *e = getenv("CRUMB_CC");
2384 if (e && *e) return xstrdup(e);
2385 const char *h = getenv("HOME");
2386 if (!h || !*h) die("HOME is not set; set CRUMB_CC to the path of cc.sh");
2387 size_t n = strlen(h) + 64; char *s = xmalloc(n);
2388 xsnprintf(s, n, "%s/.claude/skills/checkpoint/scripts/cc.sh", h); return s;
2389}
2390static void cc_env(Plane *p) { /* records must land in <coordination root>/continuations (layout 2: the namespace's) */
2391 const char *env = getenv("CRUMB_COORD_ROOT");
2392 if (p && p->layout == 2) {
2393 char *cs = pjoin(p->store, "continuations");
2394 setenv("CRUMB_COORD_ROOT", p->root, 1); setenv("CC_STORE", cs, 1); setenv("CRUMB_REPO_ID", p->repo_id, 1);
2395 } else if (p) setenv("CRUMB_COORD_ROOT", p->store, 1);
2396 else if (!(env && *env)) die("no repository context: run inside a git checkout or set CRUMB_COORD_ROOT");
2397 else { /* a ".." in the root is resolved here (canon_dotdot), for this process and for cc.sh alike */
2398 char *rt = canon_dotdot(env), *st = env_store(rt);
2399 if (strcmp(rt, env)) setenv("CRUMB_COORD_ROOT", rt, 1);
2400 if (strcmp(st, rt)) { char *cs = pjoin(st, "continuations"); setenv("CC_STORE", cs, 1); }
2401 }
2402 char self[PATH_MAX]; ssize_t n = readlink("/proc/self/exe", self, sizeof self - 1);
2403 if (n > 0 && !getenv("CRUMB_BIN")) { self[n] = 0; setenv("CRUMB_BIN", self, 1); }
2404}
2405static char *cc_script(void) {
2406 char *cc = cc_path();
2407 if (access(cc, X_OK) != 0) die("cc.sh not found or not executable at %s (the checkpoint skill; set CRUMB_CC to override)", cc);
2408 return cc;
2409}
2410static char *shq(const char *s) { Buf q = {0}; bstr(&q, "'"); for (; *s; s++) { if (*s == '\'') bstr(&q, "'\\''"); else bput(&q, s, 1); } bstr(&q, "'"); return q.p; }
2411static int cmd_checkpoint(int a, char **v) {
2412 const char *agent = NULL, *reason = NULL, *seal = NULL;
2413 for (int i = 0; i < a; i++) {
2414 if (!strcmp(v[i], "--reason") && i + 1 < a) reason = v[++i];
2415 else if (!strcmp(v[i], "--seal") && i + 1 < a) seal = v[++i];
2416 else if (!agent && v[i][0] != '-') agent = v[i];
2417 else usage();
2418 }
2419 if (!agent && !seal) usage();
2420 Plane *p = plane_resolve("."); cc_env(p);
2421 char *cc = cc_script(); const char *ag = agent ? agent : (getenv("CC_AGENT") ? getenv("CC_AGENT") : "claude");
2422 setenv("CC_AGENT", ag, 1);
2423 if (seal) execl(cc, cc, "seal", seal, ag, (char *)NULL);
2424 else {
2425 char *top = p ? p->top : absdir(".");
2426 Buf cmd = {0}; char *q1 = shq(cc), *q2 = shq(agent), *q3 = shq(top);
2427 bstr(&cmd, q1); bstr(&cmd, " new "); bstr(&cmd, q2); bstr(&cmd, " "); bstr(&cmd, q3);
2428 FILE *f = popen(cmd.p, "r"); if (!f) die("cannot run %s", cc);
2429 char out[PATH_MAX + 2]; size_t n = fread(out, 1, sizeof out - 1, f); out[n] = 0;
2430 if (pclose(f) != 0 || !n) die("cc.sh new failed");
2431 out[strcspn(out, "\n")] = 0;
2432 if (reason) {
2433 Buf c2 = {0}; char *qr = shq(reason), *qo = shq(out);
2434 bstr(&c2, "tmp=$(mktemp) && jq --arg r "); bstr(&c2, qr); bstr(&c2, " '.identity.reason=$r' "); bstr(&c2, qo);
2435 bstr(&c2, " > \"$tmp\" && mv \"$tmp\" "); bstr(&c2, qo);
2436 if (system(c2.p) != 0) die("could not record the reason (jq missing?)");
2437 }
2438 printf("%s\n", out);
2439 fprintf(stderr, "fill in the record, then: crumb checkpoint --seal <id> %s\n", agent);
2440 return 0;
2441 }
2442 die("cannot exec %s: %s", cc, strerror(errno));
2443 return 1;
2444}
2445static int cmd_resume(const char *id) {
2446 Plane *p = plane_resolve("."); cc_env(p);
2447 char *cc = cc_script();
2448 execl(cc, cc, "resume", id, (char *)NULL);
2449 die("cannot exec %s: %s", cc, strerror(errno));
2450 return 1;
2451}
2452
2453/* decimal seconds, 0..MAX_TTL, nothing else (no sign, no spaces, no overflow): the writer accepts exactly what every
2454 * reader accepts (crumb924 B5; the strict reader refuses ttl_seconds above MAX_TTL, enforcement also refuses 0) */
2455static long ttl_arg(const char *s, long dflt) {
2456 if (!s) return dflt;
2457 long v = 0;
2458 for (const char *c = s; *c; c++) {
2459 if (*c < '0' || *c > '9' || v > (MAX_TTL - (*c - '0')) / 10) die("bad ttl: %s (expected 0..%ld seconds)", s, MAX_TTL);
2460 v = v * 10 + (*c - '0');
2461 }
2462 if (!*s) die("bad ttl: (empty) (expected 0..%ld seconds)", MAX_TTL);
2463 return v;
2464}
2465/* ---------- RFC-0003: Crumb Compiler (C port of crumb-compile.sh; design decisions D1-D9 there are binding) ----------
2466 * compile/verify/status: hand-authored kernel stays, everything structural is generated bottom-up into
2467 * .crumb extensions.generated with Merkle digests. Output is byte-identical to the shell reference. */
2468static char *xstrndup_(const char *s, size_t n) { char *p = xmalloc(n + 1); memcpy(p, s, n); p[n] = 0; return p; }
2469typedef struct { uint32_t h[8]; uint64_t len; unsigned char buf[64]; size_t nb; } Sha;
2470static const uint32_t K256[64] = {
2471 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,
2472 0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,
2473 0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,
2474 0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2 };
2475#define ROR(x, n) (((x) >> (n)) | ((x) << (32 - (n))))
2476static void sha_block(Sha *s, const unsigned char *p) {
2477 uint32_t w[64], a, b, c, d, e, f, g, h;
2478 for (int i = 0; i < 16; i++) w[i] = (uint32_t)p[4*i] << 24 | (uint32_t)p[4*i+1] << 16 | (uint32_t)p[4*i+2] << 8 | p[4*i+3];
2479 for (int i = 16; i < 64; i++) {
2480 uint32_t s0 = ROR(w[i-15], 7) ^ ROR(w[i-15], 18) ^ (w[i-15] >> 3), s1 = ROR(w[i-2], 17) ^ ROR(w[i-2], 19) ^ (w[i-2] >> 10);
2481 w[i] = w[i-16] + s0 + w[i-7] + s1;
2482 }
2483 a = s->h[0]; b = s->h[1]; c = s->h[2]; d = s->h[3]; e = s->h[4]; f = s->h[5]; g = s->h[6]; h = s->h[7];
2484 for (int i = 0; i < 64; i++) {
2485 uint32_t t1 = h + (ROR(e, 6) ^ ROR(e, 11) ^ ROR(e, 25)) + ((e & f) ^ (~e & g)) + K256[i] + w[i];
2486 uint32_t t2 = (ROR(a, 2) ^ ROR(a, 13) ^ ROR(a, 22)) + ((a & b) ^ (a & c) ^ (b & c));
2487 h = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2;
2488 }
2489 s->h[0] += a; s->h[1] += b; s->h[2] += c; s->h[3] += d; s->h[4] += e; s->h[5] += f; s->h[6] += g; s->h[7] += h;
2490}
2491static void sha_init(Sha *s) {
2492 static const uint32_t iv[8] = { 0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19 };
2493 memcpy(s->h, iv, sizeof iv); s->len = 0; s->nb = 0;
2494}
2495static void sha_add(Sha *s, const void *data, size_t n) {
2496 const unsigned char *p = data; s->len += n;
2497 while (n) {
2498 size_t k = 64 - s->nb; if (k > n) k = n;
2499 memcpy(s->buf + s->nb, p, k); s->nb += k; p += k; n -= k;
2500 if (s->nb == 64) { sha_block(s, s->buf); s->nb = 0; }
2501 }
2502}
2503static void sha_hex(Sha *s, char *out) { /* out: 65 bytes */
2504 uint64_t bits = s->len * 8; unsigned char pad = 0x80, z = 0, lb[8];
2505 sha_add(s, &pad, 1); while (s->nb != 56) sha_add(s, &z, 1);
2506 for (int i = 0; i < 8; i++) lb[i] = (unsigned char)(bits >> (56 - 8 * i));
2507 sha_add(s, lb, 8);
2508 for (int i = 0; i < 8; i++) snprintf(out + 8 * i, 9, "%08x", s->h[i]);
2509}
2510
2511static void jsort(J *j) { /* jq -S: object keys in codepoint (= UTF-8 byte) order, recursively */
2512 if (j->t == JARR) { for (size_t i = 0; i < j->n; i++) jsort(j->v[i]); return; }
2513 if (j->t != JOBJ) return;
2514 for (size_t i = 1; i < j->n; i++) { /* insertion sort on parallel arrays (stable, small) */
2515 char *k = j->k[i]; J *v = j->v[i]; size_t m = i;
2516 while (m > 0 && strcmp(j->k[m - 1], k) > 0) { j->k[m] = j->k[m - 1]; j->v[m] = j->v[m - 1]; m--; }
2517 j->k[m] = k; j->v[m] = v;
2518 }
2519 for (size_t i = 0; i < j->n; i++) jsort(j->v[i]);
2520}
2521static void jcompact(const J *j, Buf *b) { /* jq -c */
2522 switch (j->t) {
2523 case JARR: bput(b, "[", 1); for (size_t i = 0; i < j->n; i++) { if (i) bput(b, ",", 1); jcompact(j->v[i], b); } bput(b, "]", 1); break;
2524 case JOBJ: bput(b, "{", 1); for (size_t i = 0; i < j->n; i++) { if (i) bput(b, ",", 1); jescape(b, j->k[i]); bput(b, ":", 1); jcompact(j->v[i], b); } bput(b, "}", 1); break;
2525 default: jprint(j, b, 0);
2526 }
2527}
2528static char *jcompact_s(const J *j) { Buf b = {0}; bstr(&b, ""); jcompact(j, &b); return b.p; }
2529
2530static char *cap_cmd(const char *cmd, size_t *len) { /* all output bytes of a shell command, NUL-safe */
2531 FILE *f = popen(cmd, "r"); Buf b = {0}; bstr(&b, "");
2532 if (!f) { if (len) *len = 0; return b.p; }
2533 char t[8192]; size_t n;
2534 while ((n = fread(t, 1, sizeof t, f)) > 0) bput(&b, t, n);
2535 pclose(f); if (len) *len = b.n; return b.p;
2536}
2537static void chomp(char *s) { size_t n = strlen(s); while (n && s[n - 1] == '\n') s[--n] = 0; }
2538
2539typedef struct { char *blob, *path; } CFile;
2540static int cfcmp(const void *a, const void *b) { return strcmp(((const CFile *)a)->path, ((const CFile *)b)->path); }
2541typedef struct { char *dir, *dig; } DDig;
2542typedef struct { CFile *f; size_t nf; DDig *dd; size_t ndd, cdd; char *top; } Comp;
2543
2544static int is_crumb_name(const char *path) { /* D1: every .crumb and .crumb.local */
2545 const char *b = strrchr(path, '/'); b = b ? b + 1 : path;
2546 return !strcmp(b, ".crumb") || !strcmp(b, ".crumb.local");
2547}
2548static int is_evidence(const char *p) {
2549 size_t n = strlen(p);
2550 if (n >= 13 && !strcmp(p + n - 13, ".receipt.json")) return 1;
2551 static const char *w[] = { "evidence/", "receipts/", NULL };
2552 for (int k = 0; w[k]; k++) for (const char *s = p; (s = strstr(s, w[k])); s++) if (s == p || s[-1] == '/') return 1;
2553 return 0;
2554}
2555static void comp_load_files(Comp *c) { /* D2: tracked files of the working tree, blob ids via git hash-object */
2556 size_t n; char *raw;
2557 char *tq = shq(c->top), cmd[PATH_MAX + 64];
2558 snprintf(cmd, sizeof cmd, "git -C %s ls-files -z 2>/dev/null", tq);
2559 raw = cap_cmd(cmd, &n);
2560 Buf present = {0}; bstr(&present, ""); size_t np = 0; char **pp = NULL, *s = raw;
2561 while (s < raw + n) {
2562 size_t l = strlen(s);
2563 if (l && !is_crumb_name(s)) {
2564 char *full = pjoin(c->top, s); struct stat st;
2565 if (stat(full, &st) == 0 && S_ISREG(st.st_mode)) { pp = xrealloc(pp, (np + 1) * sizeof *pp); pp[np++] = xstrdup(s); bstr(&present, s); bput(&present, "\n", 1); }
2566 free(full);
2567 }
2568 s += l + 1;
2569 }
2570 c->nf = 0; c->f = NULL;
2571 if (np) {
2572 char tmpl[] = "/tmp/crumb-compile-XXXXXX"; int fd = mkstemp(tmpl);
2573 if (fd < 0) die("cannot create temp file");
2574 if (write(fd, present.p, present.n) != (ssize_t)present.n) die("temp write failed");
2575 close(fd);
2576 snprintf(cmd, sizeof cmd, "git -C %s hash-object --stdin-paths < %s 2>/dev/null", tq, tmpl);
2577 char *hs = cap_cmd(cmd, NULL); unlink(tmpl);
2578 char *sv2 = NULL, *ln = strtok_r(hs, "\n", &sv2);
2579 c->f = xmalloc(np * sizeof *c->f);
2580 for (size_t i = 0; i < np; i++) {
2581 if (!ln) die("git hash-object returned too few ids");
2582 c->f[i].blob = xstrdup(ln); c->f[i].path = pp[i]; ln = strtok_r(NULL, "\n", &sv2);
2583 }
2584 c->nf = np;
2585 qsort(c->f, c->nf, sizeof *c->f, cfcmp);
2586 }
2587}
2588static const char *dig_of(Comp *c, const char *dir) { for (size_t i = 0; i < c->ndd; i++) if (!strcmp(c->dd[i].dir, dir)) return c->dd[i].dig; return NULL; }
2589static void dig_set(Comp *c, const char *dir, const char *dig) {
2590 if (c->ndd == c->cdd) { c->cdd = c->cdd ? c->cdd * 2 : 16; c->dd = xrealloc(c->dd, c->cdd * sizeof *c->dd); }
2591 c->dd[c->ndd].dir = xstrdup(dir); c->dd[c->ndd++].dig = xstrdup(dig);
2592}
2593static size_t utf8_prefix(const char *s, int cps) { /* byte length of the first cps codepoints (jq .[0:n]) */
2594 size_t i = 0; int k = 0;
2595 while (s[i] && k < cps) { i++; while (((unsigned char)s[i] & 0xC0) == 0x80) i++; k++; }
2596 return i;
2597}
2598static int sstrcmp(const void *a, const void *b) { return strcmp(*(char *const *)a, *(char *const *)b); }
2599/* Children of a crumb directory = nearest crumbed descendants (D7 amendment). One traversal policy with find_crumbs. */
2600typedef struct { char *rel; char *name; } Kid; /* rel: repo-relative directory; name: path relative to the parent crumb dir */
2601static int kidcmp(const void *a, const void *b) { return strcmp(((const Kid *)a)->name, ((const Kid *)b)->name); }
2602static void collect_kids(Comp *c, const char *dir, const char *prefix, Kid **out, size_t *n, size_t *cap) {
2603 int root = !strcmp(dir, "."); char *dfull = root ? xstrdup(c->top) : pjoin(c->top, dir); DIR *dp = opendir(dfull);
2604 char **names = NULL; size_t nn = 0;
2605 if (dp) { struct dirent *e; while ((e = readdir(dp))) if (strcmp(e->d_name, ".") && strcmp(e->d_name, "..")) { names = xrealloc(names, (nn + 1) * sizeof *names); names[nn++] = xstrdup(e->d_name); } closedir(dp); }
2606 qsort(names, nn, sizeof *names, sstrcmp);
2607 for (size_t i = 0; i < nn; i++) {
2608 char *kd = root ? xstrdup(names[i]) : pjoin(dir, names[i]), *kf = pjoin(c->top, kd); struct stat st;
2609 if (lstat(kf, &st) || !S_ISDIR(st.st_mode) || skip_generated_dir(kd)) { free(kd); free(kf); continue; } /* D10 + #355 */
2610 char *kc = pjoin(kf, ".crumb"); struct stat sb; int has = !stat(kc, &sb) && S_ISREG(sb.st_mode);
2611 size_t pl = strlen(prefix), nl = strlen(names[i]); char *name = xmalloc(pl + nl + 2); memcpy(name, prefix, pl); memcpy(name + pl, names[i], nl + 1);
2612 if (has) {
2613 if (*n == *cap) { *cap = *cap ? *cap * 2 : 16; *out = xrealloc(*out, *cap * sizeof **out); }
2614 (*out)[*n].rel = kd; (*out)[(*n)++].name = name;
2615 } else { name[pl + nl] = '/'; name[pl + nl + 1] = 0; collect_kids(c, kd, name, out, n, cap); free(name); free(kd); }
2616 free(kf); free(kc);
2617 }
2618 free(names); free(dfull);
2619}
2620static J *comp_object(Comp *c, const char *d, char *dig_out) { /* the generated object, without stamps */
2621 int root = !strcmp(d, "."); size_t pl = root ? 0 : strlen(d) + 1;
2622 char pre[PATH_MAX]; if (!root) snprintf(pre, sizeof pre, "%s/", d); else pre[0] = 0;
2623 Sha st, ev; sha_init(&st); sha_init(&ev); long nfiles = 0, nev = 0; (void)pl;
2624 for (size_t i = 0; i < c->nf; i++) {
2625 if (!root && strncmp(c->f[i].path, pre, strlen(pre))) continue;
2626 sha_add(&st, c->f[i].blob, strlen(c->f[i].blob)); sha_add(&st, " ", 1); sha_add(&st, c->f[i].path, strlen(c->f[i].path)); sha_add(&st, "\n", 1);
2627 nfiles++;
2628 if (is_evidence(c->f[i].path)) { sha_add(&ev, c->f[i].blob, strlen(c->f[i].blob)); sha_add(&ev, "\n", 1); nev++; }
2629 }
2630 char sth[65], evh[65]; sha_hex(&st, sth); sha_hex(&ev, evh);
2631 /* D5: semantic kernel as hand written */
2632 char *cp = pjoin(d, ".crumb"), *full = pjoin(c->top, cp), *txt = slurp(full); J *cr = txt ? jparse(txt) : NULL;
2633 J *sem = jnew(JOBJ);
2634 if (cr && cr->t == JOBJ) {
2635 static const char *ks[] = { "purpose", "layer", "invariants", "exports", "related", "boundaries", NULL };
2636 for (int k = 0; ks[k]; k++) { J *v = jget(cr, ks[k]); if (v && v->t != JNULL) jset(sem, ks[k], v); }
2637 }
2638 jsort(sem); char *semc = jcompact_s(sem);
2639 /* D7 (amended 2026-10-11, orphan crumbs): children = the NEAREST crumbed descendants. The walk descends through
2640 * directories that hold no .crumb (same traversal policy as find_crumbs: skip_generated_dir, lstat, no symlinks),
2641 * so every compiled crumb is reachable from the root digest and deleting any .crumb stales its nearest crumbed
2642 * ancestor. A deep child is named by its path relative to this crumb's directory ("archive/plans"). */
2643 Kid *kids_v = NULL; size_t nn = 0, kcap = 0; collect_kids(c, d, "", &kids_v, &nn, &kcap);
2644 qsort(kids_v, nn, sizeof *kids_v, kidcmp);
2645 J *kids = jnew(JARR); Sha crs; sha_init(&crs);
2646 for (size_t i = 0; i < nn; i++) {
2647 char *kd = kids_v[i].rel, *kc = pjoin(kd, ".crumb"), *kcf = pjoin(c->top, kc); const char *kname = kids_v[i].name;
2648 const char *kdig = dig_of(c, kd); char *kdig_own = NULL;
2649 if (!kdig) { /* not compiled in this run: fall back to what the crumb says */
2650 char *kt = slurp(kcf); J *kj = kt ? jparse(kt) : NULL; J *x = kj ? jget(kj, "extensions") : NULL; x = x ? jget(x, "generated") : NULL;
2651 const char *g = x ? jstrval(x, "digest") : NULL; kdig = kdig_own = xstrdup(g ? g : "uncompiled");
2652 }
2653 char *kt = slurp(kcf); J *kj = kt ? jparse(kt) : NULL; const char *kp = kj ? jstrval(kj, "purpose") : NULL; if (!kp) kp = "";
2654 char *kpur = xstrdup(kp); kpur[utf8_prefix(kpur, 96)] = 0; chomp(kpur);
2655 char gq[PATH_MAX * 2 + 64], *kq = shq(kd); snprintf(gq, sizeof gq, "log -1 --format=%%h HEAD -- %s ':!**/.crumb'", kq);
2656 char *lc = run_git_full(c->top, gq); chomp(lc);
2657 J *o = jnew(JOBJ); jset(o, "name", jstr(kname)); jset(o, "digest", jstr(kdig)); jset(o, "purpose", jstr(kpur)); jset(o, "last_commit", jstr(lc));
2658 jpush(kids, o); sha_add(&crs, kdig, strlen(kdig)); sha_add(&crs, "\n", 1);
2659 (void)kdig_own;
2660 }
2661 char crh[65]; sha_hex(&crs, crh);
2662 Sha ds; sha_init(&ds); sha_add(&ds, semc, strlen(semc)); sha_add(&ds, sth, 64); sha_add(&ds, crh, 64); sha_add(&ds, evh, 64);
2663 char dgh[65]; sha_hex(&ds, dgh); /* D3: content only, no stamps */
2664 strcpy(dig_out, dgh);
2665 J *g = jnew(JOBJ); char t[80];
2666 jset(g, "compiler", jstr("crumb-compile/1"));
2667 snprintf(t, sizeof t, "sha256:%s", sth); jset(g, "source_tree", jstr(t));
2668 jset(g, "files", jnum(nfiles)); jset(g, "children", kids);
2669 snprintf(t, sizeof t, "sha256:%s", crh); jset(g, "children_root", jstr(t));
2670 jset(g, "evidence_files", jnum(nev));
2671 snprintf(t, sizeof t, "sha256:%s", evh); jset(g, "evidence_root", jstr(t));
2672 snprintf(t, sizeof t, "sha256:%s", dgh); jset(g, "digest", jstr(t));
2673 jsort(g); return g;
2674}
2675/* D3a (added by the C port): children[].last_commit is derived from history and changes with every commit that
2676 * touches the child, exactly like the stamps of D3. It is written by compile but never decides STALE; otherwise a
2677 * PR could never pass verify (committing changes last_commit, which would need another compile, forever). */
2678static void strip_lc(J *g) { J *k = jget(g, "children"); if (k && k->t == JARR) for (size_t i = 0; i < k->n; i++) if (k->v[i]->t == JOBJ) jdel(k->v[i], "last_commit"); }
2679typedef struct { char *d; int depth; } CDir;
2680static int cdcmp(const void *a, const void *b) {
2681 const CDir *x = a, *y = b;
2682 if (x->depth != y->depth) return y->depth - x->depth; /* deepest first (D4) */
2683 return strcmp(x->d, y->d);
2684}
2685static void find_crumbs(const char *top, const char *rel, CDir **out, size_t *n, size_t *cap) {
2686 char *full = *rel ? pjoin(top, rel) : xstrdup(top); DIR *dp = opendir(full); if (!dp) return;
2687 struct dirent *e;
2688 while ((e = readdir(dp))) {
2689 if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue;
2690 char *r = *rel ? pjoin(rel, e->d_name) : xstrdup(e->d_name), *f = pjoin(top, r); struct stat st;
2691 if (lstat(f, &st) == 0) {
2692 if (S_ISDIR(st.st_mode) && skip_generated_dir(r)) { free(r); free(f); continue; } /* D10 + #355 */
2693 if (!strcmp(e->d_name, ".crumb") && !S_ISDIR(st.st_mode)) {
2694 if (*n == *cap) { *cap = *cap ? *cap * 2 : 32; *out = xrealloc(*out, *cap * sizeof **out); }
2695 (*out)[*n].d = *rel ? xstrdup(rel) : xstrdup("."); (*n)++;
2696 } else if (S_ISDIR(st.st_mode)) find_crumbs(top, r, out, n, cap);
2697 }
2698 free(r); free(f);
2699 }
2700 closedir(dp); free(full);
2701}
2702
2703/* RFC-0003 amendment 1 (2026-10-18): generated data is derived on demand, never committed.
2704 * A repository opts in with "extensions": {"generated_policy": "on-demand"} in its ROOT .crumb (written once by
2705 * `crumb migrate`). Then every committed crumb holds only what a human writes; a committed extensions.generated
2706 * block is STALE (it is the roll-up that made two unrelated PRs rewrite the same root lines), compile strips it,
2707 * verify prints the root digest computed from the tree at HEAD, and `crumb digest` prints any generated block.
2708 * Without the marker the repository is legacy and every command behaves exactly as before the amendment. */
2709#define GEN_POLICY_KEY "generated_policy"
2710#define GEN_POLICY_ON_DEMAND "on-demand"
2711static const char *g_digest_dir = NULL; /* mode 'd': repo-relative directory whose generated block to print */
2712static int root_on_demand(const char *top) {
2713 J *rc = load_crumb(top); J *x = rc ? jget(rc, "extensions") : NULL;
2714 const char *p = x && x->t == JOBJ ? jstrval(x, GEN_POLICY_KEY) : NULL;
2715 return p && !strcmp(p, GEN_POLICY_ON_DEMAND);
2716}
2717static void write_crumb(const char *full, J *cr) { /* D9: key-sorted, temp file then rename */
2718 jsort(cr);
2719 char *out = jdump(cr), *tmp = xmalloc(strlen(full) + 32); xsnprintf(tmp, strlen(full) + 32, "%s.tmp.%ld", full, (long)getpid());
2720 FILE *f = fcreate(tmp, 0); if (!f) die("cannot write %s", tmp);
2721 if (fputs(out, f) < 0 || fclose(f) != 0) die("write failed: %s", tmp);
2722 if (rename(tmp, full)) die("rename failed: %s", full);
2723}
2724
2725/* mode: 'c' compile, 'v' verify, 's' status, 'm' migrate (to on-demand), 'd' digest (print one generated block).
2726 * Returns number of stale crumbs; *total set. */
2727static int compile_engine(char mode, const char *root, int quiet, int *total_out, char *head_out) {
2728 Comp c; memset(&c, 0, sizeof c);
2729 char *rq = shq(root), cmd[PATH_MAX + 80]; snprintf(cmd, sizeof cmd, "git -C %s rev-parse --show-toplevel 2>/dev/null", rq);
2730 char *top = cap_cmd(cmd, NULL); chomp(top);
2731 if (!*top) die("crumb %s: not inside a git repository: %s", mode == 'c' ? "compile" : mode == 'v' ? "verify" : "status", root);
2732 c.top = top;
2733 reset_ignore(); load_ignore(top); policy_load(top); /* D10: <root>/.crumbignore subtrees never participate */
2734 char *head = run_git(top, "rev-parse HEAD"); if (strlen(head) != 40) head = xstrdup("0000000000000000000000000000000000000000");
2735 if (head_out) strcpy(head_out, head);
2736 comp_load_files(&c);
2737 /* D4, D7: every directory holding a .crumb (tracked or freshly seeded on disk), deepest first */
2738 CDir *ds = NULL; size_t nd = 0, cap = 0; find_crumbs(top, "", &ds, &nd, &cap);
2739 { size_t tl; char *lz = NULL; snprintf(cmd, sizeof cmd, "git -C %s ls-files -z 2>/dev/null", rq); lz = cap_cmd(cmd, &tl);
2740 for (char *s = lz; s < lz + tl; s += strlen(s) + 1) {
2741 size_t l = strlen(s); const char *b = strrchr(s, '/'); b = b ? b + 1 : s;
2742 if (strcmp(b, ".crumb")) continue;
2743 char *d = l == 6 ? xstrdup(".") : xstrndup_(s, l - 7); int dup = 0;
2744 if (ignored_subtree(d)) { free(d); continue; } /* D10 */
2745 for (size_t i = 0; i < nd; i++) if (!strcmp(ds[i].d, d)) dup = 1;
2746 if (dup) continue;
2747 if (nd == cap) { cap = cap ? cap * 2 : 32; ds = xrealloc(ds, cap * sizeof *ds); }
2748 ds[nd++].d = d;
2749 } }
2750 { size_t w = 0; for (size_t i = 0; i < nd; i++) { /* sort -u */
2751 int dup = 0; for (size_t j = 0; j < w; j++) if (!strcmp(ds[j].d, ds[i].d)) dup = 1;
2752 if (!dup) ds[w++] = ds[i]; } nd = w; }
2753 for (size_t i = 0; i < nd; i++) { int n = 0; if (!strcmp(ds[i].d, ".")) n = -1; else for (const char *s = ds[i].d; *s; s++) if (*s == '/') n++; ds[i].depth = n; }
2754 qsort(ds, nd, sizeof *ds, cdcmp);
2755 int total = 0, changed = 0, stale = 0, found = 0; char stamp[21]; now_iso(stamp);
2756 int ondemand = mode == 'm' || root_on_demand(top);
2757 for (size_t i = 0; i < nd; i++) {
2758 const char *d = ds[i].d; char *cp = pjoin(d, ".crumb"), *full = pjoin(top, cp); struct stat sb;
2759 if (stat(full, &sb) || !S_ISREG(sb.st_mode)) continue;
2760 total++;
2761 char dg[65]; J *nw = comp_object(&c, d, dg); dig_set(&c, d, dg);
2762 if (mode == 'd') { /* on demand: the block compile would have committed, with this HEAD as its stamp */
2763 if (g_digest_dir && !strcmp(d, g_digest_dir)) { jset(nw, "generated_at_commit", jstr(head)); jsort(nw); fputs(jdump(nw), stdout); found = 1; }
2764 continue;
2765 }
2766 char *txt = slurp(full); J *cr = txt ? jparse(txt) : NULL;
2767 if (ondemand) { /* amendment 1: only the hand-written crumb is committed */
2768 J *x = cr && cr->t == JOBJ ? jget(cr, "extensions") : NULL;
2769 int has_gen = x && x->t == JOBJ && jget(x, "generated");
2770 int need_mark = mode == 'm' && !strcmp(d, ".") && !root_on_demand(top);
2771 if (!cr || cr->t != JOBJ) {
2772 stale++; if (!quiet) printf("INVALID %s (not a JSON object)\n", d);
2773 if (mode == 'c' || mode == 'm') die("cannot compile %s: not a JSON object", cp);
2774 continue;
2775 }
2776 if (!has_gen && !need_mark) { if (mode == 's' && !quiet) printf("CURRENT %s\n", d); continue; }
2777 if (mode == 's' || mode == 'v') { stale++; if (!quiet) printf("STALE %s (committed generated data; run: crumb compile)\n", d); continue; }
2778 if (has_gen) { jdel(x, "generated"); if (x->n == 0) jdel(cr, "extensions"); }
2779 if (need_mark) { J *rx = jget(cr, "extensions"); if (!rx || rx->t != JOBJ) { rx = jnew(JOBJ); jset(cr, "extensions", rx); } jset(rx, GEN_POLICY_KEY, jstr(GEN_POLICY_ON_DEMAND)); }
2780 write_crumb(full, cr); changed++; if (!quiet) printf("STRIPPED %s\n", d);
2781 continue;
2782 }
2783 J *old = jnew(JOBJ);
2784 if (cr && cr->t == JOBJ) { J *x = jget(cr, "extensions"), *g = x && x->t == JOBJ ? jget(x, "generated") : NULL;
2785 if (g && g->t == JOBJ) { old = jclone(g); jdel(old, "generated_at_commit"); jdel(old, "compiled_at"); } }
2786 jsort(old);
2787 strip_lc(old); J *nwc = jclone(nw); strip_lc(nwc); /* D3a: last_commit is a stamp for staleness */
2788 char *ns = jcompact_s(nwc), *os = jcompact_s(old);
2789 if (!strcmp(ns, os)) { if (mode == 's' && !quiet) printf("CURRENT %s\n", d); continue; }
2790 stale++;
2791 if (mode == 's') { if (!quiet) printf("%s %s\n", old->n == 0 ? "UNCOMPILED" : "STALE ", d); }
2792 else if (mode == 'v') { if (!quiet) printf("STALE %s\n", d); }
2793 else {
2794 if (!cr || cr->t != JOBJ) die("cannot compile %s: not a JSON object", cp);
2795 J *x = jget(cr, "extensions"); if (!x || x->t != JOBJ) { x = jnew(JOBJ); jset(cr, "extensions", x); }
2796 J *g = jclone(nw); jset(g, "generated_at_commit", jstr(head)); jset(g, "compiled_at", jstr(stamp));
2797 jset(x, "generated", g); jsort(cr);
2798 char *out = jdump(cr), *tmp = xmalloc(strlen(full) + 32); xsnprintf(tmp, strlen(full) + 32, "%s.tmp.%ld", full, (long)getpid());
2799 FILE *f = fcreate(tmp, 0); if (!f) die("cannot write %s", tmp);
2800 if (fputs(out, f) < 0 || fclose(f) != 0) die("write failed: %s", tmp);
2801 if (rename(tmp, full)) die("rename failed: %s", full);
2802 changed++; if (!quiet) printf("COMPILED %s\n", d);
2803 }
2804 }
2805 if (total_out) *total_out = total;
2806 char h7[8]; memcpy(h7, head, 7); h7[7] = 0;
2807 const char *rd = dig_of(&c, "."); char rds[80]; snprintf(rds, sizeof rds, "sha256:%s", rd ? rd : "none");
2808 if (mode == 'd') { if (!found) die("crumb digest: %s holds no compiled .crumb", g_digest_dir ? g_digest_dir : "?"); return 0; }
2809 if (!quiet && ondemand) { /* one line: verify.rs takes the first stdout line as the readiness note */
2810 if (mode == 'c') printf("crumb compile: %d crumbs, %d rewritten, HEAD %s, generated data on demand, root digest %s\n", total, changed, h7, rds);
2811 else if (mode == 'm') printf("crumb migrate: %d crumbs, %d rewritten, generated data is now derived on demand, root digest %s\n", total, changed, rds);
2812 else if (mode == 'v') {
2813 if (stale) printf("crumb verify: FAIL: %d of %d crumbs stale; run: crumb compile\n", stale, total);
2814 else printf("crumb verify: OK: %d crumbs current at HEAD %s, generated data on demand, root digest %s\n", total, h7, rds);
2815 } else printf("crumb status: %d crumbs, %d not current\n", total, stale);
2816 return stale;
2817 }
2818 if (!quiet) {
2819 if (mode == 'c') printf("crumb compile: %d crumbs, %d rewritten, HEAD %s\n", total, changed, h7);
2820 else if (mode == 'v') {
2821 if (stale) printf("crumb verify: FAIL: %d of %d crumbs stale; run: crumb compile\n", stale, total);
2822 else printf("crumb verify: OK: %d crumbs current\n", total);
2823 } else printf("crumb status: %d crumbs, %d not current\n", total, stale);
2824 }
2825 return stale;
2826}
2827static int cmd_compile(char mode, const char *root) { int t; int s = compile_engine(mode, root, 0, &t, NULL); return mode == 'v' && s ? 1 : 0; }
2828static int cmd_digest(const char *dir) { /* amendment 1: print a directory's generated block, computed now */
2829 char r[PATH_MAX]; if (!realpath(dir, r)) die("no such directory: %s", dir);
2830 char *rq = shq(r), cmd[PATH_MAX + 80]; snprintf(cmd, sizeof cmd, "git -C %s rev-parse --show-toplevel 2>/dev/null", rq);
2831 char *top = cap_cmd(cmd, NULL); chomp(top);
2832 if (!*top) die("crumb digest: not inside a git repository: %s", dir);
2833 size_t tl = strlen(top); g_digest_dir = r[tl] ? xstrdup(r + tl + 1) : xstrdup(".");
2834 int t; compile_engine('d', top, 1, &t, NULL); return 0;
2835}
2836static int cmd_propose(const char *dir, const char *purpose) { /* D5: only extensions.proposed, never .purpose */
2837 char *cp = pjoin(dir, ".crumb"), *txt = slurp(cp);
2838 if (!txt) die("no .crumb in %s", dir);
2839 J *cr = jparse(txt); if (!cr || cr->t != JOBJ) die("%s is not a JSON object", cp);
2840 J *x = jget(cr, "extensions"); if (!x || x->t != JOBJ) { x = jnew(JOBJ); jset(cr, "extensions", x); }
2841 const char *by = getenv("CRUMB_SESSION"); if (!by || !*by) by = getenv("USER"); if (!by) by = "";
2842 char at[21]; now_iso(at);
2843 J *pr = jnew(JOBJ); jset(pr, "purpose", jstr(purpose)); jset(pr, "status", jstr("PROPOSED")); jset(pr, "by", jstr(by)); jset(pr, "at", jstr(at));
2844 jset(x, "proposed", pr); jsort(cr);
2845 spit(cp, jdump(cr));
2846 printf("PROPOSED purpose for %s (stays PROPOSED until a human moves it into .purpose)\n", dir);
2847 return 0;
2848}
2849
2850/* ---------- RFC-0003: crumb context ---------- */
2851#define CTX_TREE_MAX 40
2852static const char *crumb_purpose(J *c, char *buf, size_t n) { /* .purpose, else PROPOSED, else none */
2853 const char *p = c ? jstrval(c, "purpose") : NULL;
2854 if (p && *p && !strstr(p, "not yet described")) { snprintf(buf, n, "%s", p); return buf; }
2855 J *x = c ? jget(c, "extensions") : NULL, *pr = x && x->t == JOBJ ? jget(x, "proposed") : NULL;
2856 const char *pp = pr && pr->t == JOBJ ? jstrval(pr, "purpose") : NULL;
2857 if (pp && *pp) { snprintf(buf, n, "PROPOSED: %s", pp); return buf; }
2858 snprintf(buf, n, "(no purpose yet)"); return buf;
2859}
2860static int cmd_context(const char *target) {
2861 char r[PATH_MAX];
2862 if (!realpath(target, r)) die("no such file or directory: %s", target);
2863 struct stat st; if (stat(r, &st)) die("cannot stat %s", target);
2864 char *abs = xstrdup(r), *dir = S_ISDIR(st.st_mode) ? xstrdup(r) : dir_of(r);
2865 Plane *p = plane_resolve(dir);
2866 if (!p) die("crumb context needs a git repository: %s", target);
2867 size_t tl = strlen(p->top); char *rel = abs[tl] ? xstrdup(abs + tl + 1) : xstrdup(".");
2868 int total = 0; char head[64] = "";
2869 int stale = compile_engine('s', p->top, 1, &total, head); head[7] = 0;
2870 printf("CRUMB CONTEXT %s\n", rel);
2871 if (stale) printf("Crumbs STALE: %d of %d (run crumb compile)\n", stale, total);
2872 else printf("Crumbs CURRENT at HEAD %s (%d crumbs)\n", head, total);
2873 printf("== TREE ==\n");
2874 { J *rc = load_crumb(p->top); char b[300]; if (rc) printf(" . : %s\n", crumb_purpose(rc, b, sizeof b)); }
2875 DIR *dp = opendir(p->top); char **nm = NULL; size_t nn = 0;
2876 if (dp) { struct dirent *e; while ((e = readdir(dp))) if (e->d_name[0] != '.') { nm = xrealloc(nm, (nn + 1) * sizeof *nm); nm[nn++] = xstrdup(e->d_name); } closedir(dp); }
2877 qsort(nm, nn, sizeof *nm, sstrcmp);
2878 size_t shown = 0, more = 0;
2879 for (size_t i = 0; i < nn; i++) {
2880 char *kd = pjoin(p->top, nm[i]); J *kc = load_crumb(kd);
2881 if (!kc) continue;
2882 if (shown >= CTX_TREE_MAX) { more++; continue; }
2883 char b[300]; printf(" %s/ : %s\n", nm[i], crumb_purpose(kc, b, sizeof b)); shown++;
2884 }
2885 if (more) printf(" ... %zu more\n", more);
2886 if (!shown) printf(" (no child crumbs)\n");
2887 printf("== YOUR TASK TOUCHES ==\n %s%s\n", rel, S_ISDIR(st.st_mode) ? "/" : "");
2888 printf("== READ THESE CRUMBS (root to nearest) ==\n");
2889 { char **chain = NULL; size_t nc = 0, ptl = strlen(p->top); char *d = xstrdup(dir);
2890 for (;;) {
2891 size_t dl = strlen(d), tl2 = ptl;
2892 if (dl < tl2) break;
2893 if (load_crumb(d)) { chain = xrealloc(chain, (nc + 1) * sizeof *chain); chain[nc++] = xstrdup(d); }
2894 if (dl == tl2) break;
2895 char *up = dir_of(d); free(d); d = up;
2896 }
2897 if (!nc) printf(" (no .crumb at or above this path)\n");
2898 for (size_t i = nc; i-- > 0; ) { const char *rr = chain[i][ptl] ? chain[i] + ptl + 1 : "."; char b[300]; J *cj = load_crumb(chain[i]);
2899 printf(" %s%s.crumb : %s\n", !strcmp(rr, ".") ? "" : rr, !strcmp(rr, ".") ? "" : "/", crumb_purpose(cj, b, sizeof b)); }
2900 }
2901 printf("== CURRENT CONFLICTS ==\n");
2902 Txn *t = txn_begin(p, 0); txn_prune(t); int any = 0; size_t rl = strlen(rel);
2903 for (size_t i = 0; i < t->n; i++) if (!t->r[i]->agent) {
2904 J *lk = jget(t->r[i]->root, "locks");
2905 if (lk && lk->t == JOBJ) for (size_t k = 0; k < lk->n; k++) {
2906 const char *kk = lk->k[k]; size_t kl = strlen(kk);
2907 int hit = !strcmp(rel, ".") || !strcmp(kk, rel) || (kl > rl && !strncmp(kk, rel, rl) && kk[rl] == '/') || (rl > kl && !strncmp(rel, kk, kl) && rel[kl] == '/');
2908 if (hit) { print_lock(kk, lk->v[k]); any = 1; }
2909 }
2910 }
2911 if (!any) printf(" (none)\n");
2912 txn_end(t, 0);
2913 printf("== RELEVANT CONTINUATION ==\n");
2914 J *best = NULL; char *bestf = NULL; int nmatch = 0;
2915 { char **f = NULL; size_t n = 0; char *cd = pjoin(p->store, "continuations"); collect_json(cd, &f, &n);
2916 for (size_t i = 0; i < n; i++) {
2917 char *txt = read_bounded(f[i], MAX_RECORD_BYTES, NULL); J *c = txt ? jparse(txt) : NULL;
2918 if (g_enforce && (!c || c->t != JOBJ)) die("%s is not valid JSON; refusing (enforcement mode never skips unreadable state)", f[i]);
2919 if (!c || c->t != JOBJ || !jget(c, "identity") || !cont_matches(c, rel)) continue;
2920 nmatch++; if (!best || strcmp(cont_when(c), cont_when(best)) > 0) { best = c; bestf = f[i]; }
2921 } }
2922 if (!best) printf(" (none touches this path)\n");
2923 else {
2924 J *id = jget(best, "identity"), *s2 = jget(best, "state"), *items = s2 && s2->t == JOBJ ? jget(s2, "items") : s2;
2925 printf(" id: %s sealed: %s (%d matching, showing newest)\n file: %s\n reason: %s\n", sv(id, "checkpoint_id"), cont_when(best), nmatch, bestf, sv(id, "reason"));
2926 if (items && items->t == JARR) for (size_t i = 0; i < items->n && i < 8; i++) printf(" [%s] %s\n", sv(items->v[i], "tag"), sv(items->v[i], "claim"));
2927 if (items && items->t == JARR && items->n > 8) printf(" ... %zu more (crumb explain %s)\n", items->n - 8, rel);
2928 }
2929 return 0;
2930}
2931
2932/* store-id [dir]: print the coordination store's id (the onboarding step: register it with git config crumb.storeId).
2933 * Registered: verified, never created. Unregistered (also under --strict, since this is how a store is registered):
2934 * the marker is created under the store lock if absent, exactly as synapse-coord `id` / ensure_store_id does. */
2935static int cmd_store_id(const char *dir) {
2936 Plane *p = plane_find(dir);
2937 if (!p) die("store-id needs a git repository: %s", dir);
2938 if (p->id.has_expect) ident_gate(&p->id, p->root, 0);
2939 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); }
2940 else { p->id.warned = 1; Txn *t = txn_begin(p, 1); txn_end(t, 0); }
2941 char hex[33];
2942 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);
2943 printf("%s\n", hex);
2944 if (!p->id.has_expect) fprintf(stderr, "crumb: coordination store %s is unregistered; register it: git config crumb.storeId %s\n", p->root, hex);
2945 return 0;
2946}
2947/* store-init's proof that a layout-1 record directory (dirs/, agents/, continuations/) holds nothing, independent of
2948 * enforcement mode (crumb924 B8): absent, or a real directory whose whole tree is real (empty) subdirectories only.
2949 * Every open/read failure, symbolic link, record or other file refuses: an inspection that could not see everything
2950 * is never taken for an empty store. With rm set (only after every directory has been proved), the empty tree is
2951 * removed bottom-up and a failed removal refuses too (a file added since the proof makes the removal fail: refused).
2952 * The walk is descriptor-relative (openat with O_DIRECTORY|O_NOFOLLOW from the parent's descriptor, unlinkat on the
2953 * same descriptor), so no name is checked by one call and then used by another (no check-to-use window, CodeQL
2954 * cpp/toctou-race-condition). pfd is the parent directory, name the entry in it, shown the path for messages. */
2955static void legacy_empty(const char *root, int pfd, const char *name, const char *shown, int top, int rm) {
2956 int fd = openat(pfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC);
2957 if (fd < 0) {
2958 int er = errno;
2959 if (top && er == ENOENT) return;
2960 /* Linux reports a link to a directory as ENOTDIR under O_DIRECTORY; which refusal to print is decided after the
2961 * failed open (every branch here refuses, so the lookup only picks the message) */
2962 struct stat st;
2963 if (er == ELOOP || (er == ENOTDIR && fstatat(pfd, name, &st, AT_SYMLINK_NOFOLLOW) == 0 && S_ISLNK(st.st_mode)))
2964 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);
2965 if (er == ENOTDIR) {
2966 size_t l = strlen(name);
2967 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);
2968 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);
2969 }
2970 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);
2971 }
2972 DIR *d = fdopendir(fd);
2973 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); }
2974 struct dirent *e;
2975 for (;;) {
2976 errno = 0;
2977 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; }
2978 if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue;
2979 char *full = pjoin(shown, e->d_name);
2980 legacy_empty(root, dirfd(d), e->d_name, full, 0, rm);
2981 free(full);
2982 }
2983 closedir(d);
2984 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);
2985}
2986/* store-init [dir] (crumb924): make the coordination root a layout-2 (repository-namespaced) root, deliberately.
2987 * Under the root lock: STORE_ID as store-id does (registered: must match, never created); then LAYOUT is published
2988 * once (link(2), never replaced) and repos/ created. Refused unless dirs/ agents/ continuations/ are proved empty
2989 * whatever the enforcement mode (legacy_empty), so old locks are never silently dropped or reinterpreted.
2990 * Idempotent on a layout-2 root. */
2991static int cmd_store_init(const char *dir) {
2992 Plane *p = plane_find(dir);
2993 if (!p) die("store-init needs a git repository: %s", dir);
2994 if (p->id.has_expect) ident_gate(&p->id, p->root, 0);
2995 mkdir_p(p->root);
2996 int fd = root_lock(p->root, 1);
2997 p->id.warned = 1; ident_gate(&p->id, p->root, 1);
2998 int created = 0;
2999 if (read_layout(p->root) != 2) {
3000 static const char *flat[] = { "dirs", "agents", "continuations", NULL };
3001 int rfd = crumb_open_follow(p->root, O_RDONLY | O_DIRECTORY, 0); /* the root may be named through a link */
3002 if (rfd < 0) die("STORE_LAYOUT_V1_UNPROVEN: cannot open coordination root %s: %s", p->root, strerror(errno));
3003 for (int pass = 0; pass < 2; pass++) /* prove all three first; only then remove the empty trees */
3004 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); }
3005 char *ld = pjoin(p->root, "ledger"); /* never holds records; left in place when it is not empty */
3006 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);
3007 free(ld); close(rfd);
3008 char *lp = pjoin(p->root, LAYOUT_FILE);
3009 publish_once(p->root, lp, LAYOUT_V2, strlen(LAYOUT_V2));
3010 free(lp); created = 1;
3011 }
3012 if (read_layout(p->root) != 2) die("store-init: %s did not become layout 2", p->root);
3013 char *rd = pjoin(p->root, "repos"); mkdir_p(rd); free(rd);
3014 close(fd);
3015 char hex[33];
3016 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);
3017 if (!p->repo_id) p->repo_id = repo_id_resolve(p->abs, &p->repo_src);
3018 printf("STORE_INIT %s layout crumb-coord-layout/2 store %s%s\n", p->root, hex, created ? "" : " (already layout 2)");
3019 if (p->repo_id) printf("repository %s (from %s) -> %s/repos/%s\n", p->repo_id, p->repo_src, p->root, p->repo_id);
3020 else printf("repository (none resolved: set git config crumb.repoId <owner>/<repo> before using this root)\n");
3021 if (!p->id.has_expect) fprintf(stderr, "crumb: coordination store %s is unregistered; register it: git config crumb.storeId %s\n", p->root, hex);
3022 return 0;
3023}
3024
3025static void usage(void) {
3026 fputs("usage: crumb [--strict] [--enforce] <command> ...\n"
3027 " seed <root> [-n] [-v] write/refresh .crumb files (idempotent; -n dry run)\n"
3028 " backfill <root> [--since <date>] [-n] reconstruct history from git + lane reports (run after seed)\n"
3029 " create <dir> <name> <purpose> [layer] new .crumb for one directory\n"
3030 " claim <agent> <dir> <target> <intent> [ttl] scent + advisory lock (exit 2 if held by another)\n"
3031 " update <agent> <dir> <focus> [ttl] refresh scent\n"
3032 " whisper <from> <dir> <to|-> <msg> [prio] [target_file]\n"
3033 " close <agent> <dir> <target> [action] [msg] release lock, add history vector, optional whisper\n"
3034 " sniff <agent> <dir> what to read before touching a directory\n"
3035 " explain <file-or-dir> nearest + inherited crumbs, coordination, commits, evidence, newest continuation\n"
3036 " compile [root] RFC-0003: regenerate structural crumb data bottom-up (Merkle digests)\n"
3037 " verify [root] exit 1 if any committed crumb differs from what compile would write\n"
3038 " status [root] CURRENT / STALE / UNCOMPILED per crumb\n"
3039 " migrate [root] RFC-0003 am. 1: strip committed generated data, mark the root on-demand\n"
3040 " digest [dir] print the generated block of dir, computed from the tree now\n"
3041 " propose <dir> <purpose> write extensions.proposed.purpose (never .purpose)\n"
3042 " context [path] entry point: tree, what to read, conflicts, continuation, freshness\n"
3043 " checkpoint <agent> [--reason R] new Continuation Crumb (wraps cc.sh); then checkpoint --seal <id> [agent]\n"
3044 " resume <id> print record, revalidate against live repos (wraps cc.sh)\n"
3045 " list [path] live scents, locks, whispers under path\n"
3046 " validate [path] check .crumb files against RFC-0001 required fields\n"
3047 " store-id [dir] print the coordination store id (creates it if unregistered and absent)\n"
3048 " store-init [dir] make the coordination root layout 2 (repos/<repo-id>/ namespaces), deliberately\n"
3049 " 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"
3050 "store identity: expected id from CRUMB_EXPECT_STORE_ID, else git config crumb.storeId; --strict or\n"
3051 " CRUMB_STRICT_STORE_ID=1 refuses unregistered stores. Exit 3 = store identity refusal, 4 = refused store file.\n"
3052 "repository id (layout 2): CRUMB_REPO_ID, else git config crumb.repoId, else origin URL <owner>/<repo>.\n"
3053 "enforcement (--enforce, CRUMB_ENFORCE=1, git config crumb.enforce true): registered store, layout 2, repo id,\n"
3054 " verbatim agent ids, strict lease schema, no .crumb.local fallback, unreadable state is an error (exit 1).\n", stderr);
3055 exit(1);
3056}
3057static 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; }
3058int main(int argc, char **argv) {
3059 { const char *s = getenv("CRUMB_STRICT_STORE_ID"); if (s && !strcmp(s, "1")) g_strict = 1; }
3060 { const char *s = getenv("CRUMB_ENFORCE"); if (s && bool_word(s, "CRUMB_ENFORCE")) enforce_on(); }
3061 while (argc > 1 && (!strcmp(argv[1], "--strict") || !strcmp(argv[1], "--enforce"))) { if (!strcmp(argv[1], "--enforce")) enforce_on(); else g_strict = 1; argv++; argc--; }
3062 if (argc < 2) usage();
3063 const char *c = argv[1]; int a = argc - 2; char **v = argv + 2;
3064 if (!strcmp(c, "seed") && a >= 1) {
3065 int dry = 0, verb = 0;
3066 for (int i = 1; i < a; i++) { if (!strcmp(v[i], "-n")) dry = 1; else if (!strcmp(v[i], "-v")) verb = 1; else usage(); }
3067 return cmd_seed(v[0], dry, verb);
3068 }
3069 if (!strcmp(c, "backfill") && a >= 1) {
3070 const char *since = NULL; int dry = 0;
3071 for (int i = 1; i < a; i++) { if (!strcmp(v[i], "--since") && i + 1 < a) since = v[++i]; else if (!strcmp(v[i], "-n")) dry = 1; else usage(); }
3072 return cmd_backfill(v[0], since, dry);
3073 }
3074 if (!strcmp(c, "create") && a >= 3) return cmd_create(v[0], v[1], v[2], a > 3 ? v[3] : NULL);
3075 if (!strcmp(c, "claim") && a >= 4) return cmd_claim(v[0], v[1], v[2], v[3], ttl_arg(a > 4 ? v[4] : NULL, LOCK_TTL));
3076 if (!strcmp(c, "update") && a >= 3) return cmd_update(v[0], v[1], v[2], ttl_arg(a > 3 ? v[3] : NULL, SCENT_TTL));
3077 if (!strcmp(c, "whisper") && a >= 4) return cmd_whisper(v[0], v[1], v[2], v[3], a > 4 ? v[4] : NULL, a > 5 ? v[5] : NULL);
3078 if (!strcmp(c, "close") && a >= 3) return cmd_close(v[0], v[1], v[2], a > 3 ? v[3] : "modify", a > 4 ? v[4] : NULL);
3079 if (!strcmp(c, "sniff") && a >= 2) return cmd_sniff(v[0], v[1]);
3080 if (!strcmp(c, "explain") && a == 1) return cmd_explain(v[0]);
3081 if (!strcmp(c, "sha256") && a == 0) { Sha s; char h[65]; unsigned char t[8192]; size_t n; sha_init(&s); while ((n = fread(t, 1, sizeof t, stdin)) > 0) sha_add(&s, t, n); sha_hex(&s, h); printf("%s\n", h); return 0; }
3082 if (!strcmp(c, "compile") && a <= 1) return cmd_compile('c', a ? v[0] : ".");
3083 if (!strcmp(c, "verify") && a <= 1) return cmd_compile('v', a ? v[0] : ".");
3084 if (!strcmp(c, "status") && a <= 1) return cmd_compile('s', a ? v[0] : ".");
3085 if (!strcmp(c, "migrate") && a <= 1) return cmd_compile('m', a ? v[0] : ".");
3086 if (!strcmp(c, "digest") && a <= 1) return cmd_digest(a ? v[0] : ".");
3087 if (!strcmp(c, "propose") && a == 2) return cmd_propose(v[0], v[1]);
3088 if (!strcmp(c, "context") && a <= 1) return cmd_context(a ? v[0] : ".");
3089 if (!strcmp(c, "checkpoint")) return cmd_checkpoint(a, v);
3090 if (!strcmp(c, "resume") && a == 1) return cmd_resume(v[0]);
3091 if (!strcmp(c, "store-id") && a <= 1) return cmd_store_id(a ? v[0] : ".");
3092 if (!strcmp(c, "store-init") && a <= 1) return cmd_store_init(a ? v[0] : ".");
3093 if (!strcmp(c, "check") && a >= 3 && (a - 3) % 2 == 0 && a <= 7) {
3094 int has_want = 0; unsigned long long want = 0; const char *want_key = NULL;
3095 for (int i = 3; i < a; i += 2) {
3096 if (!strcmp(v[i], "--generation") && !has_want) { has_want = 1; want = gen_arg(v[i + 1]); }
3097 else if (!strcmp(v[i], "--key") && !want_key && *v[i + 1]) want_key = v[i + 1];
3098 else usage();
3099 }
3100 return cmd_check(v[0], v[1], v[2], has_want, want, want_key);
3101 }
3102 if (!strcmp(c, "list") || !strcmp(c, "validate")) {
3103 int val = !strcmp(c, "validate"); Tot t = {0, 0, 0};
3104 char *r = absdir(a ? v[0] : ".");
3105 Plane *sp = val ? NULL : plane_resolve(r);
3106 if (sp) g_skip_local = 1;
3107 walk_list(r, ".", 0, val, &t);
3108 if (sp) t.n_local += shared_list(sp);
3109 printf("%d .crumb file(s), %d directory(ies) with live local crumbs%s\n", t.n_crumb, t.n_local, val && t.bad ? ", INVALID found" : "");
3110 return t.bad ? 1 : 0;
3111 }
3112 usage();
3113 return 1;
3114}