@junghanacs/entwurf 0.12.8 → 0.12.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/AGENTS.md +4 -4
  2. package/CHANGELOG.md +20 -1
  3. package/DELIVERY.md +1 -1
  4. package/README.md +122 -10
  5. package/demo/README.md +2 -2
  6. package/docs/setup-clean-host.md +14 -3
  7. package/mcp/entwurf-bridge/dist/mcp/entwurf-bridge/src/index.js +9 -15
  8. package/mcp/entwurf-bridge/dist/pi-extensions/lib/acp/models.js +12 -12
  9. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-fact-provider.js +1 -1
  10. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-v2-production.js +5 -2
  11. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-v2-spawn-production.js +8 -2
  12. package/mcp/entwurf-bridge/dist/pi-extensions/lib/meta-sender-identity.js +15 -4
  13. package/mcp/entwurf-bridge/dist/pi-extensions/lib/meta-session.js +483 -34
  14. package/mcp/entwurf-bridge/dist/pi-extensions/meta-bridge-hook.js +8 -3
  15. package/mcp/entwurf-bridge/dist/scripts/agy-imprint.js +14 -2
  16. package/mcp/entwurf-bridge/dist/scripts/meta-bridge-fresh-cut.js +155 -29
  17. package/mcp/entwurf-bridge/src/index.ts +10 -12
  18. package/package.json +7 -7
  19. package/pi-extensions/entwurf-control.ts +12 -12
  20. package/pi-extensions/lib/acp/models.ts +12 -12
  21. package/pi-extensions/lib/entwurf-fact-provider.ts +9 -2
  22. package/pi-extensions/lib/entwurf-v2-production.ts +8 -2
  23. package/pi-extensions/lib/entwurf-v2-spawn-production.ts +8 -2
  24. package/pi-extensions/lib/meta-sender-identity.ts +15 -5
  25. package/pi-extensions/lib/meta-session.ts +526 -38
  26. package/pi-extensions/meta-bridge-hook.ts +8 -2
  27. package/run.sh +30 -26
  28. package/scripts/agy-imprint.ts +15 -1
  29. package/scripts/check-acp-session-reuse.ts +1 -1
  30. package/scripts/check-acp-session-store.ts +3 -3
  31. package/scripts/check-agy-sender-identity.ts +83 -0
  32. package/scripts/check-entwurf-control-rpc.ts +2 -2
  33. package/scripts/check-entwurf-fact-provider.ts +9 -1
  34. package/scripts/check-entwurf-facts.ts +1 -1
  35. package/scripts/check-entwurf-mailbox-guard.ts +6 -2
  36. package/scripts/check-entwurf-resume-args.ts +6 -6
  37. package/scripts/check-entwurf-session-identity.ts +7 -6
  38. package/scripts/check-entwurf-v2-production.ts +4 -2
  39. package/scripts/check-entwurf-v2-spawn-production.ts +2 -2
  40. package/scripts/check-fresh-cut-gate.sh +305 -4
  41. package/scripts/check-meta-identity-consumers.ts +501 -1
  42. package/scripts/check-meta-listing.ts +91 -9
  43. package/scripts/check-meta-receiver-marker.ts +54 -0
  44. package/scripts/check-model-lock.ts +1 -1
  45. package/scripts/meta-bridge-fresh-cut.ts +164 -28
  46. package/scripts/pi_settings_io.py +65 -0
  47. package/scripts/register-pi-package.py +183 -37
  48. package/scripts/register-pi-provider.py +68 -10
  49. package/scripts/smoke-acp-socket-citizen-live.ts +2 -2
  50. package/scripts/smoke-meta-install-state.sh +1 -1
  51. package/scripts/smoke-pi-attach.ts +7 -2
  52. package/scripts/smoke-user-scope-citizen.sh +177 -0
@@ -195,6 +195,60 @@ export const FRESH_CUT_COMMAND_INSTALLED = "entwurf meta-bridge-fresh-cut";
195
195
  * (never replaces) the `FRESH_CUT_COMMAND` substring the gates assert.
196
196
  */
197
197
  export const FRESH_CUT_PRESCRIPTION = `\`${FRESH_CUT_COMMAND}\` (from an installed package: \`${FRESH_CUT_COMMAND_INSTALLED}\`)`;
198
+ /**
199
+ * THE fresh-cut EXIT CONTRACT (#54) — the store doctor's `0/1/2/3` has a sibling here.
200
+ *
201
+ * The cut used to answer `1` for three world-states that are not each other, and the
202
+ * documented chain `fresh-cut && setup` therefore stopped on all of them alike. What
203
+ * distinguishes them is not severity, it is **what already moved**:
204
+ *
205
+ * - `COMPLETE` (0) — the generation is archived (or there was none), the fresh v3
206
+ * store is open, and every dead/refuted marker and socket is gone. `&& setup` is
207
+ * exactly right here.
208
+ * - `NO_MOVE` (1) — the cut REFUSED before touching anything: a live or unprovable
209
+ * surface, an occupied archive destination, a surface that could not be read or
210
+ * planned, or a first rename that failed. The host is what it was; fix the named
211
+ * cause and re-run the same command. Nothing downstream may proceed, because the
212
+ * store the install refused is still there.
213
+ * - `USAGE` (2) — the operator asked for something this verb does not have. Same
214
+ * number the `-h` path and the store doctor use, so a wrapper never has to learn a
215
+ * second convention.
216
+ * - `HALF_CUT` (3) — a failure arrived AFTER at least one archive move, so the cut
217
+ * transition is incomplete and the fresh generation is not confirmed open. This
218
+ * state wants inspection before anything else runs; a re-run can finish the cut
219
+ * under its own stamp.
220
+ * - `CLEANUP_INCOMPLETE` (4) — the cut IS done: the generation moved, the fresh
221
+ * generation is open, install and citizen birth are no longer blocked by the
222
+ * store. What survived is disposable process state (marker/socket residue) that
223
+ * could not be unlinked. A runbook may run `setup` here but may not call the host
224
+ * clean. Re-running fresh-cut is safe only before a new citizen is born; after
225
+ * that, repair the named residue manually rather than archiving the new generation.
226
+ *
227
+ * Still fail-closed: only `COMPLETE` is zero. #54 asked for the states to become
228
+ * distinguishable, not for cleanup failure to become success.
229
+ *
230
+ * Frozen numbers. A caller — a shell runbook, CI, another agent — reads these, so
231
+ * renumbering is a breaking change to every chain that branches on them.
232
+ */
233
+ export const FRESH_CUT_EXIT = {
234
+ COMPLETE: 0,
235
+ NO_MOVE: 1,
236
+ USAGE: 2,
237
+ HALF_CUT: 3,
238
+ CLEANUP_INCOMPLETE: 4,
239
+ };
240
+ /**
241
+ * The mid-cut verdict, as a function rather than a branch, so the distinction #54 is
242
+ * about can be EXECUTED by a gate instead of grepped for.
243
+ *
244
+ * A rename that fails is not one event: if nothing had moved yet it is a refusal that
245
+ * happens to arrive late ({@link FRESH_CUT_EXIT.NO_MOVE} — the host is untouched), and
246
+ * if something had, it is a genuine {@link FRESH_CUT_EXIT.HALF_CUT}. The old code said
247
+ * both of those in prose and neither of them in its exit status.
248
+ */
249
+ export function midCutExit(archivedCount) {
250
+ return archivedCount === 0 ? FRESH_CUT_EXIT.NO_MOVE : FRESH_CUT_EXIT.HALF_CUT;
251
+ }
198
252
  /** The uniform "this record is not a live-generation v3 record" error, naming the fresh-cut fix. */
199
253
  function nonV3RecordMessage(version) {
200
254
  return (`meta-record "schemaVersion" must be ${META_SCHEMA_VERSION_V3} (got ${describe(version)}). ` +
@@ -594,27 +648,106 @@ export function certifyActiveStore(entries, readRecord) {
594
648
  * the doctor and the install preflight call an unreadable host clean (2026-07-25
595
649
  * fresh-eyes review; `existsSync` returns false for a directory it merely cannot search,
596
650
  * which is the same laundering {@link inspectRecordEntry} refuses on the targeted path).
651
+ *
652
+ * Split out of {@link certifyActiveStoreDir} so that EVERY store-wide scan in this repo
653
+ * — the certification, the `entwurf_peers` listing, the rival scan — gets its entries
654
+ * from one function that carries the ENTRY KIND. A binding that does its own
655
+ * `readdir()` gets names only, so the next thing it does is `readFileSync`, and rule 1
656
+ * ("a symlink is refused, never followed — its bytes live where this store has no
657
+ * ownership") quietly stops holding on that surface. That is not hypothetical: both
658
+ * `entwurf_peers` bindings hand-rolled exactly that readdir, and the #52 duplicate pass
659
+ * then let a symlink pointing at foreign bytes quarantine a healthy regular record.
660
+ * The rule has to be structural, not remembered at each call site — the same lesson
661
+ * `pi_settings_io` learned about the settings writers.
597
662
  */
598
- export function certifyActiveStoreDir(dir) {
663
+ export function readActiveStoreEntries(dir) {
599
664
  const resolved = path.resolve(expandTilde(dir));
600
665
  let dirents;
601
666
  try {
602
667
  dirents = fs.readdirSync(resolved, { withFileTypes: true });
603
668
  }
604
669
  catch (err) {
605
- if (err.code === "ENOENT") {
606
- return { dir: resolved, scanned: 0, records: [], defects: [] };
607
- }
670
+ if (err.code === "ENOENT")
671
+ return [];
608
672
  throw new MetaRecordError(`cannot read the meta-record store ${resolved}: ${err instanceof Error ? err.message : String(err)}. ` +
609
673
  "That is a failure to inspect the store, not an empty store — refusing to certify a store this " +
610
674
  "process cannot read.");
611
675
  }
612
- const entries = dirents
676
+ return dirents
613
677
  .sort((a, b) => a.name.localeCompare(b.name))
614
678
  .map((entry) => ({ filename: entry.name, regularFile: entry.isFile() }));
679
+ }
680
+ /** The errno {@link readStoreRecordFile} raises for an entry whose OPEN succeeded but
681
+ * whose file description is not a regular file — a directory, a fifo, a device. There is
682
+ * no operating-system errno for "you opened the wrong KIND of thing", so this is a
683
+ * synthesized one; every real errno is passed through untouched. */
684
+ export const NOT_REGULAR_ENTRY_CODE = "ENTWURF_ENOTREG";
685
+ const O_NOFOLLOW_FLAG = typeof fs.constants.O_NOFOLLOW === "number" ? fs.constants.O_NOFOLLOW : 0;
686
+ const O_NONBLOCK_FLAG = typeof fs.constants.O_NONBLOCK === "number" ? fs.constants.O_NONBLOCK : 0;
687
+ /**
688
+ * Read a record's bytes with the entry KIND decided on the very file description the
689
+ * read will use.
690
+ *
691
+ * `lstat`-then-`readFileSync(path)` classifies one entry and reads another. Between
692
+ * those two syscalls the final path component can be replaced by a symlink, and the read
693
+ * then follows it into bytes the store does not own — rule 1 laundered by a race rather
694
+ * than by a missing check (2026-07-26 cross-review). A path looked up twice cannot hold
695
+ * the rule; one open file description can:
696
+ *
697
+ * `O_NOFOLLOW` — a symlink at the FINAL component fails the OPEN with `ELOOP`, so
698
+ * foreign bytes are refused before one of them is read. Intermediate
699
+ * components resolve as they always have: the shape of the store
700
+ * DIRECTORY is a separate question, and this seam does not widen into
701
+ * it.
702
+ * `O_NONBLOCK` — opening a fifo `O_RDONLY` BLOCKS until some writer appears, so a
703
+ * named pipe dropped in the store would hang every scan on a host where
704
+ * nobody is writing. Classify-then-open never had that window; this flag
705
+ * is what buys it back. It is a no-op for regular files, and it does not
706
+ * decide anything — the fstat below is what refuses the fifo.
707
+ * `fstat(fd)` — the kind of THIS description, not of a name. A directory opens fine on
708
+ * Linux, so without it the refusal would arrive later as a stranger
709
+ * errno from the read.
710
+ *
711
+ * Errno is deliberately NOT flattened here. The callers separate raced-away (`ENOENT`)
712
+ * from unreadable (`EACCES`) from refused (`ELOOP`), and a wrapper that turned all three
713
+ * into one `MetaRecordError` would silently kill the rival scan's raced-away skip — the
714
+ * loudest possible regression, since every concurrent birth would then refuse dispatch.
715
+ * Shaping a message is the job of the caller that knows what the answer is FOR.
716
+ */
717
+ export function readStoreRecordFile(file) {
718
+ if (O_NOFOLLOW_FLAG === 0) {
719
+ throw new MetaRecordError(`cannot read meta-record ${path.basename(file)} safely: this platform exposes no O_NOFOLLOW, so a record ` +
720
+ "read cannot refuse a symlink swapped in at the final component. entwurf certifies Linux only.");
721
+ }
722
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | O_NOFOLLOW_FLAG | O_NONBLOCK_FLAG);
723
+ try {
724
+ if (!fs.fstatSync(fd).isFile()) {
725
+ const err = new Error(`meta-record ${path.basename(file)} is not a regular file (directory/fifo/device) — a record's bytes ` +
726
+ "must live in the store itself, so this entry is never read.");
727
+ err.code = NOT_REGULAR_ENTRY_CODE;
728
+ throw err;
729
+ }
730
+ return fs.readFileSync(fd, "utf8");
731
+ }
732
+ finally {
733
+ fs.closeSync(fd);
734
+ }
735
+ }
736
+ /** The reader every store-WIDE scan pairs with {@link readActiveStoreEntries}. The
737
+ * caller's entry kind decides the POLICY — whether a non-regular entry is a defect
738
+ * (certification), a diagnostic (listing) or a non-candidate (the rival scan) — because
739
+ * only the caller knows that. What the caller cannot know is whether the entry is still
740
+ * that kind at the instant of the read, so {@link readStoreRecordFile} re-decides it on
741
+ * the fd and refuses there. Snapshot kind for the verdict, fd kind for the bytes. */
742
+ export function makeStoreRecordReader(dir) {
743
+ const resolved = path.resolve(expandTilde(dir));
744
+ return (filename) => readStoreRecordFile(path.join(resolved, filename));
745
+ }
746
+ export function certifyActiveStoreDir(dir) {
747
+ const resolved = path.resolve(expandTilde(dir));
615
748
  return {
616
749
  dir: resolved,
617
- ...certifyActiveStore(entries, (filename) => fs.readFileSync(path.join(resolved, filename), "utf8")),
750
+ ...certifyActiveStore(readActiveStoreEntries(resolved), makeStoreRecordReader(resolved)),
618
751
  };
619
752
  }
620
753
  /**
@@ -639,6 +772,25 @@ export function activeStoreRefusal(cert, shown = 3) {
639
772
  .join("\n ");
640
773
  return (`${headline}\n ${head}` + (cert.defects.length > shown ? `\n … and ${cert.defects.length - shown} more` : ""));
641
774
  }
775
+ /**
776
+ * Group already-parsed identities by the id that must be unique across a store.
777
+ * Insertion-ordered (Map), so every consumer reports rivals in the order it read them.
778
+ *
779
+ * Keeps the listing's duplicate pass deterministic and separate from its quarantine
780
+ * loop. Certification and the addressable read apply the same `nativeSessionId` equality
781
+ * rule at different granularities, but do not call this listing-specific grouping helper.
782
+ */
783
+ function groupByNativeSessionId(identities) {
784
+ const byNative = new Map();
785
+ for (const identity of identities) {
786
+ const seen = byNative.get(identity.nativeSessionId);
787
+ if (seen)
788
+ seen.push(identity);
789
+ else
790
+ byNative.set(identity.nativeSessionId, [identity]);
791
+ }
792
+ return byNative;
793
+ }
642
794
  /**
643
795
  * Scan every meta-record in a store into identities + explicit read errors.
644
796
  * Pure over injected (entries, readRecord) so gates drive it without IO; the
@@ -653,15 +805,37 @@ export function activeStoreRefusal(cert, shown = 3) {
653
805
  * is impossible: the filename IS `<gardenId>.meta.json`, so the filesystem
654
806
  * already enforces uniqueness — only body/filename drift can split authority.
655
807
  *
808
+ * It takes {@link ActiveStoreEntry} — filename PLUS kind — for the same reason the
809
+ * certification does: rule 1 says a symlinked record is refused and NEVER FOLLOWED, and
810
+ * a scan handed bare names cannot obey that, because the only thing it can do next is
811
+ * read the path. Both `entwurf_peers` bindings used to hand-roll a name-only readdir,
812
+ * so this surface read foreign bytes through a symlink while the doctor refused the
813
+ * same entry — one store, two contracts again. A non-regular entry is now a diagnostic
814
+ * whose bytes are never touched.
815
+ *
816
+ * Store-wide UNIQUENESS of `nativeSessionId` is enforced here as well (#52) — free,
817
+ * because this function already reads the whole store. See the loop below for why both
818
+ * rivals become errors rather than one becoming a winner.
819
+ *
656
820
  * mode "collect" (default) returns partial results; "strict" throws if ANY
657
821
  * record was unreadable (doctor / gate callers wanting all-or-nothing).
658
822
  */
659
823
  export function listAllMetaIdentities(entries, readRecord, opts = {}) {
660
824
  const identities = [];
661
825
  const errors = [];
662
- for (const filename of entries) {
826
+ for (const entry of entries) {
827
+ const filename = entry.filename;
663
828
  if (!filename.endsWith(".meta.json"))
664
829
  continue;
830
+ if (!entry.regularFile) {
831
+ errors.push({
832
+ filename,
833
+ message: "not a regular file (symlink/directory/special) — a record's bytes must live in the store " +
834
+ "itself, so this entry is never followed and cannot name a citizen. Inspect and remove it by " +
835
+ `hand, or archive the generation with ${FRESH_CUT_PRESCRIPTION}.`,
836
+ });
837
+ continue;
838
+ }
665
839
  let identity;
666
840
  try {
667
841
  identity = parseMetaIdentity(readRecord(filename));
@@ -682,6 +856,34 @@ export function listAllMetaIdentities(entries, readRecord, opts = {}) {
682
856
  }
683
857
  identities.push(identity);
684
858
  }
859
+ // Rule 4 of {@link certifyActiveStore}, enforced HERE too (#52). This scan already
860
+ // holds every record in its hand, so uniqueness costs NOTHING to check — and a
861
+ // facts surface that reports two records claiming one `nativeSessionId` as two
862
+ // healthy citizens is describing a store the doctor calls uncertifiable as clean.
863
+ // That is the sharpest form of the gap: not a missing guard, a WRONG FACT.
864
+ //
865
+ // Both rivals leave `identities` and become errors, never one winner: the store
866
+ // genuinely cannot say which record owns that session, so picking either would
867
+ // mint the authority the certification refuses to mint. Everyone else keeps
868
+ // listing — the same rule an unreadable record follows, because one broken pair
869
+ // must not blind `entwurf_peers` (the 0.10 lesson).
870
+ for (const [nativeSessionId, holders] of groupByNativeSessionId(identities)) {
871
+ if (holders.length < 2)
872
+ continue;
873
+ const files = holders.map((h) => metaRecordFilename(h));
874
+ for (const holder of holders) {
875
+ const index = identities.indexOf(holder);
876
+ if (index >= 0)
877
+ identities.splice(index, 1);
878
+ errors.push({
879
+ filename: metaRecordFilename(holder),
880
+ message: `duplicate nativeSessionId ${JSON.stringify(nativeSessionId)} — also claimed by ` +
881
+ `${files.filter((f) => f !== metaRecordFilename(holder)).join(", ")}. The native→garden mapping ` +
882
+ `must be unique; this store cannot say which record owns that session, so NEITHER is listed as ` +
883
+ `a citizen. Archive the generation with ${FRESH_CUT_PRESCRIPTION}.`,
884
+ });
885
+ }
886
+ }
685
887
  if (opts.mode === "strict" && errors.length > 0) {
686
888
  throw new MetaRecordError(`listAllMetaIdentities(strict): ${errors.length} unreadable meta-record(s): ${errors
687
889
  .map((e) => `${e.filename} (${e.message})`)
@@ -912,6 +1114,80 @@ export function startKeyScheme(key) {
912
1114
  return "ps";
913
1115
  return null;
914
1116
  }
1117
+ /**
1118
+ * CAN this pid own a native session at all? — the question one layer ABOVE
1119
+ * {@link classifyMarkerOwner}, and the one no marker consumer used to ask.
1120
+ *
1121
+ * `classifyMarkerOwner` answers "is the process this marker NAMES still the one
1122
+ * running", and for pid 1 the honest answer is YES: init is up for as long as the
1123
+ * host is, and its start-key does not change while it runs. So an `ownerPid: 1`
1124
+ * marker classifies `live` for the whole boot, and — this is the operational
1125
+ * point — THE ACTION THE REFUSAL PRESCRIBES CANNOT CHANGE THAT. Quiescing every
1126
+ * session leaves init running under the same start-key, so the operator does the
1127
+ * one thing they were told to do and the cut refuses again. (Deleting the marker
1128
+ * removes the CLAIM; it never refutes the verdict — which is exactly why the
1129
+ * affected host's only way out was a hand `rm`.) A reboot is not a dependable
1130
+ * remedy either: pid 1's key is `linux:<starttime in ticks since boot>` and init
1131
+ * starts within a few ticks, so the recorded value can simply come up again —
1132
+ * there is no contract in either direction, and this is not evidence that it must.
1133
+ * What was MEASURED (#53 A, second Linux host, 2026-07-25) is that the cut stayed
1134
+ * blocked until the file was deleted by hand, while `0.12.8` names that same cut
1135
+ * as the one repair for a pre-v3 store: the documented upgrade path had no in-band
1136
+ * exit. The pure rule is not wrong there; the marker's CLAIM is.
1137
+ *
1138
+ * WHERE SUCH A MARKER COMES FROM — stated at the size of the evidence. After this
1139
+ * fix no writer in THIS tree can mint one, so on a current install it is legacy or
1140
+ * corrupt residue. Legacy has more than one source: the retired shell-form Claude
1141
+ * hook (wrapper shell exits first → hook REPARENTED to init → reads `ppid = 1`),
1142
+ * and the agy imprint, which asked only `> 0` until #53 A and could mint the same
1143
+ * shape through the same reparenting. Corrupt is a real class too — this predicate
1144
+ * also refutes non-integer and unsafe-integer pids, which no writer here has ever
1145
+ * produced, so a foreign or damaged marker is the only way they appear. The ONE
1146
+ * file actually observed was a shell-form Claude hook reparented to init. None of
1147
+ * these is a zombie: a zombie is reaped, its pid is freed, the start-key stops
1148
+ * matching, and the marker resolves itself.
1149
+ *
1150
+ * A pid ≤ 1 is refuted BY CONSTRUCTION, which is why this predicate is shared by
1151
+ * both writers and every reader instead of living at one call site: 0 and
1152
+ * negatives address process GROUPS rather than a process (the rule
1153
+ * {@link probePidExistence} already holds), and on the axis this repo certifies no
1154
+ * native session is owned by init.
1155
+ *
1156
+ * THAT LAST CLAUSE IS A POLICY, NOT A LAW OF PROCESSES. The certified axis is a
1157
+ * Linux desktop/workstation host, where init is the service manager and every
1158
+ * native harness is a descendant of a login session. A container that runs the
1159
+ * harness AS pid 1 is a real shape in the world, and there `ownerPid: 1` would name
1160
+ * a genuine owner — so such a host is simply UNSUPPORTED here and fails CLOSED: the
1161
+ * writers refuse to mint the marker, so the session keeps its meta-record but never
1162
+ * claims reply-addressability, which costs a capability instead of granting a false
1163
+ * identity. Do not read this predicate as "pid 1 can never own anything"; read it as
1164
+ * "this repo does not certify a host where it does". Widening the axis means new
1165
+ * evidence and a new contract, not a quiet loosening of the bound.
1166
+ *
1167
+ * Writers refuse to mint it, readers refuse to honor it, and the cut treats it as
1168
+ * clearable residue rather than an owner claim — a proof of INVALIDITY, which is
1169
+ * stronger than the proof of death the cut already acts on.
1170
+ */
1171
+ export function isPlausibleOwnerPid(pid) {
1172
+ return Number.isSafeInteger(pid) && pid > 1;
1173
+ }
1174
+ /**
1175
+ * The write-side half of {@link isPlausibleOwnerPid}. A marker naming an
1176
+ * impossible owner is not a degraded marker, it is a lie that outlives every
1177
+ * process that could refute it — so minting one THROWS rather than warns, and no
1178
+ * future writer can reintroduce #53 A by forgetting the predicate at its own call
1179
+ * site (both current writers still ask it first, and fail closed in their own
1180
+ * words).
1181
+ */
1182
+ function requireOwnerPid(ownerPid, kind) {
1183
+ if (!isPlausibleOwnerPid(ownerPid)) {
1184
+ throw new Error(`refusing to write a ${kind} marker for owner pid ${ownerPid}: a pid <= 1 cannot own a native session ` +
1185
+ "(pid 1 is init — a reparented orphan is not an owner). Quiescing the sessions, which is what " +
1186
+ "meta-bridge-fresh-cut asks for when it refuses, would not refute such a marker, so it would keep " +
1187
+ "blocking the cut on this host (#53 A).");
1188
+ }
1189
+ return ownerPid;
1190
+ }
915
1191
  /**
916
1192
  * THE rule for "is the process this marker names still the one running?" — the one
917
1193
  * place a `dead` verdict may be produced, so no caller re-derives it from
@@ -983,15 +1259,18 @@ export function metaSenderMarkerPath(backend, ownerPid, sendersDir = defaultMeta
983
1259
  export function writeMetaSenderMarker(opts) {
984
1260
  const backend = requireBackend(opts.backend);
985
1261
  const gardenId = requireGardenId(opts.gardenId);
986
- const file = metaSenderMarkerPath(backend, opts.ownerPid, opts.sendersDir ?? defaultMetaSendersDir());
1262
+ // Refused BEFORE the path is built: an impossible owner must not even leave a
1263
+ // backend directory behind, let alone a marker keyed to its pid.
1264
+ const ownerPid = requireOwnerPid(opts.ownerPid, "sender");
1265
+ const file = metaSenderMarkerPath(backend, ownerPid, opts.sendersDir ?? defaultMetaSendersDir());
987
1266
  fs.mkdirSync(path.dirname(file), { recursive: true });
988
1267
  const marker = {
989
1268
  backend,
990
1269
  gardenId,
991
1270
  nativeSessionId: requireNonEmptyString(opts.nativeSessionId, "nativeSessionId"),
992
1271
  cwd: requireNonEmptyString(opts.cwd, "cwd"),
993
- ownerPid: opts.ownerPid,
994
- ownerStartKey: processStartKey(opts.ownerPid),
1272
+ ownerPid,
1273
+ ownerStartKey: processStartKey(ownerPid),
995
1274
  updatedAt: isoNow(opts.now ?? new Date()),
996
1275
  };
997
1276
  const tmp = `${file}.${crypto.randomBytes(4).toString("hex")}.tmp`;
@@ -1023,13 +1302,19 @@ export function readMetaSenderMarker(opts) {
1023
1302
  ownerStartKey: requireNonEmptyString(raw.ownerStartKey, "ownerStartKey"),
1024
1303
  updatedAt: requireNonEmptyString(raw.updatedAt, "updatedAt"),
1025
1304
  };
1305
+ // Plausibility comes FIRST and is never opt-out: it is a property of the CLAIM,
1306
+ // not of the owner's current state, so `verifyOwner: false` (inspection) does not
1307
+ // reach past it either. An `ownerPid: 1` marker is a reparented orphan's residue
1308
+ // and would otherwise keep granting a dead citizen's sender identity for as long
1309
+ // as the host is up — the pid-reuse guard cannot catch it, because init IS still
1310
+ // the same process (#53 A). This also subsumes the old `Number.isInteger` check.
1311
+ if (!isPlausibleOwnerPid(marker.ownerPid))
1312
+ return null;
1026
1313
  // pid-reuse guard (unless explicitly disabled): the owner pid must STILL be
1027
1314
  // the same process that wrote the marker. A bare pid is reused; pid+startKey
1028
1315
  // is boot-unique, so a stale marker from a dead session fails here instead of
1029
1316
  // granting a wrong-identity send.
1030
1317
  if (opts.verifyOwner !== false) {
1031
- if (!Number.isInteger(marker.ownerPid))
1032
- return null;
1033
1318
  const liveKey = processStartKey(marker.ownerPid);
1034
1319
  if (!liveKey || liveKey !== marker.ownerStartKey)
1035
1320
  return null;
@@ -1062,14 +1347,15 @@ export function metaReceiverMarkerPath(gardenId, receiversDir = defaultMetaRecei
1062
1347
  export function writeMetaReceiverMarker(opts) {
1063
1348
  const gardenId = requireGardenId(opts.gardenId);
1064
1349
  const backend = requireBackend(opts.backend);
1350
+ const ownerPid = requireOwnerPid(opts.ownerPid, "receiver");
1065
1351
  const file = metaReceiverMarkerPath(gardenId, opts.receiversDir ?? defaultMetaReceiversDir());
1066
1352
  fs.mkdirSync(path.dirname(file), { recursive: true });
1067
1353
  const marker = {
1068
1354
  gardenId,
1069
1355
  backend,
1070
1356
  nativeSessionId: requireNonEmptyString(opts.nativeSessionId, "nativeSessionId"),
1071
- ownerPid: opts.ownerPid,
1072
- ownerStartKey: processStartKey(opts.ownerPid),
1357
+ ownerPid,
1358
+ ownerStartKey: processStartKey(ownerPid),
1073
1359
  ownerKind: requireNonEmptyString(opts.ownerKind ?? "claude-code-cli", "ownerKind"),
1074
1360
  armProvenance: requireArmProvenance(opts.armProvenance),
1075
1361
  updatedAt: isoNow(opts.now ?? new Date()),
@@ -1106,9 +1392,12 @@ export function readMetaReceiverMarker(opts) {
1106
1392
  armProvenance: requireArmProvenance(raw.armProvenance),
1107
1393
  updatedAt: requireNonEmptyString(raw.updatedAt, "updatedAt"),
1108
1394
  };
1395
+ // Same rule as the sender marker, and for the same reason one layer over: an
1396
+ // impossible owner is not a live one, so a refuted marker must never read back
1397
+ // as an ACTIVE RECEIVER and pull the mailbox rail into delivering to a void.
1398
+ if (!isPlausibleOwnerPid(marker.ownerPid))
1399
+ return null;
1109
1400
  if (opts.verifyOwner !== false) {
1110
- if (!Number.isInteger(marker.ownerPid))
1111
- return null;
1112
1401
  const liveKey = processStartKey(marker.ownerPid);
1113
1402
  if (!liveKey || liveKey !== marker.ownerStartKey)
1114
1403
  return null;
@@ -1202,11 +1491,32 @@ function inspectRecordEntry(file) {
1202
1491
  catch (err) {
1203
1492
  if (err.code === "ENOENT")
1204
1493
  return "absent";
1205
- throw new MetaRecordError(`cannot inspect meta-record ${path.basename(file)} under ${path.dirname(file)}: ` +
1206
- `${err instanceof Error ? err.message : String(err)}. That is an inspection failure, not an absent ` +
1207
- `citizen — refusing to report "no record" from a store this process cannot read.`);
1494
+ throw recordInspectionFailure(file, err);
1208
1495
  }
1209
1496
  }
1497
+ export function classifyRecordReadFailure(code) {
1498
+ if (code === "ENOENT")
1499
+ return "absent";
1500
+ if (code === "ELOOP" || code === "ENXIO" || code === NOT_REGULAR_ENTRY_CODE)
1501
+ return "irregular";
1502
+ return "unreadable";
1503
+ }
1504
+ /** The three refusals a targeted read can reach from EITHER layer — the settled
1505
+ * classification or a raced read. One text each, so a race and a quiet store say the same
1506
+ * sentence to the operator. */
1507
+ function recordInspectionFailure(file, err) {
1508
+ return new MetaRecordError(`cannot inspect meta-record ${path.basename(file)} under ${path.dirname(file)}: ` +
1509
+ `${err instanceof Error ? err.message : String(err)}. That is an inspection failure, not an absent ` +
1510
+ `citizen — refusing to report "no record" from a store this process cannot read.`);
1511
+ }
1512
+ function absentRecordRefusal(id, file) {
1513
+ return new MetaRecordError(`no meta-record for garden id "${id}" under ${path.dirname(file)} — not a garden citizen, cannot deliver.`);
1514
+ }
1515
+ function irregularRecordRefusal(id) {
1516
+ return new MetaRecordError(`meta-record ${id}.meta.json is not a regular file (symlink/directory/special) — a record's bytes must ` +
1517
+ `live in the store itself, so this entry is never followed and cannot address a citizen. ` +
1518
+ `Inspect and remove it by hand, or archive the generation with ${FRESH_CUT_PRESCRIPTION}.`);
1519
+ }
1210
1520
  /**
1211
1521
  * The identity read-by-gardenId. Read the file, body is SSOT, fail-fast on
1212
1522
  * body/filename gardenId drift; V3-only via parseMetaIdentity (an unreadable
@@ -1216,22 +1526,48 @@ function inspectRecordEntry(file) {
1216
1526
  export function readMetaIdentityByGardenId(gardenId, sessionsDir = defaultMetaSessionsDir()) {
1217
1527
  const id = requireGardenId(gardenId);
1218
1528
  const file = recordFileFor(sessionsDir, id);
1529
+ // TWO LAYERS, AND THEY ARE NOT THE SAME RULE TWICE.
1530
+ //
1531
+ // Layer 1 — POLICY, on a settled store. Rule 1 of {@link certifyActiveStore}, enforced
1532
+ // HERE too, because this is the one place a live dispatch reads a record. Certifying
1533
+ // the store on WRITE while this read followed the link made the contract true only
1534
+ // where nobody was being addressed: the doctor refused a symlinked entry that v2
1535
+ // dispatch, `entwurf_self` and the sender-marker trust all resolved happily, from bytes
1536
+ // the store does not own (2026-07-25 fresh-eyes review). It classifies WITHOUT OPENING,
1537
+ // which is the point — a socket, a device, a mode-000 directory each earn the
1538
+ // certification's own sentence instead of whatever errno an `open` would have tripped
1539
+ // over (ENXIO, EACCES), and nothing special is opened to find out what it is. Deleting
1540
+ // this layer in favour of the fd alone looked like removing a duplicate enforcement
1541
+ // point and was actually a regression on all three shapes (2026-07-26 cross-review,
1542
+ // round 3 — found by GPT, reproduced here).
1543
+ //
1544
+ // Layer 2 — the RACE, on the bytes actually returned. A verdict about a name stops
1545
+ // being true the moment something replaces what the name points at, so the read
1546
+ // re-decides on its own fd. Its errno verdicts collapse onto layer 1's sentences via
1547
+ // {@link classifyRecordReadFailure}, which is pure so that the branches stay provable:
1548
+ // with layer 1 in front of it, no settled store can reach them.
1219
1549
  const kind = inspectRecordEntry(file);
1220
- if (kind === "absent") {
1221
- throw new MetaRecordError(`no meta-record for garden id "${id}" under ${path.dirname(file)} — not a garden citizen, cannot deliver.`);
1222
- }
1223
- // Rule 1 of {@link certifyActiveStore}, enforced HERE too — the one place a live
1224
- // dispatch reads a record. Certifying the store on WRITE while this read followed the
1225
- // link made the contract true only where nobody was being addressed: the doctor
1226
- // refused a symlinked entry that v2 dispatch, `entwurf_self` and the sender-marker
1227
- // trust all resolved happily, from bytes the store does not own (2026-07-25
1228
- // fresh-eyes review). One contract means both directions hold it.
1229
- if (kind === "irregular") {
1230
- throw new MetaRecordError(`meta-record ${id}.meta.json is not a regular file (symlink/directory/special) — a record's bytes must ` +
1231
- `live in the store itself, so this entry is never followed and cannot address a citizen. ` +
1232
- `Inspect and remove it by hand, or archive the generation with ${FRESH_CUT_PRESCRIPTION}.`);
1233
- }
1234
- const identity = parseMetaIdentity(fs.readFileSync(file, "utf8"));
1550
+ if (kind === "absent")
1551
+ throw absentRecordRefusal(id, file);
1552
+ if (kind === "irregular")
1553
+ throw irregularRecordRefusal(id);
1554
+ let raw;
1555
+ try {
1556
+ raw = readStoreRecordFile(file);
1557
+ }
1558
+ catch (err) {
1559
+ if (err instanceof MetaRecordError)
1560
+ throw err;
1561
+ switch (classifyRecordReadFailure(err.code)) {
1562
+ case "absent":
1563
+ throw absentRecordRefusal(id, file);
1564
+ case "irregular":
1565
+ throw irregularRecordRefusal(id);
1566
+ default:
1567
+ throw recordInspectionFailure(file, err);
1568
+ }
1569
+ }
1570
+ const identity = parseMetaIdentity(raw);
1235
1571
  if (identity.gardenId !== id) {
1236
1572
  throw new MetaRecordError(`meta-record body/filename drift: ${id}.meta.json contains gardenId "${identity.gardenId}". ` +
1237
1573
  `The body is the authority; this file is corrupt and a garden-id lookup can never reach it. ` +
@@ -1258,6 +1594,119 @@ export function metaRecordExistsByGardenId(gardenId, sessionsDir = defaultMetaSe
1258
1594
  const id = requireGardenId(gardenId);
1259
1595
  return inspectRecordEntry(recordFileFor(sessionsDir, id)) !== "absent";
1260
1596
  }
1597
+ /**
1598
+ * Pure: which OTHER records in this store claim `identity`'s `nativeSessionId`.
1599
+ * Returns their filenames, sorted; empty means `identity` holds it alone.
1600
+ *
1601
+ * A RIVAL IS A RECORD THAT COULD BE ADDRESSED INSTEAD. That is the whole test, and it
1602
+ * is narrower than "a file whose bytes mention the same id" — three neighbour shapes
1603
+ * are therefore NOT candidates, and skipping them is a claim about reachability, not
1604
+ * leniency:
1605
+ *
1606
+ * - NON-REGULAR (symlink/dir/special): rule 1 of {@link certifyActiveStore} says such
1607
+ * an entry is refused and never followed, because its bytes live where this store
1608
+ * has no ownership. So it is skipped WITHOUT BEING READ — following it to see
1609
+ * whether it "counts" would break the rule in the act of enforcing it, and let a
1610
+ * planted symlink to foreign bytes quarantine a healthy citizen.
1611
+ * - BODY/FILENAME DRIFT: a record whose body names a different garden id is
1612
+ * unreachable by garden-id lookup from either name, so it can never be dispatched
1613
+ * to and cannot compete for an address.
1614
+ * - UNPARSEABLE by the live schema: same reason — no read path can reach it.
1615
+ *
1616
+ * All three are real certification defects, and the certification and the listing both
1617
+ * say so. What they must not do is blind a healthy citizen, which is the 0.10 "corrupt
1618
+ * blocks registration forever" mistake wearing a new hat.
1619
+ *
1620
+ * A CANDIDATE WE COULD NOT READ IS A DIFFERENT ANSWER AND THROWS. A regular
1621
+ * `.meta.json` this process cannot read might be a genuine duplicate; skipping it would
1622
+ * report "holds it alone" from a scan that never asked, which is exactly the vacuous
1623
+ * pass the store-level readdir guard refuses one level up. ENOENT is the one exception
1624
+ * and the one this repo already recognises everywhere (`inspectRecordEntry`, the cut's
1625
+ * socket walk, `clearFiles`): a file that vanished between the readdir and the read is
1626
+ * not in the store, so it holds nothing.
1627
+ *
1628
+ * The identity's OWN file is excluded by filename, not by identity equality: the caller
1629
+ * has already proven body and filename agree, and a rival is by definition a different
1630
+ * file.
1631
+ */
1632
+ export function nativeSessionIdRivals(identity, entries, readRecord) {
1633
+ const own = metaRecordFilename(identity);
1634
+ const rivals = [];
1635
+ for (const entry of entries) {
1636
+ const filename = entry.filename;
1637
+ if (!filename.endsWith(".meta.json") || filename === own)
1638
+ continue;
1639
+ if (!entry.regularFile)
1640
+ continue; // never followed — see rule 1 above
1641
+ let raw;
1642
+ try {
1643
+ raw = readRecord(filename);
1644
+ }
1645
+ catch (err) {
1646
+ if (err.code === "ENOENT")
1647
+ continue; // raced away — holds nothing
1648
+ throw new MetaRecordError(`cannot read meta-record ${filename} while proving that ${own} holds nativeSessionId ` +
1649
+ `${JSON.stringify(identity.nativeSessionId)} alone: ` +
1650
+ `${err instanceof Error ? err.message : String(err)}. That record may be a duplicate, so this ` +
1651
+ `is an unanswered question, not a clean scan — refusing to dispatch at an address this process ` +
1652
+ `cannot certify.`);
1653
+ }
1654
+ let other;
1655
+ try {
1656
+ other = parseMetaIdentity(raw);
1657
+ }
1658
+ catch {
1659
+ continue; // unreachable by the live schema — not an addressable rival
1660
+ }
1661
+ if (metaRecordFilename(other) !== filename)
1662
+ continue; // drifted — unreachable by garden id
1663
+ if (other.nativeSessionId === identity.nativeSessionId)
1664
+ rivals.push(filename);
1665
+ }
1666
+ return rivals.sort();
1667
+ }
1668
+ /**
1669
+ * The read a DISPATCH does (#52) — the targeted read PLUS the store-wide half of the
1670
+ * contract that a targeted read cannot see on its own.
1671
+ *
1672
+ * WHY THIS IS A SECOND FUNCTION AND NOT A CHANGE TO {@link readMetaIdentityByGardenId}:
1673
+ * the cost is real and the README says so out loud — a call-relay does not re-scan the
1674
+ * whole store per message, and the mailbox poke, the sender-marker trust and
1675
+ * `entwurf_self` keep the per-entry half exactly as before. What separates the callers
1676
+ * is not how careful they are, it is what they DO with the answer: these two turn
1677
+ * `nativeSessionId` into an ADDRESS — a native-push injection into a live conversation,
1678
+ * a pi resume against a transcript — and each does it ONCE per dispatch, next to a
1679
+ * socket connect and a process spawn. One readdir there is nothing; the same readdir
1680
+ * per relayed message is the design the store deliberately does not have.
1681
+ *
1682
+ * The failure it prevents is not hypothetical corruption. `upsertMetaSession` certifies
1683
+ * and then writes, which is not a transaction: two concurrent births — two SessionStart
1684
+ * hooks, an `entwurf_register_native` racing an agy imprint — can both read one clean
1685
+ * snapshot and mint DIFFERENT garden ids for one native session. Nothing was ever
1686
+ * corrupted on such a host, and yet both ids would direct-inject the same conversation,
1687
+ * or resume one transcript twice under two per-garden-id locks.
1688
+ *
1689
+ * Fails LOUD, never soft: a duplicate is corruption of the address space, and QB1
1690
+ * reserves the soft `bad-target` answer for a record that is simply ABSENT.
1691
+ */
1692
+ export function readAddressableMetaIdentity(gardenId, sessionsDir = defaultMetaSessionsDir()) {
1693
+ const identity = readMetaIdentityByGardenId(gardenId, sessionsDir);
1694
+ const dir = path.resolve(expandTilde(sessionsDir));
1695
+ // Entries carry their KIND (readActiveStoreEntries), so the rival scan can refuse a
1696
+ // symlinked neighbour without reading it. A bare-name readdir here would have made
1697
+ // rule 1 unenforceable at exactly the surface that turns a record into an address.
1698
+ // A store that cannot be listed throws from there — answering "unique" from a scan
1699
+ // that never happened is the vacuous pass this whole check exists to refuse.
1700
+ const rivals = nativeSessionIdRivals(identity, readActiveStoreEntries(dir), makeStoreRecordReader(dir));
1701
+ if (rivals.length > 0) {
1702
+ throw new MetaRecordError(`meta-record ${metaRecordFilename(identity)} shares nativeSessionId ` +
1703
+ `${JSON.stringify(identity.nativeSessionId)} with ${rivals.join(", ")} — the native→garden mapping ` +
1704
+ `must be unique, so this store cannot say which record owns that session and dispatching at either ` +
1705
+ `garden id would reach the same native session twice. Archive the generation with ` +
1706
+ `${FRESH_CUT_PRESCRIPTION}.`);
1707
+ }
1708
+ return identity;
1709
+ }
1261
1710
  /**
1262
1711
  * Deliver a message body to a garden citizen's mailbox: validate the record
1263
1712
  * exists, write the `.msg` body FIRST, stamp `lastEnqueuedAt`, then poke