Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/synapse/blob/main/crates/synapse-coord/README.md # synapse A component of the AienOS ecosystem. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `synapse / crates / synapse-coord / README.md` 207 lines ยท 14318 bytes Raw Blame History Rendered 1 # synapse-coord 2 3 Shared agent coordination (claims, presence, whispers) for agents working through Synapse, 4 on the **same store** as the Crumb tool `crumb.c`. Deliverable 2 of the Crumb-Synapse 5 workstream (ADR 0004): move shared agent coordination off Git without creating a second, 6 invisible lock set. 7 8 Reference implementation: `tools/crumb/crumb.c` in aien-architecture at ``29780e5`` 9 (sha256 of the file: ``ef0f6566fb838917a750eb898f66596b76aa15a53d7d61bedac03c4c963ee147``; 10 identical to `origin/main` on 2026-10-14), RFC-0002 plane from the comment 11 "RFC-0002 common coordination plane", and `docs/CRUMB_PROTOCOL_RFC_0002.md`. 12 13 ## The problem this prevents 14 15 During the transition some agents claim through `crumb` in Git worktrees and some through 16 Synapse. If each side kept its own locks, two agents could both "own" `src/runtime.c` and 17 neither would know. Here both tools read and write one store under one OS lock, so a claim 18 made by either is refused by the other, and each sees the other in `sniff`. 19 `scripts/crumb-coord-interop.sh` proves this against the pinned C tool. 20 21 ## Compatibility contract with crumb.c (what is kept identical) 22 23 | Aspect | Rule (same as crumb.c) | 24 |---|---| 25 | Store root | Passed in explicitly. crumb.c uses `CRUMB_COORD_ROOT`, else `git config crumb.coordinationRoot`, else `/crumb/v1`. Synapse points both at one directory beside its repository store. This crate never calls Git. | 26 | Layout | `dirs/.json` (`dirs/_root.json` for `.`), `agents/.json` (bytes outside `[A-Za-z0-9._-]` become `_`), `continuations/`, `ledger/`, lock file `.lock`. | 27 | Transaction lock | `fcntl(F_SETLKW, F_WRLCK)` on `/.lock`, whole file, held for the read-modify-write of one command. Readers (`sniff`) take no lock. | 28 | Durable write | `.tmp`, write, fsync, close, rename over the record, fsync the directory. Only changed records are written. | 29 | Keys | `norm_path` collapses `.`, `..`, `//`; a path that climbs above the root is refused. Target key: `/` if it exists, else `` from the root if it exists, else the repo-relative form when the target contains `/`, else `/`. Absolute targets must lie inside the workspace. | 30 | TTLs | lock 1800 s, scent 3600 s, whispers kept 24 h; a claim's presence lasts `max(3600, lock ttl)`. Expired = `now - stamp > ttl`, or the stamp is unparseable. | 31 | Pruning | Every mutation loads every record, drops expired locks/scents/whispers, unlinks expired agent records, and writes back what changed. | 32 | Records | Byte-identical JSON: key order kept, two-space indent, `": "`, trailing newline, `\u007f` and control bytes escaped as crumb.c does, numbers kept as written, unknown fields preserved. Strings are bytes (no UTF-8 requirement). History capped at 20. | 33 | Exit semantics | claim on a key held by another agent: blocked with holder info (C exit 2); close by a non-holder: refused (exit 2). | 34 | Session id | `CRUMB_SESSION` if set, else `agent@host`; never a PID. A caller may pass one explicitly. | 35 36 ## What replaces branch / head / base for Synapse agents (decision) 37 38 RFC-0002 says branch, worktree, head and base are **holder metadata, never identity**. 39 crumb.c writes them from Git. A Synapse agent has no Git branch, so `Holder::synapse(lane, 40 revision, base)` fills the same fields and adds one: 41 42 | Field | Git agent (crumb.c) | Synapse agent (this crate) | 43 |---|---|---| 44 | `worktree` | `git rev-parse --show-toplevel` | the agent's workspace path or a stable absolute label (e.g. `/synapse/ws/`) | 45 | `branch` | short branch name | the Synapse lane/ref name | 46 | `head` | 12-hex short commit | first 12 hex of the ChangesetId the agent works from | 47 | `base` | 12-hex merge-base with origin/main | first 12 hex of the base ChangesetId | 48 | `synapse_revision` | absent | full ChangesetId hex (new, appended last) | 49 50 The extra field is only appended; every field crumb.c reads keeps its meaning, so crumb.c's 51 displays (`held by X [branch]`, `BLOCKED ... on branch ...`) stay readable. crumb.c's JSON 52 model keeps unknown fields, and the interop script checks that crumb.c rewriting the same 53 directory record keeps `synapse_revision` (I5). The crate takes strings, not 54 `synapse_core::ChangesetId`, so it has no dependency on Synapse internals. 55 56 ## Store identity: catching split coordination roots (issue #15) 57 58 The two tools agree on one store only by configuration (`CRUMB_COORD_ROOT` / 59 `crumb.coordinationRoot` for crumb.c, `--store` or the path given to `CoordStore` here). A 60 wrong root used to fail silently: each tool granted a claim on the same file in its own store. 61 62 - **Marker.** `/STORE_ID` holds one line, `crumb-coord-store-id/1 <32 lowercase hex>` 63 (128 random bits from `/dev/urandom`). Any other content is refused (`StoreIdUnreadable`), 64 never rewritten. 65 - **Creation.** The first mutating transaction of a plain `CoordStore::open` handle (or 66 `ensure_store_id`) creates it while holding the store lock (process mutex plus `fcntl` on 67 `.lock`). It is written to `STORE_ID.tmp`, fsynced, and published with `link(2)`, which 68 never replaces an existing file; then the directory is fsynced. Concurrent first opens 69 (16 threads plus 8 processes, 5 rounds) all read one id. Either layer alone holds: a 70 negative control with `rename` outside the lock made the race test fail; `link` outside the 71 lock still passed. Reads (`sniff`, `store_id`) never create it. 72 - **Expecting open.** Synapse is to register a store's id per repository (taken from 73 `ensure_store_id`; that registration is not built yet) and open agents with 74 `CoordStore::open_expecting(root, id)`. That 75 refuses with `StoreIdMissing` (no marker) or `StoreIdMismatch` (another store), before 76 creating anything, and re-checks inside every transaction under the lock. An expecting handle 77 never creates a marker, so a misconfigured root is never adopted. CLI: 78 `--expect-store-id ID`; `synapse-coord --store DIR id` prints (and if needed creates) the id. 79 - **crumb.c ignores it.** The pinned crumb.c never names `STORE_ID`; it touches only `.lock`, 80 `dirs/`, `agents/`, `continuations/`, `ledger/`, and its `collect_json` walks only those 81 record directories. The interop script checks crumb.c never creates it and that it is 82 byte-identical after crumb.c's claims, closes, whispers and prunes (I11). 83 - **sniff** shows `store id: ` (or `(none yet)`). crumb.c's sniff does not print it; 84 that needs a crumb.c change in aien-architecture (not done here). A crumb.c-side check of the 85 id is likewise out of scope: today only the Synapse side refuses a wrong root. 86 - **Root helper.** `resolve_coord_root(env, git_config, git_common_dir)` mirrors crumb.c's 87 order as a pure function (no Git calls): non-empty `CRUMB_COORD_ROOT`, else non-empty 88 `crumb.coordinationRoot` (trailing `\n`/`\r` stripped), else `/crumb/v1` with the 89 common dir already absolute and resolved. Env and config values are returned as given 90 (crumb.c does not canonicalize them); a config value of 511 bytes or more is refused because 91 crumb.c would truncate it. 92 93 ## Crash safety 94 95 - A writer that dies before `rename` leaves the old record intact plus a `*.tmp` file. 96 Neither tool ever loads it (records are only names ending in `.json`). Tested by killing a 97 real process at that point (`SYNAPSE_COORD_FAULT=before-rename`, test-only) and by planting 98 torn tmp files. 99 - The OS releases the `fcntl` lock when the holding process dies, so a crash never wedges the store. 100 - A record that is not a JSON object is refused with an error and left untouched (as crumb.c). 101 - POSIX record locks belong to the process, not the thread. A process-wide mutex serializes 102 transactions inside one process; the `fcntl` lock serializes processes. A negative control 103 (mutex removed) made the 16-thread race test fail, so both layers are needed. 104 105 ## Hostile store files (issue #58) 106 107 Anyone who can write into the shared store can plant a FIFO, a device, a symlink to 108 `/dev/zero` or a huge file under a record name. Every store file this crate reads 109 (`dirs/**/*.json`, `agents/*.json`, `STORE_ID`, and the `.lock` file a mutation opens) goes 110 through one bounded read (`src/record.rs`): 111 112 - `lstat` first: anything that is not a regular file is refused without being opened; 113 - then `open(O_NOFOLLOW | O_NONBLOCK)` and `fstat` the descriptor, refusing anything that is 114 not a regular file (catches a swap between the two steps); 115 - read at most cap + 1 bytes. Caps: `MAX_RECORD_BYTES` = 1 MiB per record (crumb.c records 116 are a few KiB), `MAX_MARKER_BYTES` = 4 KiB for `STORE_ID`. 117 118 A refusal is `CoordError::RefusedRecord { path, reason }` with `reason` one of `Symlink`, 119 `NotRegular("fifo" | "socket" | "char device" | ...)` or `TooLarge { limit }`. It is handled 120 exactly like a corrupt record: the operation fails, nothing is written, the file is left as 121 found, and the D3 pre-submit advisory reports `CoordinationStatus::Unavailable`. The scope is 122 store-wide, because every mutation and `sniff` load every record: a FIFO planted at 123 `dirs/sub/x.json` also fails `claim . other/y.c`. The error names the file; an operator 124 moves it aside to restore the store. Mutations 125 also refuse to rename over a non-regular file and to write a record over the cap; their 126 temporary file is created fresh with `O_EXCL | O_NOFOLLOW`. Directory listing never opens an 127 entry: it uses the entry type, does not walk symlinked directories, and ignores names that 128 do not end in `.json`. 129 130 crumb.c at `29780e5` has the same defect (a FIFO `dirs/*.json` hangs its `sniff` and `claim`); 131 that fix belongs in aien-architecture and is out of scope here. 132 133 ## What coordination state is not 134 135 Coordination state is ephemeral. It is **never written into Synapse history**, is **never an 136 evidence receipt**, and is **never an authority**: a claim is advisory, it does not grant 137 publication or merge rights (AEGIS stays the sole publication authority). Nothing in this 138 crate touches `synapse-store`, changesets or refs. 139 140 ## Known differences and limits 141 142 - No legacy `.crumb.local` import. crumb.c merges a worktree's `.crumb.local` into the store 143 on its next mutation; Synapse workspaces have no `.crumb.local`. Until crumb.c has run once in 144 such a worktree, a legacy lock there is invisible to this crate. 145 - `sniff` lists "other workspaces" from the records themselves (any `worktree` value other 146 than the caller's); crumb.c lists Git worktrees from `git worktree list`, so crumb.c's 147 OTHER WORKTREES section does not list Synapse workspaces (their agents and locks still 148 appear under ACTIVE AGENTS and LOCKS). 149 - Key resolution consults a `PathOracle` for "does this path exist". crumb.c resolves a 150 relative target named from a subdirectory by file existence (`README` from `src` may mean 151 `README` or `src/README`), so with `NoOracle` such targets are refused 152 (`AmbiguousWithoutTree`) instead of guessed: a guess could key one file twice and let two 153 agents hold it. Without a tree, name targets from the root (dir `.`) or by absolute path, 154 or supply an oracle over the snapshot. 155 - Directories are taken as given (normalized), not through `realpath`, so symlinked 156 directories are not resolved the way crumb.c resolves them. 157 - Store files are never followed (#58): a symlinked record is refused and a symlinked 158 directory under `dirs/` is not walked, where crumb.c follows both. A store written by 159 either tool contains neither. 160 - `continuations/` and `ledger/` are created but not used; checkpoint/resume stay in `cc.sh`. 161 162 ## Using it 163 164 ```rust 165 let store = CoordStore::open("/path/beside/synapse/store/crumb/v1"); 166 let ws = Workspace::with_oracle("/synapse/ws/agent-7", 167 Holder::synapse("lane/main", &changeset_hex, &base_hex), Box::new(NoOracle)); 168 match store.claim(&ws, "agent-7", ".", "crates/x/src/lib.rs", "refactor", None)? { 169 ClaimOutcome::Claimed { key } => { /* work */ } 170 ClaimOutcome::Blocked { key, holder } => { /* someone else owns it */ } 171 } 172 ``` 173 174 The `synapse-coord` binary mirrors `crumb claim|update|whisper|close|sniff` lines and exit 175 codes for scripts: `synapse-coord --store DIR --top WS [--synapse LANE REV BASE] claim ...`. 176 177 ## Verification 178 179 - `cargo test -p synapse-coord`: unit tests (JSON layout, ISO time, paths) and 180 `tests/plane.rs` (test.sh claim/block/close, T1-T7, threads and processes racing, 181 crash before rename, torn tmp files, corrupt record refusal, byte layout, history cap) and 182 `tests/identity.rs` (store identity marker: creation, thread and process race, mismatch and 183 missing marker refused, recheck per transaction, crash before link, split-root control). 184 - `scripts/crumb-coord-interop.sh [aien-architecture checkout]`: builds crumb.c at ``29780e5`` 185 with `cc` only and runs both tools against one store (I1-I10), checks crumb.c ignores the 186 identity marker (I11), and reproduces then catches the split-root case (I12). 187 188 ## Mission message board (issue #83) 189 190 `synapse_coord::board` (CLI `synapse-coord board ...`) is a separate, durable per-mission 191 board for agent findings, questions, answers and handoffs: one fsynced journal (group 192 commit: concurrent posts share their flushes) with a 64-byte commit table, per-topic and per-addressee id indexes, tag registration 193 (`board register `; addressing only, never authentication), subscriptions, per-tag 194 cursors with at-least-once delivery, and best-effort wake datagrams so a waiting agent does 195 not poll. It lives under its own root with its own `BOARD_ID` and changes nothing in the 196 coordination store's records or verbs. Board content is untrusted data. Design, crash rules 197 and CLI: [`docs/SWARM_BOARD.md`](../../docs/SWARM_BOARD.md). Tests: 198 `tests/board_core.rs`, `tests/board_cli.rs`, `tests/durability.rs`. 199 200 ## Migration 201 202 This crate is existing Rust. Under the pure-Omega directive (rule 3) it receives only 203 minimal fixes of production defects, such as the board durability repairs of crumb924 204 (aien-sovereign-core-mv#928 review rounds), and no new features, verbs or dependencies. 205 Its successor is an Omega (`.om`) board for the swarm-bridge port: `om/swarm-bridge` in 206 aien-sovereign-core-mv (crumb924), tracked in Linear DRA-460 (follow-up of DRA-97). The board's recovery contract and the 207 regressions in `tests/durability.rs` are the behaviour that successor must reproduce.