session-peer 0.5.1 → 0.6.0

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/CONTRIBUTING.md +26 -0
  2. package/PARITY.md +134 -4
  3. package/README.ja.md +12 -8
  4. package/README.ko.md +12 -8
  5. package/README.md +12 -8
  6. package/README.zh-CN.md +12 -8
  7. package/RELEASING.md +142 -0
  8. package/VALIDATION.md +154 -2
  9. package/dist/app-server.d.ts +10 -2
  10. package/dist/app-server.js +115 -53
  11. package/dist/cli.js +54 -4
  12. package/dist/codex-storage.d.ts +46 -0
  13. package/dist/codex-storage.js +447 -0
  14. package/dist/diagnostics.js +23 -102
  15. package/dist/discovery.d.ts +32 -1
  16. package/dist/discovery.js +405 -89
  17. package/dist/handoff-operations.js +40 -10
  18. package/dist/help.js +18 -2
  19. package/dist/macos-acl.d.ts +10 -0
  20. package/dist/macos-acl.js +75 -0
  21. package/dist/output.js +6 -1
  22. package/dist/process.d.ts +1 -0
  23. package/dist/process.js +1 -1
  24. package/dist/protocol.d.ts +2 -2
  25. package/dist/protocol.js +1 -1
  26. package/dist/receipt-collector.d.ts +12 -0
  27. package/dist/receipt-collector.js +283 -0
  28. package/dist/receipt-command.d.ts +10 -0
  29. package/dist/receipt-command.js +246 -0
  30. package/dist/receipt-producer.d.ts +7 -0
  31. package/dist/receipt-producer.js +107 -0
  32. package/dist/receipt-protocol.d.ts +219 -0
  33. package/dist/receipt-protocol.js +374 -0
  34. package/dist/receipt-send.d.ts +26 -0
  35. package/dist/receipt-send.js +375 -0
  36. package/dist/receipt-state.d.ts +89 -0
  37. package/dist/receipt-state.js +503 -0
  38. package/dist/receipt-store.d.ts +32 -0
  39. package/dist/receipt-store.js +286 -0
  40. package/dist/replies.js +3 -1
  41. package/dist/send.d.ts +14 -3
  42. package/dist/send.js +165 -63
  43. package/dist/skill-metadata.js +5 -3
  44. package/docs/api.md +155 -7
  45. package/docs/design/remote-deployment.md +8 -0
  46. package/docs/design/typescript-skill-compatibility.md +50 -0
  47. package/docs/guide.ja.md +47 -15
  48. package/docs/guide.ko.md +50 -19
  49. package/docs/guide.md +48 -16
  50. package/docs/guide.zh-CN.md +47 -15
  51. package/docs/shorthand.md +1 -1
  52. package/package.json +5 -3
package/VALIDATION.md CHANGED
@@ -1,4 +1,156 @@
1
- # Validation record — updated 2026-10-20 KST
1
+ # Validation record — updated 2026-11-03 KST
2
+
3
+ ## 0.6.0 preparation scope — 2026-11-03 KST
4
+
5
+ The candidate tracks [#175](https://github.com/abruption/session-peer-ts/issues/175)
6
+ and combines merged Orca Claude profile discovery
7
+ ([#165](https://github.com/abruption/session-peer-ts/issues/165),
8
+ [#173](https://github.com/abruption/session-peer-ts/pull/173)) with
9
+ [#176](https://github.com/abruption/session-peer-ts/pull/176)'s staged local
10
+ receipt implementation for [#132](https://github.com/abruption/session-peer-ts/issues/132).
11
+ The integrated source `ef1ba36b7d9b4f4ac7917527fdb8d2db009d5def` passed
12
+ 660 tests: 648 pass, 0 fail, 11 skip and 1 existing TODO on Node 24/macOS arm64,
13
+ using the pinned Python reference `8ca77cf31254c8287a2593fe484bb30a7dba2727`.
14
+ Build/types, scoped versions and repository links/structure passed. The exact
15
+ 95-file package passed reproducible packing, isolated install, native binding,
16
+ shorthand lifecycle and uninstall. Final PR-head CI/reviews and exact merged-main
17
+ release evidence remain separate gates; the candidate archive identity is
18
+ recorded in the release PR and its source-bound manifest, not inferred from an
19
+ earlier feature or metadata-only artifact.
20
+
21
+ The new collector is explicitly started and stopped by its operator; it does
22
+ not start a service, wake a session or resend messages. Codex retains the v1
23
+ non-null generation contract on the qualified owned native queue route.
24
+ Claude's v2 delegated receipt context deliberately does not prove a native
25
+ generation. Authenticated receipt submission proves neither model identity nor
26
+ message consumption, injection or completion. Sender/collector output does not
27
+ publish the private capability; the intended recipient's native input/history
28
+ may retain it. Unknown effects keep the no-retry/no-resend boundary.
29
+
30
+ The implementation's local CLI, private IPC, storage and synthetic transport
31
+ checks do not establish new live native/model/SSH receipt or ACK qualification.
32
+ Existing platform refusals and native observation profiles remain bounded;
33
+ Linux/Windows observation and Windows managed receipt storage are not enabled.
34
+ [#73](https://github.com/abruption/session-peer-ts/issues/73)'s transcript/body
35
+ probe is closed NO-GO and is not included as a runtime feature. Existing
36
+ companion skill publication and its immutable source/hash pin remain separate
37
+ and unchanged; metadata compatibility is not new workflow coverage.
38
+
39
+ This preparation makes no public 0.6.0 availability, fresh npm authentication or
40
+ publisher/MFA-policy audit, stage approval, installation or operational claim.
41
+ Exact merged-source approval, protected-environment approval, final npm stage
42
+ approval, publication verification and any authorized tag/release remain future
43
+ release gates. Historical publication records below retain their original
44
+ versions, dates and evidence limits.
45
+
46
+ <a id="public-052--2026-10-30-kst"></a>
47
+
48
+ ## Public 0.5.2 — 2026-10-30 KST
49
+
50
+ `session-peer@0.5.2` was published at `2026-10-30T01:54:47.513Z` from
51
+ `d5c40ecd09baa831315266d0debf63eb1c4a1e59`.
52
+ [Run 40988011234](https://github.com/abruption/session-peer-ts/actions/runs/40988011234)
53
+ ran once; both prepare and publish succeeded, with npm stage
54
+ `333968c3-29bd-4fbe-afeb-134da02924a5`. The
55
+ [GitHub release](https://github.com/abruption/session-peer-ts/releases/tag/v0.5.2)
56
+ was published at `2026-10-30T02:04:15Z`. Annotated tag object
57
+ `b19877a806154afecbd35b7754333d23b55ebd31` peels to the same source commit.
58
+
59
+ The reviewed local, exact-main, retained Actions, staged and public tarball raw
60
+ bytes all matched. All 79 archive files, including 18 Markdown files, matched
61
+ the selected source. The immutable archive contains the correct release source;
62
+ this later GitHub public record is not in the 0.5.2 archive and does not imply
63
+ republishing it.
64
+
65
+ - SHA-256: `c799e4f7ed96794928e5780732f8d230e6eac8502301a75f44c0d55393c85d8b`
66
+ - Registry integrity: `sha512-4cgqyU7AaSVUnTZvsFeP5Ocyri9XNqUQCxV+WDZOhHK0aJ8c/CkeMiv7isVtZns3RYu58TyU0sAoz4oBbQLhAA==`
67
+
68
+ The full suite recorded 503 tests: 491 pass, 0 fail, 11 platform skips and
69
+ 1 existing TODO. Exact-main
70
+ [CLI CI run 40984539326](https://github.com/abruption/session-peer-ts/actions/runs/40984539326)
71
+ and [CodeQL run 40984538915](https://github.com/abruption/session-peer-ts/actions/runs/40984538915)
72
+ succeeded. The release helper's public verification with pinned npm 11.15.0
73
+ passed signature/provenance checks, an isolated installation, CLI version and
74
+ empty Claude-list checks, and uninstallation.
75
+
76
+ The actual registry SLSA bundle passed `sigstore.verify` certificate-chain,
77
+ certificate-transparency and transparency-log verification, including the
78
+ GitHub OIDC issuer and workflow identity. Its subject SHA-512, source commit,
79
+ repository, `main` ref, `publish.yml`, `workflow_dispatch` trigger and invocation
80
+ `40988011234` matched the release. Rekor entry: `3581769908`. The staged-byte
81
+ comparison completed at `01:53:47Z`, before publication; full provenance trust
82
+ verification completed after publication. These results do not establish that
83
+ all checks preceded user approval.
84
+
85
+ The user explicitly confirmed source approval and GitHub environment approval.
86
+ Fresh checks established authenticated owner `abruption`, no pre-existing
87
+ stages, a stage-only `createStagedPackage` publisher and the GitHub environment's
88
+ required reviewer and main-only restriction. For 0.5.2 the user explicitly
89
+ skipped only the web read of npm's publish-MFA policy; that setting was not
90
+ freshly audited. No protection or setting was changed. The stage later returned
91
+ 404 and public `latest=0.5.2` was observed. The agent did not execute final
92
+ `npm stage approve`; this record claims neither that action nor an explicit
93
+ chat confirmation of npm 2FA approval.
94
+
95
+ At public verification, `latest=0.5.2` and `preview=0.1.0-preview.1` (unchanged).
96
+ Registry `readmeFilename=README.zh-CN.md` and the registry README exactly matched
97
+ the packaged 0.5.2 Chinese README. Public npm HTML returned HTTP 403, so rendered
98
+ npm-page inspection is not claimed. These checks establish source/package
99
+ identity and public package availability only: no new native/model, SSH, delivery/ACK,
100
+ fleet-installation or global-installation test is claimed. Historical evidence
101
+ and the dated preparation checkpoint below retain their original scope.
102
+
103
+
104
+ ## 0.5.2 preparation scope — 2026-10-30 KST
105
+
106
+ Preparation baseline is merged main
107
+ `1b9e762c154e1050b04f98d5c36cee0d332cf484`: #169's storage guards, scoped parity
108
+ matrix and current-version maintenance, plus #160's repository-only local static
109
+ qualification reporter. This release preparation selects package/banner/current
110
+ examples 0.5.2 and one finite doctor row preserving the four exact 0.5.1 skill
111
+ profiles. Historical evidence, the ordinary Python 1.1.0 oracle, frozen handoff
112
+ fixtures, native observation profiles and independent skill pins stay separate.
113
+
114
+ The guarded local loader-source versions are Codex 0.160.1, 0.162.1 and 0.165.0.
115
+ Source review and fixture refusal tests are not new native submission, positive
116
+ managed-preference/MDM, Linux/Windows observation, live delivery or ACK
117
+ qualification. Ordinary signed-in file-auth/keyring/cloud-unclassifiable homes
118
+ can refuse even when their accounts would not receive cloud policy. Windows
119
+ Codex send/dry-run remain unqualified and refuse before submission; ordinary
120
+ Claude behavior is separate. The owned stdio route requires its actual opened
121
+ storage binding. Existing unknown/no-resend and explicit operator-confirmed
122
+ receipt boundaries are retained.
123
+
124
+ The reporter measures only operator-selected local static metadata/digests and
125
+ keeps execution/ownership/qualification predicates independent. Its source
126
+ script, tests and two review/design documents are excluded from the npm archive;
127
+ it is not an installed command, SDK API, readiness certificate, deployment or
128
+ cleanup engine. Draft #155 and experiments #82/#142 remain excluded. The
129
+ remaining remote/platform acceptance gates in #20/#23/#130/#131/#132 are not
130
+ completed by this release preparation.
131
+
132
+ For source provenance, #169's reviewed head
133
+ `76f556cca869da95ad4368af914bad6f0f43af3d` passed its current-head matrix and
134
+ release gate; its macOS Node 24 retry followed an execution-free hosted-runner
135
+ capacity cancellation. #160's integrated head
136
+ `d2760958ebf5f1f160fb716af54e63dabcce8862` passed 12 checks in
137
+ [run 40980450661](https://github.com/abruption/session-peer-ts/actions/runs/40980450661).
138
+ Its local full suite recorded 503 tests: 491 pass, 0 fail, 11 platform skips and
139
+ 1 existing TODO. The earlier integrated macOS Node 24 result had observation
140
+ `unsupported` instead of `pending`; the original cause remains unconfirmed.
141
+ The follow-up added assertion diagnostics only and did not relax outcomes,
142
+ deadlines or product guards. A later pass does not establish that original cause.
143
+ These 0.5.1 implementation-head results do not substitute for final 0.5.2
144
+ source, package, profile and exact merged-main checks.
145
+
146
+ At this dated preparation checkpoint the public registry baseline is
147
+ latest=0.5.1, preview=0.1.0-preview.1 and target 0.5.2 absent. Fresh authenticated
148
+ publisher/MFA/pending-stage checks, final-source approval, staging and publication
149
+ belong to their separate release gates. No new live-host/native/model/ACK
150
+ experiment, existing user-session input, global installation or operational
151
+ change is claimed. Final release-preparation PR and artifact records must name
152
+ the exact tested source and bytes before source/publication approval.
153
+
2
154
 
3
155
  ## 0.5.1 dependency patch preparation — 2026-10-27 KST
4
156
 
@@ -1595,7 +1747,7 @@ All three operating systems run Node 22/24. The checks differ:
1595
1747
  | Platform | Automated scope |
1596
1748
  | --- | --- |
1597
1749
  | macOS/Linux | Full contract suite, type checks, Python reference fixtures, package smoke, release pack/artifact checks and audit. |
1598
- | Windows x64 | Build/type checks, Claude named-pipe/auth/stale-record fixtures, held/free kernel locks, writer ownership and pre-submit races, native queue outcome fixtures, PowerShell/.cmd SSH framing through a fake endpoint, package/native-load smoke and audit. |
1750
+ | Windows x64 | Build/type checks, Claude named-pipe/auth/stale-record fixtures, held/free kernel locks, writer ownership and pre-submit races, Codex storage-refusal fixtures and synthetic native-exit/SSH response outcomes, PowerShell/.cmd SSH framing through a fake endpoint, package/native-load smoke and audit. |
1599
1751
 
1600
1752
  Windows runs its native suite, not the POSIX/Python reference suite. Both
1601
1753
  Windows Node jobs are required by the aggregate release gate. The x64/Node 24
@@ -98,6 +98,8 @@ export type NativeQueueOptions = {
98
98
  deadlineMs: number;
99
99
  verifyOwner: (scope: AppServerScope) => Promise<boolean>;
100
100
  beforeEffect: () => Promise<void>;
101
+ verifyStorage?: () => Promise<void>;
102
+ verifyStorageSync?: () => void;
101
103
  env?: NodeJS.ProcessEnv;
102
104
  };
103
105
  export declare function nativeQueueCapability(context: AppServerContext): {
@@ -148,6 +150,7 @@ export declare class BoundedAppServerClient implements AppServerPort {
148
150
  private readonly verifyOwner;
149
151
  private readonly nativeQueue;
150
152
  private readonly beforeEffect;
153
+ private readonly beforeWrite;
151
154
  private readonly pending;
152
155
  private readonly observers;
153
156
  private readonly operations;
@@ -169,7 +172,7 @@ export declare class BoundedAppServerClient implements AppServerPort {
169
172
  private constructor();
170
173
  static connectMetadataFixture(scope: AppServerScope, transport: MetadataOnlyTransport, deadlineMs: number, verifyOwner: (scope: AppServerScope) => Promise<boolean>): Promise<BoundedAppServerClient>;
171
174
  static connectNativeQueueFixture(scope: AppServerScope, transport: MetadataOnlyTransport, deadlineMs: number, verifyOwner: (scope: AppServerScope) => Promise<boolean>, beforeEffect: () => Promise<void>, nativeVersion?: string, platform?: string, profiles?: readonly NativeProfile[]): Promise<NativeQueuePort>;
172
- static connectNativeQueueWire(scope: AppServerScope, transport: NativeQueueTransport, deadlineMs: number, verifyOwner: (scope: AppServerScope) => Promise<boolean>, beforeEffect: () => Promise<void>, profile: NativeProfile): Promise<NativeQueuePort>;
175
+ static connectNativeQueueWire(scope: AppServerScope, transport: NativeQueueTransport, deadlineMs: number, verifyOwner: (scope: AppServerScope) => Promise<boolean>, beforeEffect: () => Promise<void>, profile: NativeProfile, beforeWrite: () => void): Promise<NativeQueuePort>;
173
176
  private static connectWire;
174
177
  private check;
175
178
  private owner;
@@ -193,8 +196,13 @@ export declare class BoundedAppServerClient implements AppServerPort {
193
196
  private fail;
194
197
  close(): Promise<void>;
195
198
  }
199
+ type SqliteBindingProof = readonly Readonly<{
200
+ path: string;
201
+ dev: bigint | null;
202
+ ino: bigint | null;
203
+ }>[];
196
204
  export declare function artifactDigest(path: string, deadlineMs: number, maxBytes?: number): Promise<string>;
197
- export declare function verifyProcfsSqliteBinding(pid: number | undefined, home: string, deadlineMs: number, binary: string, reader?: ProcReader): Promise<void>;
205
+ export declare function verifyProcfsSqliteBinding(pid: number | undefined, home: string, deadlineMs: number, binary: string, reader?: ProcReader): Promise<SqliteBindingProof>;
198
206
  export declare function nativeQueueOnce(options: NativeQueueOptions): Promise<{
199
207
  queueId: string;
200
208
  clientUserMessageId: string;
@@ -13,6 +13,7 @@ import { basename, isAbsolute, join } from 'node:path';
13
13
  import { performance } from 'node:perf_hooks';
14
14
  import { TextDecoder } from 'node:util';
15
15
  import { run } from './process.js';
16
+ import { classifyCodexStorage, codexConsumerCwd, codexConsumerSnapshotSync, codexStoragePin, decodeLsofFilename } from './codex-storage.js';
16
17
  import { CANDIDATE_PROFILES, NATIVE_PROFILES, platformProfiled, selectNativeProfile, validateNativeProfiles } from './native-profiles.js';
17
18
  import { procOwnedFiles } from './linux-proc.js';
18
19
  import { fileURLToPath } from 'node:url';
@@ -286,6 +287,7 @@ export class BoundedAppServerClient {
286
287
  verifyOwner;
287
288
  nativeQueue;
288
289
  beforeEffect;
290
+ beforeWrite;
289
291
  pending = new Map();
290
292
  observers = new Set();
291
293
  operations = new Set();
@@ -304,13 +306,14 @@ export class BoundedAppServerClient {
304
306
  fault;
305
307
  closing;
306
308
  timer;
307
- constructor(scope, transport, deadlineMs, verifyOwner, nativeQueue = false, beforeEffect = async () => { }) {
309
+ constructor(scope, transport, deadlineMs, verifyOwner, nativeQueue = false, beforeEffect = async () => { }, beforeWrite = () => { }) {
308
310
  this.scope = scope;
309
311
  this.transport = transport;
310
312
  this.deadlineMs = deadlineMs;
311
313
  this.verifyOwner = verifyOwner;
312
314
  this.nativeQueue = nativeQueue;
313
315
  this.beforeEffect = beforeEffect;
316
+ this.beforeWrite = beforeWrite;
314
317
  this.timer = setTimeout(() => this.fail('deadline'), Math.max(1, deadlineMs - performance.now()));
315
318
  transport.input.on('data', this.receive);
316
319
  transport.input.once('end', this.ended);
@@ -327,10 +330,10 @@ export class BoundedAppServerClient {
327
330
  static async connectNativeQueueFixture(scope, transport, deadlineMs, verifyOwner, beforeEffect, nativeVersion = APP_SERVER_EVIDENCE.version, platform = APP_SERVER_EVIDENCE.inspectedPlatform, profiles = NATIVE_PROFILES) {
328
331
  return this.connectWire(scope, transport, deadlineMs, verifyOwner, true, beforeEffect, selectNativeProfile({ platform, version: nativeVersion }, validateNativeProfiles(profiles)));
329
332
  }
330
- static async connectNativeQueueWire(scope, transport, deadlineMs, verifyOwner, beforeEffect, profile) {
331
- return this.connectWire(scope, transport, deadlineMs, verifyOwner, true, beforeEffect, profile);
333
+ static async connectNativeQueueWire(scope, transport, deadlineMs, verifyOwner, beforeEffect, profile, beforeWrite) {
334
+ return this.connectWire(scope, transport, deadlineMs, verifyOwner, true, beforeEffect, profile, beforeWrite);
332
335
  }
333
- static async connectWire(scope, transport, deadlineMs, verifyOwner, nativeQueue, beforeEffect = async () => { }, profile) {
336
+ static async connectWire(scope, transport, deadlineMs, verifyOwner, nativeQueue, beforeEffect = async () => { }, profile, beforeWrite) {
334
337
  let original;
335
338
  try {
336
339
  original = scopeValue(scope);
@@ -348,7 +351,7 @@ export class BoundedAppServerClient {
348
351
  await disposeTransport(transport);
349
352
  throw new AppServerFault('deadline', false);
350
353
  }
351
- const client = new BoundedAppServerClient(original, transport, deadlineMs, verifyOwner, nativeQueue, beforeEffect);
354
+ const client = new BoundedAppServerClient(original, transport, deadlineMs, verifyOwner, nativeQueue, beforeEffect, beforeWrite);
352
355
  try {
353
356
  await client.owner();
354
357
  if (nativeQueue) {
@@ -404,9 +407,9 @@ export class BoundedAppServerClient {
404
407
  return new Promise((resolve, reject) => {
405
408
  const wait = { reject };
406
409
  this.operations.add(wait);
407
- promise.then(value => { this.operations.delete(wait); resolve(value); }, () => {
410
+ promise.then(value => { this.operations.delete(wait); resolve(value); }, error => {
408
411
  this.operations.delete(wait);
409
- this.fail(failureCode);
412
+ this.fail(error instanceof AppServerFault ? error.code : failureCode);
410
413
  reject(this.fault);
411
414
  });
412
415
  });
@@ -542,6 +545,7 @@ export class BoundedAppServerClient {
542
545
  // owner after that await, before marking an attempt or writing the RPC.
543
546
  // The ledger may already be fenced; this never authorizes a new effect.
544
547
  await this.owner();
548
+ this.beforeWrite();
545
549
  this.check();
546
550
  }
547
551
  return new Promise((resolve, reject) => {
@@ -668,7 +672,7 @@ async function beforeDeadline(deadlineMs, operation, code) {
668
672
  async function verifyOwnedSqliteBinding(pid, home, deadlineMs) {
669
673
  if (!pid || pid < 2 || performance.now() >= deadlineMs)
670
674
  throw new AppServerFault('storage_binding_unverified', false);
671
- verifyOpenedSqlite(await darwinOpenedFiles(pid, deadlineMs), home);
675
+ return verifyOpenedSqlite(await darwinOpenedFiles(pid, deadlineMs), home);
672
676
  }
673
677
  async function darwinOpenedFiles(pid, deadlineMs) {
674
678
  // Only the owned app-server PID is queried, never a session inventory/PID scan.
@@ -694,8 +698,14 @@ async function darwinOpenedFiles(pid, deadlineMs) {
694
698
  current = {};
695
699
  files.push(current);
696
700
  }
697
- else if (current && field.startsWith('n'))
698
- current.name = lsofFilename(field.slice(1));
701
+ else if (current && field.startsWith('n')) {
702
+ try {
703
+ current.name = decodeLsofFilename(field.slice(1));
704
+ }
705
+ catch {
706
+ throw new AppServerFault('storage_binding_unverified', false);
707
+ }
708
+ }
699
709
  else if (current && /^D0x[0-9a-f]+$/i.test(field))
700
710
  current.dev = BigInt(field.slice(1));
701
711
  else if (current && /^i[0-9]+$/.test(field))
@@ -707,6 +717,7 @@ async function darwinOpenedFiles(pid, deadlineMs) {
707
717
  // be opened by the owned PID with the inode now at that canonical path.
708
718
  function verifyOpenedSqlite(files, home) {
709
719
  const required = ['state_5.sqlite', 'queue_1.sqlite'];
720
+ const proof = new Map();
710
721
  for (const file of required) {
711
722
  const expected = join(home, file);
712
723
  const opened = files.filter(row => row.name && [file, file + '-wal', file + '-shm'].includes(basename(row.name)));
@@ -719,12 +730,52 @@ function verifyOpenedSqlite(files, home) {
719
730
  const canonical = lstatSync(row.name, { bigint: true });
720
731
  if (!canonical.isFile() || canonical.isSymbolicLink() || row.dev !== canonical.dev || row.ino !== canonical.ino)
721
732
  throw new Error('storage identity changed');
733
+ const prior = proof.get(row.name);
734
+ if (prior && (prior.dev !== row.dev || prior.ino !== row.ino))
735
+ throw new Error('conflicting opened identities');
736
+ // Retain the opened FD's identity, not a later sample of the pathname.
737
+ proof.set(row.name, Object.freeze({ path: row.name, dev: row.dev, ino: row.ino }));
722
738
  }
723
739
  catch {
724
740
  throw new AppServerFault('storage_binding_unverified', false);
725
741
  }
726
742
  }
727
743
  }
744
+ // The fixed WAL/SHM paths may not be opened yet. Retain their named presence
745
+ // and identity too, without claiming FD evidence for these additional paths.
746
+ for (const file of required)
747
+ for (const suffix of ['', '-wal', '-shm']) {
748
+ const path = join(home, file + suffix);
749
+ if (proof.has(path))
750
+ continue;
751
+ try {
752
+ const info = lstatSync(path, { bigint: true });
753
+ if (!info.isFile() || info.isSymbolicLink())
754
+ throw new Error();
755
+ proof.set(path, Object.freeze({ path, dev: info.dev, ino: info.ino }));
756
+ }
757
+ catch (error) {
758
+ if (error.code !== 'ENOENT')
759
+ throw new AppServerFault('storage_binding_unverified', false);
760
+ proof.set(path, Object.freeze({ path, dev: null, ino: null }));
761
+ }
762
+ }
763
+ return Object.freeze([...proof.values()]);
764
+ }
765
+ function revalidateSqliteBinding(proof) {
766
+ if (!proof)
767
+ throw new AppServerFault('storage_binding_unverified', false);
768
+ for (const expected of proof) {
769
+ try {
770
+ const info = lstatSync(expected.path, { bigint: true });
771
+ if (!info.isFile() || info.isSymbolicLink() || info.dev !== expected.dev || info.ino !== expected.ino)
772
+ throw new Error();
773
+ }
774
+ catch (error) {
775
+ if (expected.dev !== null || error.code !== 'ENOENT')
776
+ throw new AppServerFault('storage_binding_unverified', false);
777
+ }
778
+ }
728
779
  }
729
780
  // Synchronous native-profile I/O (executable digest, procfs walk) runs in an
730
781
  // owned worker. Supervisor refusal boundary for that worker only: run()
@@ -797,38 +848,7 @@ export async function verifyProcfsSqliteBinding(pid, home, deadlineMs, binary, r
797
848
  }
798
849
  if (performance.now() >= deadlineMs)
799
850
  throw new AppServerFault('deadline', false);
800
- verifyOpenedSqlite(files, home);
801
- }
802
- // lsof field output escapes backslashes and non-ASCII bytes even with NUL field
803
- // delimiters. Decode the protected system tool's filename representation, then
804
- // compare exact canonical paths; never accept a prefix/substring match.
805
- function lsofFilename(raw) {
806
- const bytes = [];
807
- for (let i = 0; i < raw.length; i++) {
808
- if (raw[i] !== '\\') {
809
- const char = String.fromCodePoint(raw.codePointAt(i));
810
- bytes.push(...Buffer.from(char));
811
- i += char.length - 1;
812
- continue;
813
- }
814
- const next = raw[++i];
815
- if (next === '\\') {
816
- bytes.push(92);
817
- continue;
818
- }
819
- if (next === 'x' && /^[0-9a-f]{2}$/i.test(raw.slice(i + 1, i + 3))) {
820
- bytes.push(parseInt(raw.slice(i + 1, i + 3), 16));
821
- i += 2;
822
- continue;
823
- }
824
- throw new AppServerFault('storage_binding_unverified', false);
825
- }
826
- try {
827
- return new TextDecoder('utf-8', { fatal: true }).decode(Buffer.from(bytes));
828
- }
829
- catch {
830
- throw new AppServerFault('storage_binding_unverified', false);
831
- }
851
+ return verifyOpenedSqlite(files, home);
832
852
  }
833
853
  function executableIdentity(binary) {
834
854
  try {
@@ -870,21 +890,39 @@ export async function nativeQueueOnceWithProfiles(options, table) {
870
890
  // Reject malformed effect input before even a version probe or bootstrap can
871
891
  // start the binary and access/create native files in the selected home.
872
892
  validateQueueInput(options, false);
873
- // In the qualified versions config.sqlite_home precedes CODEX_SQLITE_HOME. Pin BOTH env and
874
- // a quoted CLI value so an ordinary config A->B->A load cannot redirect us.
875
- // Managed policy can still supersede the CLI pin, hence the FD-path check.
876
- const env = { ...(options.env ?? process.env), CODEX_HOME: original.codexHome,
877
- CODEX_SQLITE_HOME: original.codexHome };
878
893
  if (!await beforeDeadline(options.deadlineMs, () => options.verifyOwner(original), 'owner_changed'))
879
894
  throw new AppServerFault('owner_changed', false);
880
895
  if (performance.now() >= options.deadlineMs)
881
896
  throw new AppServerFault('deadline', false);
897
+ const consumerCwd = await codexConsumerCwd(original.codexHome, original.threadId).catch(() => {
898
+ throw new AppServerFault('storage_binding_unverified', false);
899
+ });
900
+ const checkStorage = (version) => {
901
+ const value = classifyCodexStorage({ home: original.codexHome, queueCwd: original.codexHome,
902
+ consumerCwds: [consumerCwd], ownedAppServer: true, version, environment: options.env ?? process.env });
903
+ if (value.status !== 'classified')
904
+ throw new AppServerFault('storage_binding_unverified', false);
905
+ return value;
906
+ };
907
+ const initialStorage = checkStorage();
908
+ const consumerDatabase = codexConsumerSnapshotSync(original.codexHome, original.threadId).database;
909
+ const revalidateStorage = async (version) => {
910
+ if (await codexConsumerCwd(original.codexHome, original.threadId).catch(() => '') !== consumerCwd ||
911
+ checkStorage(version).fingerprint !== initialStorage.fingerprint)
912
+ throw new AppServerFault('storage_binding_unverified', false);
913
+ };
914
+ // In the qualified versions config.sqlite_home precedes CODEX_SQLITE_HOME. Pin BOTH env and
915
+ // a quoted CLI value so an ordinary config A->B->A load cannot redirect us.
916
+ // Managed policy can still supersede the CLI pin, hence the FD-path check.
917
+ const inherited = Object.fromEntries(Object.entries(options.env ?? process.env).filter(([key]) => !['CODEX_HOME', 'CODEX_SQLITE_HOME'].includes(key.toUpperCase())));
918
+ const env = { ...inherited, CODEX_HOME: original.codexHome,
919
+ CODEX_SQLITE_HOME: original.codexHome, PWD: initialStorage.queueCwd };
882
920
  const binaryIdentity = executableIdentity(options.binary);
883
921
  const probeRemaining = options.deadlineMs - performance.now();
884
922
  if (probeRemaining <= 0)
885
923
  throw new AppServerFault('deadline', false);
886
924
  const version = await run(options.binary, ['--version'], {
887
- env, timeout: probeRemaining, limit: 4096,
925
+ env, cwd: initialStorage.queueCwd, timeout: probeRemaining, limit: 4096,
888
926
  });
889
927
  if (performance.now() >= options.deadlineMs)
890
928
  throw new AppServerFault('deadline', false);
@@ -894,6 +932,7 @@ export async function nativeQueueOnceWithProfiles(options, table) {
894
932
  throw new AppServerFault('unsupported_version', false);
895
933
  }
896
934
  verifyExecutableIdentity(options.binary, binaryIdentity);
935
+ await revalidateStorage(nativeVersion);
897
936
  if (performance.now() >= options.deadlineMs)
898
937
  throw new AppServerFault('deadline', false);
899
938
  if (profile.artifact) {
@@ -917,8 +956,9 @@ export async function nativeQueueOnceWithProfiles(options, table) {
917
956
  verifyOwnedSqliteBinding(pid, original.codexHome, options.deadlineMs);
918
957
  const transport = { qualification: 'native_queue_only_stdio',
919
958
  ...spawnOwnedStdio(options.binary, ['app-server', '--stdio', '-c', 'analytics.enabled=false',
920
- '-c', `sqlite_home=${JSON.stringify(original.codexHome)}`], env, original.codexHome) };
959
+ '-c', codexStoragePin(original.codexHome)], env, original.codexHome) };
921
960
  let client;
961
+ let lastBinding;
922
962
  try {
923
963
  verifyExecutableIdentity(options.binary, binaryIdentity);
924
964
  let effectGuarded = false;
@@ -927,12 +967,34 @@ export async function nativeQueueOnceWithProfiles(options, table) {
927
967
  if (valid && effectGuarded) {
928
968
  // Run after the LAST asynchronous owner verification. The durable guard
929
969
  // and owner probe can both await I/O and change canonical file bindings.
930
- verifyExecutableIdentity(options.binary, binaryIdentity);
931
- await bind(transport.pid);
970
+ try {
971
+ await options.verifyStorage?.();
972
+ await revalidateStorage(nativeVersion);
973
+ lastBinding = await bind(transport.pid);
974
+ }
975
+ catch (error) {
976
+ throw error instanceof AppServerFault ? error : new AppServerFault('storage_binding_unverified', false);
977
+ }
932
978
  }
933
979
  return valid;
934
- }, async () => { await options.beforeEffect(); effectGuarded = true; }, profile);
935
- await bind(transport.pid);
980
+ }, async () => { await options.beforeEffect(); effectGuarded = true; }, profile, () => {
981
+ // The effect writer calls this after its final await, before setting the
982
+ // attempted marker. No async callback follows these continuity checks.
983
+ try {
984
+ options.verifyStorageSync?.();
985
+ if (checkStorage(nativeVersion).fingerprint !== initialStorage.fingerprint)
986
+ throw new Error();
987
+ const current = codexConsumerSnapshotSync(original.codexHome, original.threadId);
988
+ if (current.database !== consumerDatabase || current.cwd !== consumerCwd)
989
+ throw new Error();
990
+ revalidateSqliteBinding(lastBinding);
991
+ verifyExecutableIdentity(options.binary, binaryIdentity);
992
+ }
993
+ catch (error) {
994
+ throw error instanceof AppServerFault ? error : new AppServerFault('storage_binding_unverified', false);
995
+ }
996
+ });
997
+ lastBinding = await bind(transport.pid);
936
998
  return await client.queueOnce({ clientUserMessageId: options.clientUserMessageId, message: options.message });
937
999
  }
938
1000
  finally {
package/dist/cli.js CHANGED
@@ -1,11 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
  import { handoffCommand, handoffSend, prepareHandoff, privateMessage } from './handoff-operations.js';
3
+ import { receiptCommand } from './receipt-command.js';
4
+ import { managedReceiptSend } from './receipt-send.js';
3
5
  import { canonicalId, closed, HANDOFF_LIMITS, HandoffBudget, parseStrictJson, parseWaitTimeout, safeInteger, systemClock } from './handoff.js';
4
6
  import { doctor } from './diagnostics.js';
5
7
  import { help } from './help.js';
6
8
  import { renderOutput } from './output.js';
7
9
  import { hostname } from 'node:os';
8
10
  import { lstatSync } from 'node:fs';
11
+ import { isAbsolute } from 'node:path';
9
12
  import { listing, Refusal } from './discovery.js';
10
13
  import { executable, run, UnknownOutcome } from './process.js';
11
14
  import { checkMessage, send, CodexUnknownOutcome } from './send.js';
@@ -16,7 +19,7 @@ import { CHANNELS, checkUpdate, noticeText, refreshCache, refuseSelfUpdate, REFR
16
19
  import { jumpOptions, sshConfig, sshJump, sshOptions } from './ssh.js';
17
20
  import { configuredHost, detectedHost, isSelf, probeReturnRoute, unsafeReturnHost, replyUri, returnHost, route, sender, tailnet } from './replies.js';
18
21
  const FLAGS = ['--json', '--all', '--dry-run', '--no-from', '--no-reply-to', '--no-update-notice', '--allow-inactive-codex-home', '--check-return-route', '--check', '--request-ack', '--observe-delivery'];
19
- const VALUES = ['--agent', '--codex-home', '--codex-bin', '--output-format', '--to', '--message', '-m', '--host', '--remote-bin', '--remote-platform', '--ssh-control-path', '--reply-address', '--ssh-opt', '--ssh-jump', '--reply-to', '--return-route-host', '--channel', '--correlation-id', '--wait-for', '--wait-timeout', '--message-file'];
22
+ const VALUES = ['--agent', '--codex-home', '--codex-bin', '--output-format', '--to', '--message', '-m', '--host', '--remote-bin', '--remote-platform', '--ssh-control-path', '--reply-address', '--ssh-opt', '--ssh-jump', '--reply-to', '--return-route-host', '--channel', '--correlation-id', '--wait-for', '--wait-timeout', '--message-file', '--receipt-collector'];
20
23
  // Repeated in order; every other value option is single.
21
24
  const REPEATED = ['--host', '--ssh-opt'];
22
25
  // Requested destinations, so a command-wide refusal can be attributed to each.
@@ -91,6 +94,16 @@ export function parse(args) {
91
94
  if (!flags.has('--json') && !values.has('--output-format'))
92
95
  throw new Refusal('json_output_required');
93
96
  const handoff = flags.has('--request-ack') || flags.has('--observe-delivery') || values.has('--correlation-id') || values.has('--wait-for') || values.has('--wait-timeout');
97
+ if (values.has('--receipt-collector')) {
98
+ const selector = values.get('--receipt-collector');
99
+ if (command !== 'send' || !isAbsolute(selector) || selector.includes('\0') || hosts.length ||
100
+ repeated.get('--ssh-opt').length || values.has('--remote-bin') || values.has('--remote-platform') ||
101
+ values.has('--ssh-control-path') || values.has('--ssh-jump') || values.has('--correlation-id') ||
102
+ flags.has('--observe-delivery') || values.get('--wait-for') === 'delivered' || flags.has('--allow-inactive-codex-home'))
103
+ throw new Refusal('inapplicable_option');
104
+ if (!flags.has('--dry-run') && !flags.has('--request-ack') && values.get('--wait-for') !== 'acknowledged')
105
+ throw new Refusal('receipt_opt_in_required', 2);
106
+ }
94
107
  if (handoff) {
95
108
  if (command !== 'send')
96
109
  throw new Refusal('inapplicable_option');
@@ -172,6 +185,8 @@ export function parse(args) {
172
185
  if (process.platform === 'win32' || values.get('--remote-platform') === 'win32')
173
186
  throw new Refusal('remote_handoff_unsupported', 1);
174
187
  }
188
+ if (values.has('--receipt-collector') && hosts.length)
189
+ throw new Refusal('remote_receipt_unsupported', 1);
175
190
  if (command === 'send' && flags.has('--allow-inactive-codex-home')) {
176
191
  if (!values.get('--to').startsWith('codex:'))
177
192
  throw new Refusal('inapplicable_option');
@@ -469,8 +484,35 @@ try {
469
484
  else if (args.length === 1 && args[0] === '--version')
470
485
  console.log(VERSION_LINE);
471
486
  else if ((args.length === 1 && ['--help', '-h'].includes(args[0])) ||
472
- (args.length === 2 && ['list', 'send', 'doctor', 'update', 'handoff', 'ack'].includes(args[0]) && ['--help', '-h'].includes(args[1])))
487
+ (args.length === 2 && ['list', 'send', 'doctor', 'update', 'handoff', 'ack', 'receipt'].includes(args[0]) && ['--help', '-h'].includes(args[1])))
473
488
  console.log(help(args.length === 2 ? args[0] : undefined));
489
+ else if (args[0] === 'receipt') {
490
+ command = 'receipt';
491
+ const operation = await receiptCommand(args, (limit, privateInput, timeoutMs) => input(limit, privateInput ?? true, timeoutMs));
492
+ console.log(JSON.stringify(operation.raw ? operation.value : { schemaVersion: 1, host: hostname(), command, ok: operation.exitCode === 0, ...operation.value }));
493
+ process.exitCode = operation.exitCode;
494
+ if (operation.collector) {
495
+ const collector = operation.collector;
496
+ let stopping = false;
497
+ const stop = (code) => {
498
+ if (stopping)
499
+ return;
500
+ stopping = true;
501
+ void collector.close().then(result => {
502
+ process.removeListener('SIGINT', interrupt);
503
+ process.removeListener('SIGTERM', terminate);
504
+ process.exitCode = code;
505
+ if (result.cleanup !== 'confirmed') {
506
+ console.error('receipt_cleanup_unconfirmed');
507
+ process.exit(code || 1);
508
+ }
509
+ }, () => { console.error('receipt_cleanup_unconfirmed'); process.exit(code || 1); });
510
+ };
511
+ const interrupt = () => stop(130), terminate = () => stop(143);
512
+ process.once('SIGINT', interrupt);
513
+ process.once('SIGTERM', terminate);
514
+ }
515
+ }
474
516
  else if (args[0] === 'handoff' || args[0] === 'ack') {
475
517
  command = args[0];
476
518
  const operation = await handoffCommand(args, limit => input(limit, true));
@@ -530,6 +572,8 @@ try {
530
572
  }
531
573
  command = ['list', 'send', 'doctor', 'update'].includes(args[0] ?? '') ? args[0] : 'unknown';
532
574
  const options = parse(args);
575
+ if (wire && options.values.has('--receipt-collector'))
576
+ throw new Refusal('remote_receipt_unsupported', 1);
533
577
  const handoffEnabled = options.flags.has('--request-ack') || options.flags.has('--observe-delivery') || options.values.has('--correlation-id') || options.values.has('--wait-for') || options.values.has('--wait-timeout');
534
578
  if (wire && (handoffEnabled !== !!wireContext || handoffEnabled !== !!wireBudget))
535
579
  throw new Refusal('remote_handoff_context_required', 1);
@@ -649,6 +693,12 @@ try {
649
693
  const enabled = options.flags.has('--request-ack') || options.flags.has('--observe-delivery') || options.values.has('--correlation-id') || options.values.has('--wait-for') || options.values.has('--wait-timeout');
650
694
  if (wireContext?.preparation)
651
695
  ({ value: result, exitCode } = await prepareHandoff(settings, undefined, options.values.get('--correlation-id'), handoffBudget));
696
+ else if (options.values.has('--receipt-collector'))
697
+ ({ value: result, exitCode } = await managedReceiptSend(settings, {
698
+ collector: options.values.get('--receipt-collector'), requestAck: options.flags.has('--request-ack'),
699
+ waitFor: options.values.get('--wait-for'),
700
+ seconds: parseWaitTimeout(options.values.get('--wait-timeout') ?? '30'), payload: rawMessage, budget: handoffBudget
701
+ }));
652
702
  else if (enabled)
653
703
  ({ value: result, exitCode } = await handoffSend(settings, { remote: wireContext !== undefined, correlationId: options.values.get('--correlation-id'), requestAck: options.flags.has('--request-ack'), observeDelivery: options.flags.has('--observe-delivery'), waitFor: options.values.get('--wait-for'), seconds: parseWaitTimeout(options.values.get('--wait-timeout') ?? '30'), payload: rawMessage, budget: handoffBudget, resultOverhead: Buffer.byteLength(JSON.stringify(routing)) + 1024 }));
654
704
  else
@@ -691,8 +741,8 @@ try {
691
741
  }
692
742
  catch (error) {
693
743
  // A command-wide refusal before dispatch applies to every requested host.
694
- if (command === 'handoff' || command === 'ack') {
695
- const failureCode = error instanceof Refusal ? error.code : 'handoff_operation_failed';
744
+ if (command === 'handoff' || command === 'ack' || command === 'receipt') {
745
+ const failureCode = error instanceof Refusal ? error.code : command === 'receipt' ? 'receipt_operation_failed' : 'handoff_operation_failed';
696
746
  console.log(JSON.stringify({ schemaVersion: 1, host: hostname(), command, ok: false, error: failureCode }));
697
747
  process.exitCode = error instanceof Refusal ? error.exitCode : 1;
698
748
  }