@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
@@ -268,6 +268,64 @@ export const FRESH_CUT_COMMAND_INSTALLED = "entwurf meta-bridge-fresh-cut";
268
268
  */
269
269
  export const FRESH_CUT_PRESCRIPTION = `\`${FRESH_CUT_COMMAND}\` (from an installed package: \`${FRESH_CUT_COMMAND_INSTALLED}\`)`;
270
270
 
271
+ /**
272
+ * THE fresh-cut EXIT CONTRACT (#54) — the store doctor's `0/1/2/3` has a sibling here.
273
+ *
274
+ * The cut used to answer `1` for three world-states that are not each other, and the
275
+ * documented chain `fresh-cut && setup` therefore stopped on all of them alike. What
276
+ * distinguishes them is not severity, it is **what already moved**:
277
+ *
278
+ * - `COMPLETE` (0) — the generation is archived (or there was none), the fresh v3
279
+ * store is open, and every dead/refuted marker and socket is gone. `&& setup` is
280
+ * exactly right here.
281
+ * - `NO_MOVE` (1) — the cut REFUSED before touching anything: a live or unprovable
282
+ * surface, an occupied archive destination, a surface that could not be read or
283
+ * planned, or a first rename that failed. The host is what it was; fix the named
284
+ * cause and re-run the same command. Nothing downstream may proceed, because the
285
+ * store the install refused is still there.
286
+ * - `USAGE` (2) — the operator asked for something this verb does not have. Same
287
+ * number the `-h` path and the store doctor use, so a wrapper never has to learn a
288
+ * second convention.
289
+ * - `HALF_CUT` (3) — a failure arrived AFTER at least one archive move, so the cut
290
+ * transition is incomplete and the fresh generation is not confirmed open. This
291
+ * state wants inspection before anything else runs; a re-run can finish the cut
292
+ * under its own stamp.
293
+ * - `CLEANUP_INCOMPLETE` (4) — the cut IS done: the generation moved, the fresh
294
+ * generation is open, install and citizen birth are no longer blocked by the
295
+ * store. What survived is disposable process state (marker/socket residue) that
296
+ * could not be unlinked. A runbook may run `setup` here but may not call the host
297
+ * clean. Re-running fresh-cut is safe only before a new citizen is born; after
298
+ * that, repair the named residue manually rather than archiving the new generation.
299
+ *
300
+ * Still fail-closed: only `COMPLETE` is zero. #54 asked for the states to become
301
+ * distinguishable, not for cleanup failure to become success.
302
+ *
303
+ * Frozen numbers. A caller — a shell runbook, CI, another agent — reads these, so
304
+ * renumbering is a breaking change to every chain that branches on them.
305
+ */
306
+ export const FRESH_CUT_EXIT = {
307
+ COMPLETE: 0,
308
+ NO_MOVE: 1,
309
+ USAGE: 2,
310
+ HALF_CUT: 3,
311
+ CLEANUP_INCOMPLETE: 4,
312
+ } as const;
313
+
314
+ export type FreshCutExit = (typeof FRESH_CUT_EXIT)[keyof typeof FRESH_CUT_EXIT];
315
+
316
+ /**
317
+ * The mid-cut verdict, as a function rather than a branch, so the distinction #54 is
318
+ * about can be EXECUTED by a gate instead of grepped for.
319
+ *
320
+ * A rename that fails is not one event: if nothing had moved yet it is a refusal that
321
+ * happens to arrive late ({@link FRESH_CUT_EXIT.NO_MOVE} — the host is untouched), and
322
+ * if something had, it is a genuine {@link FRESH_CUT_EXIT.HALF_CUT}. The old code said
323
+ * both of those in prose and neither of them in its exit status.
324
+ */
325
+ export function midCutExit(archivedCount: number): typeof FRESH_CUT_EXIT.NO_MOVE | typeof FRESH_CUT_EXIT.HALF_CUT {
326
+ return archivedCount === 0 ? FRESH_CUT_EXIT.NO_MOVE : FRESH_CUT_EXIT.HALF_CUT;
327
+ }
328
+
271
329
  /** The uniform "this record is not a live-generation v3 record" error, naming the fresh-cut fix. */
272
330
  function nonV3RecordMessage(version: unknown): string {
273
331
  return (
@@ -760,28 +818,114 @@ export function certifyActiveStore(
760
818
  * the doctor and the install preflight call an unreadable host clean (2026-07-25
761
819
  * fresh-eyes review; `existsSync` returns false for a directory it merely cannot search,
762
820
  * which is the same laundering {@link inspectRecordEntry} refuses on the targeted path).
821
+ *
822
+ * Split out of {@link certifyActiveStoreDir} so that EVERY store-wide scan in this repo
823
+ * — the certification, the `entwurf_peers` listing, the rival scan — gets its entries
824
+ * from one function that carries the ENTRY KIND. A binding that does its own
825
+ * `readdir()` gets names only, so the next thing it does is `readFileSync`, and rule 1
826
+ * ("a symlink is refused, never followed — its bytes live where this store has no
827
+ * ownership") quietly stops holding on that surface. That is not hypothetical: both
828
+ * `entwurf_peers` bindings hand-rolled exactly that readdir, and the #52 duplicate pass
829
+ * then let a symlink pointing at foreign bytes quarantine a healthy regular record.
830
+ * The rule has to be structural, not remembered at each call site — the same lesson
831
+ * `pi_settings_io` learned about the settings writers.
763
832
  */
764
- export function certifyActiveStoreDir(dir: string): ActiveStoreCertification & { dir: string } {
833
+ export function readActiveStoreEntries(dir: string): ActiveStoreEntry[] {
765
834
  const resolved = path.resolve(expandTilde(dir));
766
835
  let dirents: fs.Dirent[];
767
836
  try {
768
837
  dirents = fs.readdirSync(resolved, { withFileTypes: true });
769
838
  } catch (err) {
770
- if ((err as { code?: unknown }).code === "ENOENT") {
771
- return { dir: resolved, scanned: 0, records: [], defects: [] };
772
- }
839
+ if ((err as { code?: unknown }).code === "ENOENT") return [];
773
840
  throw new MetaRecordError(
774
841
  `cannot read the meta-record store ${resolved}: ${err instanceof Error ? err.message : String(err)}. ` +
775
842
  "That is a failure to inspect the store, not an empty store — refusing to certify a store this " +
776
843
  "process cannot read.",
777
844
  );
778
845
  }
779
- const entries: ActiveStoreEntry[] = dirents
846
+ return dirents
780
847
  .sort((a, b) => a.name.localeCompare(b.name))
781
848
  .map((entry) => ({ filename: entry.name, regularFile: entry.isFile() }));
849
+ }
850
+
851
+ /** The errno {@link readStoreRecordFile} raises for an entry whose OPEN succeeded but
852
+ * whose file description is not a regular file — a directory, a fifo, a device. There is
853
+ * no operating-system errno for "you opened the wrong KIND of thing", so this is a
854
+ * synthesized one; every real errno is passed through untouched. */
855
+ export const NOT_REGULAR_ENTRY_CODE = "ENTWURF_ENOTREG";
856
+
857
+ const O_NOFOLLOW_FLAG = typeof fs.constants.O_NOFOLLOW === "number" ? fs.constants.O_NOFOLLOW : 0;
858
+ const O_NONBLOCK_FLAG = typeof fs.constants.O_NONBLOCK === "number" ? fs.constants.O_NONBLOCK : 0;
859
+
860
+ /**
861
+ * Read a record's bytes with the entry KIND decided on the very file description the
862
+ * read will use.
863
+ *
864
+ * `lstat`-then-`readFileSync(path)` classifies one entry and reads another. Between
865
+ * those two syscalls the final path component can be replaced by a symlink, and the read
866
+ * then follows it into bytes the store does not own — rule 1 laundered by a race rather
867
+ * than by a missing check (2026-07-26 cross-review). A path looked up twice cannot hold
868
+ * the rule; one open file description can:
869
+ *
870
+ * `O_NOFOLLOW` — a symlink at the FINAL component fails the OPEN with `ELOOP`, so
871
+ * foreign bytes are refused before one of them is read. Intermediate
872
+ * components resolve as they always have: the shape of the store
873
+ * DIRECTORY is a separate question, and this seam does not widen into
874
+ * it.
875
+ * `O_NONBLOCK` — opening a fifo `O_RDONLY` BLOCKS until some writer appears, so a
876
+ * named pipe dropped in the store would hang every scan on a host where
877
+ * nobody is writing. Classify-then-open never had that window; this flag
878
+ * is what buys it back. It is a no-op for regular files, and it does not
879
+ * decide anything — the fstat below is what refuses the fifo.
880
+ * `fstat(fd)` — the kind of THIS description, not of a name. A directory opens fine on
881
+ * Linux, so without it the refusal would arrive later as a stranger
882
+ * errno from the read.
883
+ *
884
+ * Errno is deliberately NOT flattened here. The callers separate raced-away (`ENOENT`)
885
+ * from unreadable (`EACCES`) from refused (`ELOOP`), and a wrapper that turned all three
886
+ * into one `MetaRecordError` would silently kill the rival scan's raced-away skip — the
887
+ * loudest possible regression, since every concurrent birth would then refuse dispatch.
888
+ * Shaping a message is the job of the caller that knows what the answer is FOR.
889
+ */
890
+ export function readStoreRecordFile(file: string): string {
891
+ if (O_NOFOLLOW_FLAG === 0) {
892
+ throw new MetaRecordError(
893
+ `cannot read meta-record ${path.basename(file)} safely: this platform exposes no O_NOFOLLOW, so a record ` +
894
+ "read cannot refuse a symlink swapped in at the final component. entwurf certifies Linux only.",
895
+ );
896
+ }
897
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | O_NOFOLLOW_FLAG | O_NONBLOCK_FLAG);
898
+ try {
899
+ if (!fs.fstatSync(fd).isFile()) {
900
+ const err = new Error(
901
+ `meta-record ${path.basename(file)} is not a regular file (directory/fifo/device) — a record's bytes ` +
902
+ "must live in the store itself, so this entry is never read.",
903
+ ) as Error & { code: string };
904
+ err.code = NOT_REGULAR_ENTRY_CODE;
905
+ throw err;
906
+ }
907
+ return fs.readFileSync(fd, "utf8");
908
+ } finally {
909
+ fs.closeSync(fd);
910
+ }
911
+ }
912
+
913
+ /** The reader every store-WIDE scan pairs with {@link readActiveStoreEntries}. The
914
+ * caller's entry kind decides the POLICY — whether a non-regular entry is a defect
915
+ * (certification), a diagnostic (listing) or a non-candidate (the rival scan) — because
916
+ * only the caller knows that. What the caller cannot know is whether the entry is still
917
+ * that kind at the instant of the read, so {@link readStoreRecordFile} re-decides it on
918
+ * the fd and refuses there. Snapshot kind for the verdict, fd kind for the bytes. */
919
+ export function makeStoreRecordReader(dir: string): (filename: string) => string {
920
+ const resolved = path.resolve(expandTilde(dir));
921
+ return (filename: string) => readStoreRecordFile(path.join(resolved, filename));
922
+ }
923
+
924
+ export function certifyActiveStoreDir(dir: string): ActiveStoreCertification & { dir: string } {
925
+ const resolved = path.resolve(expandTilde(dir));
782
926
  return {
783
927
  dir: resolved,
784
- ...certifyActiveStore(entries, (filename) => fs.readFileSync(path.join(resolved, filename), "utf8")),
928
+ ...certifyActiveStore(readActiveStoreEntries(resolved), makeStoreRecordReader(resolved)),
785
929
  };
786
930
  }
787
931
 
@@ -823,6 +967,24 @@ export interface ListIdentitiesResult {
823
967
  errors: MetaRecordReadError[];
824
968
  }
825
969
 
970
+ /**
971
+ * Group already-parsed identities by the id that must be unique across a store.
972
+ * Insertion-ordered (Map), so every consumer reports rivals in the order it read them.
973
+ *
974
+ * Keeps the listing's duplicate pass deterministic and separate from its quarantine
975
+ * loop. Certification and the addressable read apply the same `nativeSessionId` equality
976
+ * rule at different granularities, but do not call this listing-specific grouping helper.
977
+ */
978
+ function groupByNativeSessionId(identities: readonly MetaIdentity[]): Map<string, MetaIdentity[]> {
979
+ const byNative = new Map<string, MetaIdentity[]>();
980
+ for (const identity of identities) {
981
+ const seen = byNative.get(identity.nativeSessionId);
982
+ if (seen) seen.push(identity);
983
+ else byNative.set(identity.nativeSessionId, [identity]);
984
+ }
985
+ return byNative;
986
+ }
987
+
826
988
  /**
827
989
  * Scan every meta-record in a store into identities + explicit read errors.
828
990
  * Pure over injected (entries, readRecord) so gates drive it without IO; the
@@ -837,18 +999,41 @@ export interface ListIdentitiesResult {
837
999
  * is impossible: the filename IS `<gardenId>.meta.json`, so the filesystem
838
1000
  * already enforces uniqueness — only body/filename drift can split authority.
839
1001
  *
1002
+ * It takes {@link ActiveStoreEntry} — filename PLUS kind — for the same reason the
1003
+ * certification does: rule 1 says a symlinked record is refused and NEVER FOLLOWED, and
1004
+ * a scan handed bare names cannot obey that, because the only thing it can do next is
1005
+ * read the path. Both `entwurf_peers` bindings used to hand-roll a name-only readdir,
1006
+ * so this surface read foreign bytes through a symlink while the doctor refused the
1007
+ * same entry — one store, two contracts again. A non-regular entry is now a diagnostic
1008
+ * whose bytes are never touched.
1009
+ *
1010
+ * Store-wide UNIQUENESS of `nativeSessionId` is enforced here as well (#52) — free,
1011
+ * because this function already reads the whole store. See the loop below for why both
1012
+ * rivals become errors rather than one becoming a winner.
1013
+ *
840
1014
  * mode "collect" (default) returns partial results; "strict" throws if ANY
841
1015
  * record was unreadable (doctor / gate callers wanting all-or-nothing).
842
1016
  */
843
1017
  export function listAllMetaIdentities(
844
- entries: readonly string[],
1018
+ entries: readonly ActiveStoreEntry[],
845
1019
  readRecord: (filename: string) => string,
846
1020
  opts: { mode?: "collect" | "strict" } = {},
847
1021
  ): ListIdentitiesResult {
848
1022
  const identities: MetaIdentity[] = [];
849
1023
  const errors: MetaRecordReadError[] = [];
850
- for (const filename of entries) {
1024
+ for (const entry of entries) {
1025
+ const filename = entry.filename;
851
1026
  if (!filename.endsWith(".meta.json")) continue;
1027
+ if (!entry.regularFile) {
1028
+ errors.push({
1029
+ filename,
1030
+ message:
1031
+ "not a regular file (symlink/directory/special) — a record's bytes must live in the store " +
1032
+ "itself, so this entry is never followed and cannot name a citizen. Inspect and remove it by " +
1033
+ `hand, or archive the generation with ${FRESH_CUT_PRESCRIPTION}.`,
1034
+ });
1035
+ continue;
1036
+ }
852
1037
  let identity: MetaIdentity;
853
1038
  try {
854
1039
  identity = parseMetaIdentity(readRecord(filename));
@@ -869,6 +1054,33 @@ export function listAllMetaIdentities(
869
1054
  }
870
1055
  identities.push(identity);
871
1056
  }
1057
+ // Rule 4 of {@link certifyActiveStore}, enforced HERE too (#52). This scan already
1058
+ // holds every record in its hand, so uniqueness costs NOTHING to check — and a
1059
+ // facts surface that reports two records claiming one `nativeSessionId` as two
1060
+ // healthy citizens is describing a store the doctor calls uncertifiable as clean.
1061
+ // That is the sharpest form of the gap: not a missing guard, a WRONG FACT.
1062
+ //
1063
+ // Both rivals leave `identities` and become errors, never one winner: the store
1064
+ // genuinely cannot say which record owns that session, so picking either would
1065
+ // mint the authority the certification refuses to mint. Everyone else keeps
1066
+ // listing — the same rule an unreadable record follows, because one broken pair
1067
+ // must not blind `entwurf_peers` (the 0.10 lesson).
1068
+ for (const [nativeSessionId, holders] of groupByNativeSessionId(identities)) {
1069
+ if (holders.length < 2) continue;
1070
+ const files = holders.map((h) => metaRecordFilename(h));
1071
+ for (const holder of holders) {
1072
+ const index = identities.indexOf(holder);
1073
+ if (index >= 0) identities.splice(index, 1);
1074
+ errors.push({
1075
+ filename: metaRecordFilename(holder),
1076
+ message:
1077
+ `duplicate nativeSessionId ${JSON.stringify(nativeSessionId)} — also claimed by ` +
1078
+ `${files.filter((f) => f !== metaRecordFilename(holder)).join(", ")}. The native→garden mapping ` +
1079
+ `must be unique; this store cannot say which record owns that session, so NEITHER is listed as ` +
1080
+ `a citizen. Archive the generation with ${FRESH_CUT_PRESCRIPTION}.`,
1081
+ });
1082
+ }
1083
+ }
872
1084
  if (opts.mode === "strict" && errors.length > 0) {
873
1085
  throw new MetaRecordError(
874
1086
  `listAllMetaIdentities(strict): ${errors.length} unreadable meta-record(s): ${errors
@@ -1136,6 +1348,84 @@ export function startKeyScheme(key: string): StartKeyScheme | null {
1136
1348
  return null;
1137
1349
  }
1138
1350
 
1351
+ /**
1352
+ * CAN this pid own a native session at all? — the question one layer ABOVE
1353
+ * {@link classifyMarkerOwner}, and the one no marker consumer used to ask.
1354
+ *
1355
+ * `classifyMarkerOwner` answers "is the process this marker NAMES still the one
1356
+ * running", and for pid 1 the honest answer is YES: init is up for as long as the
1357
+ * host is, and its start-key does not change while it runs. So an `ownerPid: 1`
1358
+ * marker classifies `live` for the whole boot, and — this is the operational
1359
+ * point — THE ACTION THE REFUSAL PRESCRIBES CANNOT CHANGE THAT. Quiescing every
1360
+ * session leaves init running under the same start-key, so the operator does the
1361
+ * one thing they were told to do and the cut refuses again. (Deleting the marker
1362
+ * removes the CLAIM; it never refutes the verdict — which is exactly why the
1363
+ * affected host's only way out was a hand `rm`.) A reboot is not a dependable
1364
+ * remedy either: pid 1's key is `linux:<starttime in ticks since boot>` and init
1365
+ * starts within a few ticks, so the recorded value can simply come up again —
1366
+ * there is no contract in either direction, and this is not evidence that it must.
1367
+ * What was MEASURED (#53 A, second Linux host, 2026-07-25) is that the cut stayed
1368
+ * blocked until the file was deleted by hand, while `0.12.8` names that same cut
1369
+ * as the one repair for a pre-v3 store: the documented upgrade path had no in-band
1370
+ * exit. The pure rule is not wrong there; the marker's CLAIM is.
1371
+ *
1372
+ * WHERE SUCH A MARKER COMES FROM — stated at the size of the evidence. After this
1373
+ * fix no writer in THIS tree can mint one, so on a current install it is legacy or
1374
+ * corrupt residue. Legacy has more than one source: the retired shell-form Claude
1375
+ * hook (wrapper shell exits first → hook REPARENTED to init → reads `ppid = 1`),
1376
+ * and the agy imprint, which asked only `> 0` until #53 A and could mint the same
1377
+ * shape through the same reparenting. Corrupt is a real class too — this predicate
1378
+ * also refutes non-integer and unsafe-integer pids, which no writer here has ever
1379
+ * produced, so a foreign or damaged marker is the only way they appear. The ONE
1380
+ * file actually observed was a shell-form Claude hook reparented to init. None of
1381
+ * these is a zombie: a zombie is reaped, its pid is freed, the start-key stops
1382
+ * matching, and the marker resolves itself.
1383
+ *
1384
+ * A pid ≤ 1 is refuted BY CONSTRUCTION, which is why this predicate is shared by
1385
+ * both writers and every reader instead of living at one call site: 0 and
1386
+ * negatives address process GROUPS rather than a process (the rule
1387
+ * {@link probePidExistence} already holds), and on the axis this repo certifies no
1388
+ * native session is owned by init.
1389
+ *
1390
+ * THAT LAST CLAUSE IS A POLICY, NOT A LAW OF PROCESSES. The certified axis is a
1391
+ * Linux desktop/workstation host, where init is the service manager and every
1392
+ * native harness is a descendant of a login session. A container that runs the
1393
+ * harness AS pid 1 is a real shape in the world, and there `ownerPid: 1` would name
1394
+ * a genuine owner — so such a host is simply UNSUPPORTED here and fails CLOSED: the
1395
+ * writers refuse to mint the marker, so the session keeps its meta-record but never
1396
+ * claims reply-addressability, which costs a capability instead of granting a false
1397
+ * identity. Do not read this predicate as "pid 1 can never own anything"; read it as
1398
+ * "this repo does not certify a host where it does". Widening the axis means new
1399
+ * evidence and a new contract, not a quiet loosening of the bound.
1400
+ *
1401
+ * Writers refuse to mint it, readers refuse to honor it, and the cut treats it as
1402
+ * clearable residue rather than an owner claim — a proof of INVALIDITY, which is
1403
+ * stronger than the proof of death the cut already acts on.
1404
+ */
1405
+ export function isPlausibleOwnerPid(pid: unknown): pid is number {
1406
+ return Number.isSafeInteger(pid) && (pid as number) > 1;
1407
+ }
1408
+
1409
+ /**
1410
+ * The write-side half of {@link isPlausibleOwnerPid}. A marker naming an
1411
+ * impossible owner is not a degraded marker, it is a lie that outlives every
1412
+ * process that could refute it — so minting one THROWS rather than warns, and no
1413
+ * future writer can reintroduce #53 A by forgetting the predicate at its own call
1414
+ * site (both current writers still ask it first, and fail closed in their own
1415
+ * words).
1416
+ */
1417
+ function requireOwnerPid(ownerPid: number, kind: string): number {
1418
+ if (!isPlausibleOwnerPid(ownerPid)) {
1419
+ throw new Error(
1420
+ `refusing to write a ${kind} marker for owner pid ${ownerPid}: a pid <= 1 cannot own a native session ` +
1421
+ "(pid 1 is init — a reparented orphan is not an owner). Quiescing the sessions, which is what " +
1422
+ "meta-bridge-fresh-cut asks for when it refuses, would not refute such a marker, so it would keep " +
1423
+ "blocking the cut on this host (#53 A).",
1424
+ );
1425
+ }
1426
+ return ownerPid;
1427
+ }
1428
+
1139
1429
  /**
1140
1430
  * THE rule for "is the process this marker names still the one running?" — the one
1141
1431
  * place a `dead` verdict may be produced, so no caller re-derives it from
@@ -1227,15 +1517,18 @@ export interface WriteMetaSenderMarkerOptions {
1227
1517
  export function writeMetaSenderMarker(opts: WriteMetaSenderMarkerOptions): string {
1228
1518
  const backend = requireBackend(opts.backend);
1229
1519
  const gardenId = requireGardenId(opts.gardenId);
1230
- const file = metaSenderMarkerPath(backend, opts.ownerPid, opts.sendersDir ?? defaultMetaSendersDir());
1520
+ // Refused BEFORE the path is built: an impossible owner must not even leave a
1521
+ // backend directory behind, let alone a marker keyed to its pid.
1522
+ const ownerPid = requireOwnerPid(opts.ownerPid, "sender");
1523
+ const file = metaSenderMarkerPath(backend, ownerPid, opts.sendersDir ?? defaultMetaSendersDir());
1231
1524
  fs.mkdirSync(path.dirname(file), { recursive: true });
1232
1525
  const marker: MetaSenderMarker = {
1233
1526
  backend,
1234
1527
  gardenId,
1235
1528
  nativeSessionId: requireNonEmptyString(opts.nativeSessionId, "nativeSessionId"),
1236
1529
  cwd: requireNonEmptyString(opts.cwd, "cwd"),
1237
- ownerPid: opts.ownerPid,
1238
- ownerStartKey: processStartKey(opts.ownerPid),
1530
+ ownerPid,
1531
+ ownerStartKey: processStartKey(ownerPid),
1239
1532
  updatedAt: isoNow(opts.now ?? new Date()),
1240
1533
  };
1241
1534
  const tmp = `${file}.${crypto.randomBytes(4).toString("hex")}.tmp`;
@@ -1278,12 +1571,18 @@ export function readMetaSenderMarker(opts: ReadMetaSenderMarkerOptions): MetaSen
1278
1571
  ownerStartKey: requireNonEmptyString(raw.ownerStartKey, "ownerStartKey"),
1279
1572
  updatedAt: requireNonEmptyString(raw.updatedAt, "updatedAt"),
1280
1573
  };
1574
+ // Plausibility comes FIRST and is never opt-out: it is a property of the CLAIM,
1575
+ // not of the owner's current state, so `verifyOwner: false` (inspection) does not
1576
+ // reach past it either. An `ownerPid: 1` marker is a reparented orphan's residue
1577
+ // and would otherwise keep granting a dead citizen's sender identity for as long
1578
+ // as the host is up — the pid-reuse guard cannot catch it, because init IS still
1579
+ // the same process (#53 A). This also subsumes the old `Number.isInteger` check.
1580
+ if (!isPlausibleOwnerPid(marker.ownerPid)) return null;
1281
1581
  // pid-reuse guard (unless explicitly disabled): the owner pid must STILL be
1282
1582
  // the same process that wrote the marker. A bare pid is reused; pid+startKey
1283
1583
  // is boot-unique, so a stale marker from a dead session fails here instead of
1284
1584
  // granting a wrong-identity send.
1285
1585
  if (opts.verifyOwner !== false) {
1286
- if (!Number.isInteger(marker.ownerPid)) return null;
1287
1586
  const liveKey = processStartKey(marker.ownerPid);
1288
1587
  if (!liveKey || liveKey !== marker.ownerStartKey) return null;
1289
1588
  }
@@ -1349,14 +1648,15 @@ export interface WriteMetaReceiverMarkerOptions {
1349
1648
  export function writeMetaReceiverMarker(opts: WriteMetaReceiverMarkerOptions): string {
1350
1649
  const gardenId = requireGardenId(opts.gardenId);
1351
1650
  const backend = requireBackend(opts.backend);
1651
+ const ownerPid = requireOwnerPid(opts.ownerPid, "receiver");
1352
1652
  const file = metaReceiverMarkerPath(gardenId, opts.receiversDir ?? defaultMetaReceiversDir());
1353
1653
  fs.mkdirSync(path.dirname(file), { recursive: true });
1354
1654
  const marker: MetaReceiverMarker = {
1355
1655
  gardenId,
1356
1656
  backend,
1357
1657
  nativeSessionId: requireNonEmptyString(opts.nativeSessionId, "nativeSessionId"),
1358
- ownerPid: opts.ownerPid,
1359
- ownerStartKey: processStartKey(opts.ownerPid),
1658
+ ownerPid,
1659
+ ownerStartKey: processStartKey(ownerPid),
1360
1660
  ownerKind: requireNonEmptyString(opts.ownerKind ?? "claude-code-cli", "ownerKind"),
1361
1661
  armProvenance: requireArmProvenance(opts.armProvenance),
1362
1662
  updatedAt: isoNow(opts.now ?? new Date()),
@@ -1403,8 +1703,11 @@ export function readMetaReceiverMarker(opts: ReadMetaReceiverMarkerOptions): Met
1403
1703
  armProvenance: requireArmProvenance(raw.armProvenance),
1404
1704
  updatedAt: requireNonEmptyString(raw.updatedAt, "updatedAt"),
1405
1705
  };
1706
+ // Same rule as the sender marker, and for the same reason one layer over: an
1707
+ // impossible owner is not a live one, so a refuted marker must never read back
1708
+ // as an ACTIVE RECEIVER and pull the mailbox rail into delivering to a void.
1709
+ if (!isPlausibleOwnerPid(marker.ownerPid)) return null;
1406
1710
  if (opts.verifyOwner !== false) {
1407
- if (!Number.isInteger(marker.ownerPid)) return null;
1408
1711
  const liveKey = processStartKey(marker.ownerPid);
1409
1712
  if (!liveKey || liveKey !== marker.ownerStartKey) return null;
1410
1713
  }
@@ -1516,14 +1819,62 @@ function inspectRecordEntry(file: string): RecordEntryKind {
1516
1819
  return fs.lstatSync(file).isFile() ? "regular-file" : "irregular";
1517
1820
  } catch (err) {
1518
1821
  if ((err as { code?: unknown }).code === "ENOENT") return "absent";
1519
- throw new MetaRecordError(
1520
- `cannot inspect meta-record ${path.basename(file)} under ${path.dirname(file)}: ` +
1521
- `${err instanceof Error ? err.message : String(err)}. That is an inspection failure, not an absent ` +
1522
- `citizen — refusing to report "no record" from a store this process cannot read.`,
1523
- );
1822
+ throw recordInspectionFailure(file, err);
1524
1823
  }
1525
1824
  }
1526
1825
 
1826
+ /**
1827
+ * How a FAILED record read is classified when the entry was already snapshotted as a
1828
+ * regular file — that is, a race: the entry changed between the classification and the
1829
+ * open. Pure, errno-only, so the branch a synthetic errno takes is exactly the branch a
1830
+ * real one takes (the 2026-07-26 cross-review found the previous shape unprovable: with
1831
+ * the classification in front of it, no settled store could reach these branches at all,
1832
+ * and a cell that claimed to pin them passed with the mapping deleted).
1833
+ *
1834
+ * Every verdict here collapses onto the answer the SETTLED store already gives, because a
1835
+ * race must not teach the operator a second vocabulary for one state of the world:
1836
+ *
1837
+ * - `ENOENT` — the record went away mid-read. Absence, and absence alone.
1838
+ * - `ELOOP` — `O_NOFOLLOW` refused a symlink at the final component.
1839
+ * - `ENXIO` — a socket (or a device with no driver behind it) is what the name now
1840
+ * points at. `lstat` calls that irregular, so an open that trips over it
1841
+ * must say the same thing rather than "this host is unreadable".
1842
+ * - {@link NOT_REGULAR_ENTRY_CODE} — the fd opened, and `fstat` says it is a directory
1843
+ * or a fifo.
1844
+ * - anything else (EACCES, ENOTDIR, EIO…) — an inspection FAILURE, which stays loud and
1845
+ * must never be laundered into a clean "no such citizen".
1846
+ */
1847
+ export type RecordReadFailure = "absent" | "irregular" | "unreadable";
1848
+
1849
+ export function classifyRecordReadFailure(code: unknown): RecordReadFailure {
1850
+ if (code === "ENOENT") return "absent";
1851
+ if (code === "ELOOP" || code === "ENXIO" || code === NOT_REGULAR_ENTRY_CODE) return "irregular";
1852
+ return "unreadable";
1853
+ }
1854
+
1855
+ /** The three refusals a targeted read can reach from EITHER layer — the settled
1856
+ * classification or a raced read. One text each, so a race and a quiet store say the same
1857
+ * sentence to the operator. */
1858
+ function recordInspectionFailure(file: string, err: unknown): MetaRecordError {
1859
+ return new MetaRecordError(
1860
+ `cannot inspect meta-record ${path.basename(file)} under ${path.dirname(file)}: ` +
1861
+ `${err instanceof Error ? err.message : String(err)}. That is an inspection failure, not an absent ` +
1862
+ `citizen — refusing to report "no record" from a store this process cannot read.`,
1863
+ );
1864
+ }
1865
+ function absentRecordRefusal(id: string, file: string): MetaRecordError {
1866
+ return new MetaRecordError(
1867
+ `no meta-record for garden id "${id}" under ${path.dirname(file)} — not a garden citizen, cannot deliver.`,
1868
+ );
1869
+ }
1870
+ function irregularRecordRefusal(id: string): MetaRecordError {
1871
+ return new MetaRecordError(
1872
+ `meta-record ${id}.meta.json is not a regular file (symlink/directory/special) — a record's bytes must ` +
1873
+ `live in the store itself, so this entry is never followed and cannot address a citizen. ` +
1874
+ `Inspect and remove it by hand, or archive the generation with ${FRESH_CUT_PRESCRIPTION}.`,
1875
+ );
1876
+ }
1877
+
1527
1878
  /**
1528
1879
  * The identity read-by-gardenId. Read the file, body is SSOT, fail-fast on
1529
1880
  * body/filename gardenId drift; V3-only via parseMetaIdentity (an unreadable
@@ -1536,26 +1887,44 @@ export function readMetaIdentityByGardenId(
1536
1887
  ): MetaIdentity {
1537
1888
  const id = requireGardenId(gardenId);
1538
1889
  const file = recordFileFor(sessionsDir, id);
1890
+ // TWO LAYERS, AND THEY ARE NOT THE SAME RULE TWICE.
1891
+ //
1892
+ // Layer 1 — POLICY, on a settled store. Rule 1 of {@link certifyActiveStore}, enforced
1893
+ // HERE too, because this is the one place a live dispatch reads a record. Certifying
1894
+ // the store on WRITE while this read followed the link made the contract true only
1895
+ // where nobody was being addressed: the doctor refused a symlinked entry that v2
1896
+ // dispatch, `entwurf_self` and the sender-marker trust all resolved happily, from bytes
1897
+ // the store does not own (2026-07-25 fresh-eyes review). It classifies WITHOUT OPENING,
1898
+ // which is the point — a socket, a device, a mode-000 directory each earn the
1899
+ // certification's own sentence instead of whatever errno an `open` would have tripped
1900
+ // over (ENXIO, EACCES), and nothing special is opened to find out what it is. Deleting
1901
+ // this layer in favour of the fd alone looked like removing a duplicate enforcement
1902
+ // point and was actually a regression on all three shapes (2026-07-26 cross-review,
1903
+ // round 3 — found by GPT, reproduced here).
1904
+ //
1905
+ // Layer 2 — the RACE, on the bytes actually returned. A verdict about a name stops
1906
+ // being true the moment something replaces what the name points at, so the read
1907
+ // re-decides on its own fd. Its errno verdicts collapse onto layer 1's sentences via
1908
+ // {@link classifyRecordReadFailure}, which is pure so that the branches stay provable:
1909
+ // with layer 1 in front of it, no settled store can reach them.
1539
1910
  const kind = inspectRecordEntry(file);
1540
- if (kind === "absent") {
1541
- throw new MetaRecordError(
1542
- `no meta-record for garden id "${id}" under ${path.dirname(file)} — not a garden citizen, cannot deliver.`,
1543
- );
1544
- }
1545
- // Rule 1 of {@link certifyActiveStore}, enforced HERE too — the one place a live
1546
- // dispatch reads a record. Certifying the store on WRITE while this read followed the
1547
- // link made the contract true only where nobody was being addressed: the doctor
1548
- // refused a symlinked entry that v2 dispatch, `entwurf_self` and the sender-marker
1549
- // trust all resolved happily, from bytes the store does not own (2026-07-25
1550
- // fresh-eyes review). One contract means both directions hold it.
1551
- if (kind === "irregular") {
1552
- throw new MetaRecordError(
1553
- `meta-record ${id}.meta.json is not a regular file (symlink/directory/special) — a record's bytes must ` +
1554
- `live in the store itself, so this entry is never followed and cannot address a citizen. ` +
1555
- `Inspect and remove it by hand, or archive the generation with ${FRESH_CUT_PRESCRIPTION}.`,
1556
- );
1911
+ if (kind === "absent") throw absentRecordRefusal(id, file);
1912
+ if (kind === "irregular") throw irregularRecordRefusal(id);
1913
+ let raw: string;
1914
+ try {
1915
+ raw = readStoreRecordFile(file);
1916
+ } catch (err) {
1917
+ if (err instanceof MetaRecordError) throw err;
1918
+ switch (classifyRecordReadFailure((err as { code?: unknown }).code)) {
1919
+ case "absent":
1920
+ throw absentRecordRefusal(id, file);
1921
+ case "irregular":
1922
+ throw irregularRecordRefusal(id);
1923
+ default:
1924
+ throw recordInspectionFailure(file, err);
1925
+ }
1557
1926
  }
1558
- const identity = parseMetaIdentity(fs.readFileSync(file, "utf8"));
1927
+ const identity = parseMetaIdentity(raw);
1559
1928
  if (identity.gardenId !== id) {
1560
1929
  throw new MetaRecordError(
1561
1930
  `meta-record body/filename drift: ${id}.meta.json contains gardenId "${identity.gardenId}". ` +
@@ -1586,6 +1955,125 @@ export function metaRecordExistsByGardenId(gardenId: string, sessionsDir: string
1586
1955
  return inspectRecordEntry(recordFileFor(sessionsDir, id)) !== "absent";
1587
1956
  }
1588
1957
 
1958
+ /**
1959
+ * Pure: which OTHER records in this store claim `identity`'s `nativeSessionId`.
1960
+ * Returns their filenames, sorted; empty means `identity` holds it alone.
1961
+ *
1962
+ * A RIVAL IS A RECORD THAT COULD BE ADDRESSED INSTEAD. That is the whole test, and it
1963
+ * is narrower than "a file whose bytes mention the same id" — three neighbour shapes
1964
+ * are therefore NOT candidates, and skipping them is a claim about reachability, not
1965
+ * leniency:
1966
+ *
1967
+ * - NON-REGULAR (symlink/dir/special): rule 1 of {@link certifyActiveStore} says such
1968
+ * an entry is refused and never followed, because its bytes live where this store
1969
+ * has no ownership. So it is skipped WITHOUT BEING READ — following it to see
1970
+ * whether it "counts" would break the rule in the act of enforcing it, and let a
1971
+ * planted symlink to foreign bytes quarantine a healthy citizen.
1972
+ * - BODY/FILENAME DRIFT: a record whose body names a different garden id is
1973
+ * unreachable by garden-id lookup from either name, so it can never be dispatched
1974
+ * to and cannot compete for an address.
1975
+ * - UNPARSEABLE by the live schema: same reason — no read path can reach it.
1976
+ *
1977
+ * All three are real certification defects, and the certification and the listing both
1978
+ * say so. What they must not do is blind a healthy citizen, which is the 0.10 "corrupt
1979
+ * blocks registration forever" mistake wearing a new hat.
1980
+ *
1981
+ * A CANDIDATE WE COULD NOT READ IS A DIFFERENT ANSWER AND THROWS. A regular
1982
+ * `.meta.json` this process cannot read might be a genuine duplicate; skipping it would
1983
+ * report "holds it alone" from a scan that never asked, which is exactly the vacuous
1984
+ * pass the store-level readdir guard refuses one level up. ENOENT is the one exception
1985
+ * and the one this repo already recognises everywhere (`inspectRecordEntry`, the cut's
1986
+ * socket walk, `clearFiles`): a file that vanished between the readdir and the read is
1987
+ * not in the store, so it holds nothing.
1988
+ *
1989
+ * The identity's OWN file is excluded by filename, not by identity equality: the caller
1990
+ * has already proven body and filename agree, and a rival is by definition a different
1991
+ * file.
1992
+ */
1993
+ export function nativeSessionIdRivals(
1994
+ identity: MetaIdentity,
1995
+ entries: readonly ActiveStoreEntry[],
1996
+ readRecord: (filename: string) => string,
1997
+ ): string[] {
1998
+ const own = metaRecordFilename(identity);
1999
+ const rivals: string[] = [];
2000
+ for (const entry of entries) {
2001
+ const filename = entry.filename;
2002
+ if (!filename.endsWith(".meta.json") || filename === own) continue;
2003
+ if (!entry.regularFile) continue; // never followed — see rule 1 above
2004
+ let raw: string;
2005
+ try {
2006
+ raw = readRecord(filename);
2007
+ } catch (err) {
2008
+ if ((err as { code?: unknown }).code === "ENOENT") continue; // raced away — holds nothing
2009
+ throw new MetaRecordError(
2010
+ `cannot read meta-record ${filename} while proving that ${own} holds nativeSessionId ` +
2011
+ `${JSON.stringify(identity.nativeSessionId)} alone: ` +
2012
+ `${err instanceof Error ? err.message : String(err)}. That record may be a duplicate, so this ` +
2013
+ `is an unanswered question, not a clean scan — refusing to dispatch at an address this process ` +
2014
+ `cannot certify.`,
2015
+ );
2016
+ }
2017
+ let other: MetaIdentity;
2018
+ try {
2019
+ other = parseMetaIdentity(raw);
2020
+ } catch {
2021
+ continue; // unreachable by the live schema — not an addressable rival
2022
+ }
2023
+ if (metaRecordFilename(other) !== filename) continue; // drifted — unreachable by garden id
2024
+ if (other.nativeSessionId === identity.nativeSessionId) rivals.push(filename);
2025
+ }
2026
+ return rivals.sort();
2027
+ }
2028
+
2029
+ /**
2030
+ * The read a DISPATCH does (#52) — the targeted read PLUS the store-wide half of the
2031
+ * contract that a targeted read cannot see on its own.
2032
+ *
2033
+ * WHY THIS IS A SECOND FUNCTION AND NOT A CHANGE TO {@link readMetaIdentityByGardenId}:
2034
+ * the cost is real and the README says so out loud — a call-relay does not re-scan the
2035
+ * whole store per message, and the mailbox poke, the sender-marker trust and
2036
+ * `entwurf_self` keep the per-entry half exactly as before. What separates the callers
2037
+ * is not how careful they are, it is what they DO with the answer: these two turn
2038
+ * `nativeSessionId` into an ADDRESS — a native-push injection into a live conversation,
2039
+ * a pi resume against a transcript — and each does it ONCE per dispatch, next to a
2040
+ * socket connect and a process spawn. One readdir there is nothing; the same readdir
2041
+ * per relayed message is the design the store deliberately does not have.
2042
+ *
2043
+ * The failure it prevents is not hypothetical corruption. `upsertMetaSession` certifies
2044
+ * and then writes, which is not a transaction: two concurrent births — two SessionStart
2045
+ * hooks, an `entwurf_register_native` racing an agy imprint — can both read one clean
2046
+ * snapshot and mint DIFFERENT garden ids for one native session. Nothing was ever
2047
+ * corrupted on such a host, and yet both ids would direct-inject the same conversation,
2048
+ * or resume one transcript twice under two per-garden-id locks.
2049
+ *
2050
+ * Fails LOUD, never soft: a duplicate is corruption of the address space, and QB1
2051
+ * reserves the soft `bad-target` answer for a record that is simply ABSENT.
2052
+ */
2053
+ export function readAddressableMetaIdentity(
2054
+ gardenId: string,
2055
+ sessionsDir: string = defaultMetaSessionsDir(),
2056
+ ): MetaIdentity {
2057
+ const identity = readMetaIdentityByGardenId(gardenId, sessionsDir);
2058
+ const dir = path.resolve(expandTilde(sessionsDir));
2059
+ // Entries carry their KIND (readActiveStoreEntries), so the rival scan can refuse a
2060
+ // symlinked neighbour without reading it. A bare-name readdir here would have made
2061
+ // rule 1 unenforceable at exactly the surface that turns a record into an address.
2062
+ // A store that cannot be listed throws from there — answering "unique" from a scan
2063
+ // that never happened is the vacuous pass this whole check exists to refuse.
2064
+ const rivals = nativeSessionIdRivals(identity, readActiveStoreEntries(dir), makeStoreRecordReader(dir));
2065
+ if (rivals.length > 0) {
2066
+ throw new MetaRecordError(
2067
+ `meta-record ${metaRecordFilename(identity)} shares nativeSessionId ` +
2068
+ `${JSON.stringify(identity.nativeSessionId)} with ${rivals.join(", ")} — the native→garden mapping ` +
2069
+ `must be unique, so this store cannot say which record owns that session and dispatching at either ` +
2070
+ `garden id would reach the same native session twice. Archive the generation with ` +
2071
+ `${FRESH_CUT_PRESCRIPTION}.`,
2072
+ );
2073
+ }
2074
+ return identity;
2075
+ }
2076
+
1589
2077
  export interface EnqueueMetaMessageOptions {
1590
2078
  gardenId: string;
1591
2079
  body: string;