session-peer 0.5.2 → 0.6.1

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 (45) hide show
  1. package/CONTRIBUTING.md +11 -5
  2. package/PARITY.md +20 -5
  3. package/README.ja.md +8 -8
  4. package/README.ko.md +8 -8
  5. package/README.md +8 -8
  6. package/README.zh-CN.md +8 -8
  7. package/RELEASING.md +116 -0
  8. package/VALIDATION.md +137 -1
  9. package/dist/cli.js +54 -4
  10. package/dist/diagnostics.js +17 -98
  11. package/dist/discovery.d.ts +32 -0
  12. package/dist/discovery.js +405 -68
  13. package/dist/handoff-operations.js +88 -34
  14. package/dist/help.js +18 -2
  15. package/dist/macos-acl.d.ts +10 -0
  16. package/dist/macos-acl.js +75 -0
  17. package/dist/output.js +6 -1
  18. package/dist/protocol.d.ts +2 -2
  19. package/dist/protocol.js +1 -1
  20. package/dist/receipt-collector.d.ts +12 -0
  21. package/dist/receipt-collector.js +283 -0
  22. package/dist/receipt-command.d.ts +10 -0
  23. package/dist/receipt-command.js +246 -0
  24. package/dist/receipt-producer.d.ts +7 -0
  25. package/dist/receipt-producer.js +107 -0
  26. package/dist/receipt-protocol.d.ts +219 -0
  27. package/dist/receipt-protocol.js +374 -0
  28. package/dist/receipt-send.d.ts +26 -0
  29. package/dist/receipt-send.js +375 -0
  30. package/dist/receipt-state.d.ts +89 -0
  31. package/dist/receipt-state.js +503 -0
  32. package/dist/receipt-store.d.ts +32 -0
  33. package/dist/receipt-store.js +286 -0
  34. package/dist/replies.js +3 -1
  35. package/dist/send.d.ts +5 -2
  36. package/dist/send.js +34 -49
  37. package/dist/skill-metadata.js +5 -3
  38. package/docs/api.md +32 -7
  39. package/docs/design/typescript-skill-compatibility.md +48 -0
  40. package/docs/guide.ja.md +41 -15
  41. package/docs/guide.ko.md +43 -17
  42. package/docs/guide.md +42 -16
  43. package/docs/guide.zh-CN.md +41 -15
  44. package/docs/shorthand.md +1 -1
  45. package/package.json +3 -3
package/dist/discovery.js CHANGED
@@ -1,6 +1,8 @@
1
1
  // Read-only discovery: no inbox connections, writer selection, queue or DB writes.
2
2
  // Windows Claude metadata uses native process inspection.
3
- import { closeSync, constants, fstatSync, lstatSync, openSync, readlinkSync, readSync, readdirSync, realpathSync, statSync } from 'node:fs';
3
+ import { closeSync, constants, fstatSync, lstatSync, openSync, opendirSync, readlinkSync, readSync, readdirSync, realpathSync, statSync } from 'node:fs';
4
+ import { createHash } from 'node:crypto';
5
+ import { MACOS_ACL_LIMITS, inspectMacosAcls } from './macos-acl.js';
4
6
  import { homedir } from 'node:os';
5
7
  import { dirname, isAbsolute, join, resolve } from 'node:path';
6
8
  import { windowsProcessStart } from './windows.js';
@@ -50,31 +52,59 @@ function canonicalPath(absolute, seen) {
50
52
  return parent === absolute ? absolute : join(canonicalPath(parent, seen), absolute.slice(parent.length));
51
53
  }
52
54
  }
53
- function alive(pid) {
54
- if (pid <= 1)
55
- return false;
55
+ // Automatic profiles are a macOS Orca convention, not a recursive home scan.
56
+ export const CLAUDE_PROFILE_LIMIT = 128;
57
+ export const CLAUDE_ENTRY_LIMIT = 4096;
58
+ const CLAUDE_RECORD_LIMIT = 1024 * 1024;
59
+ const claudeProofs = new WeakMap();
60
+ const claudeInventories = new WeakMap();
61
+ const claudeAclPaths = new WeakMap();
62
+ export const CLAUDE_ACL_LIMITS = MACOS_ACL_LIMITS;
63
+ const nodeIdentity = (s) => [s.dev, s.ino, s.uid, s.mode].join(':');
64
+ const privateNode = (s) => typeof process.getuid === 'function' && s.uid === process.getuid() && (s.mode & 0o022) === 0;
65
+ const recordIdentity = (s) => [nodeIdentity(s), s.size, s.mtimeMs, s.ctimeMs, s.birthtimeMs].join(':');
66
+ function safeDirectory(path, sameUser, direct = true) {
67
+ const node = direct ? lstatSync(path) : statSync(path);
68
+ if (!node.isDirectory() || (sameUser && !privateNode(node)))
69
+ throw new Error('unsafe_directory');
70
+ return { path, sameUser, direct, identity: nodeIdentity(node) };
71
+ }
72
+ function directoryUnchanged(proof) {
73
+ return safeDirectory(proof.path, proof.sameUser, proof.direct).identity === proof.identity;
74
+ }
75
+ function boundedEntries(path, limit) {
76
+ const directory = opendirSync(path), entries = [];
56
77
  try {
57
- process.kill(pid, 0);
58
- return true;
78
+ while (true) {
79
+ const item = directory.readSync();
80
+ if (!item)
81
+ return { entries: entries.sort(compareText), limited: false };
82
+ if (entries.length >= limit)
83
+ return { entries: entries.sort(compareText), limited: true };
84
+ entries.push(item.name);
85
+ }
59
86
  }
60
- catch (error) {
61
- return error.code === 'EPERM';
87
+ finally {
88
+ directory.closeSync();
62
89
  }
63
90
  }
64
- // Local Claude registry metadata is limited to 1 MiB per regular file. The
65
- // descriptor checks and POSIX nonblocking open also cover replacement by a FIFO
66
- // between lstat and open; this is not a deadline for network filesystem I/O.
67
- function claudeRecord(file) {
68
- const limit = 1024 * 1024, before = lstatSync(file);
69
- if (!before.isFile() || before.size > limit)
91
+ // Reads bounded session-registration JSON, which may contain extra native
92
+ // fields. No separate credential/transcript files are opened and record contents
93
+ // are not persisted. Read at most 1 MiB + one
94
+ // overflow byte; stable descriptor/path checks are observational, not an atomic
95
+ // filesystem snapshot or a deadline for blocking filesystem I/O.
96
+ function claudeRecord(file, requirePrivate = false) {
97
+ const before = lstatSync(file);
98
+ if (!before.isFile() || before.size > CLAUDE_RECORD_LIMIT || (requirePrivate && !privateNode(before)))
70
99
  return undefined;
71
100
  const flags = constants.O_RDONLY | (process.platform === 'win32' ? 0 : constants.O_NONBLOCK | constants.O_NOFOLLOW);
72
101
  const fd = openSync(file, flags);
73
102
  try {
74
103
  const opened = fstatSync(fd);
75
- if (!opened.isFile() || opened.size > limit || opened.dev !== before.dev || opened.ino !== before.ino)
104
+ if (!opened.isFile() || opened.size > CLAUDE_RECORD_LIMIT || (requirePrivate && !privateNode(opened)) ||
105
+ recordIdentity(opened) !== recordIdentity(before))
76
106
  return undefined;
77
- const bytes = Buffer.alloc(limit + 1);
107
+ const bytes = Buffer.alloc(CLAUDE_RECORD_LIMIT + 1);
78
108
  let length = 0;
79
109
  while (length < bytes.length) {
80
110
  const count = readSync(fd, bytes, length, bytes.length - length, length);
@@ -82,74 +112,381 @@ function claudeRecord(file) {
82
112
  break;
83
113
  length += count;
84
114
  }
85
- // Read at most limit + 1 even if metadata grows after the descriptor check.
86
- if (length > limit || fstatSync(fd).size > limit)
115
+ const final = fstatSync(fd), current = lstatSync(file);
116
+ if (length > CLAUDE_RECORD_LIMIT || !current.isFile() ||
117
+ (requirePrivate && (!privateNode(final) || !privateNode(current))) || recordIdentity(final) !== recordIdentity(opened) ||
118
+ recordIdentity(current) !== recordIdentity(opened))
87
119
  return undefined;
88
- return JSON.parse(bytes.subarray(0, length).toString('utf8'));
120
+ return { value: JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(0, length))), identity: recordIdentity(opened) };
89
121
  }
90
122
  finally {
91
123
  closeSync(fd);
92
124
  }
93
125
  }
94
- export function claude(all) {
95
- const directory = join(process.env.CLAUDE_CONFIG_DIR || process.env.ANTHROPIC_CONFIG_DIR || join(homedir(), '.claude'), 'sessions');
96
- let entries;
126
+ function endpointIdentity(socket) {
127
+ if (!socket || socket.includes('\0'))
128
+ return null;
129
+ if (process.platform === 'win32')
130
+ return /^\\\\\.\\pipe\\[^\r\n]+$/i.test(socket) ? socket.toLowerCase() : null;
131
+ const alias = lstatSync(socket), canonical = realpathSync(socket), target = lstatSync(canonical);
132
+ return target.isSocket() ? JSON.stringify([canonical, alias.dev, alias.ino, target.dev, target.ino]) : null;
133
+ }
134
+ function claudeLive(record, matches, unknown, absent) {
135
+ if (!matches)
136
+ return false;
137
+ const pid = Number(record.pid);
138
+ if (pid <= 1)
139
+ return false; // Known-invalid PID is stale, not a failed native inspection.
140
+ if (process.platform !== 'win32') {
141
+ try {
142
+ process.kill(pid, 0);
143
+ return true;
144
+ }
145
+ catch (error) {
146
+ if (error.code !== 'ESRCH')
147
+ unknown?.();
148
+ return false;
149
+ }
150
+ }
151
+ const started = typeof record.startedAt === 'number' && Number.isSafeInteger(record.startedAt) && record.startedAt > 0 ? record.startedAt : NaN;
152
+ const ticks = windowsProcessStart(pid);
153
+ if (ticks === undefined) {
154
+ // A stale registry for a positively absent PID is not an inventory failure.
155
+ // Signal 0 is absence-only evidence here; it never establishes a live
156
+ // Windows incarnation or replaces the native creation-time check.
157
+ try {
158
+ process.kill(pid, 0);
159
+ }
160
+ catch (error) {
161
+ if (error.code === 'ESRCH') {
162
+ absent?.();
163
+ return false;
164
+ }
165
+ }
166
+ unknown?.();
167
+ return false;
168
+ }
169
+ const actual = Number((ticks - 116444736000000000n) / 10000n);
170
+ if (!Number.isFinite(started) || !Number.isFinite(actual)) {
171
+ unknown?.();
172
+ return false;
173
+ }
174
+ return actual <= started + 2000;
175
+ }
176
+ export function claudeInventory() {
177
+ const selected = join(process.env.CLAUDE_CONFIG_DIR || process.env.ANTHROPIC_CONFIG_DIR || join(homedir(), '.claude'), 'sessions');
178
+ const inventory = { sessions: [], errors: [], directories: [selected], records: 0,
179
+ invalidRecords: 0, permissionFailures: 0, unknownInspections: 0, selectedStatus: 'missing' };
180
+ const errors = inventory.errors;
181
+ const directories = [];
182
+ // Keep every observed source, numeric record and POSIX endpoint (including
183
+ // absence) fenced until the WHOLE inventory is complete. Later reads can
184
+ // mutate an earlier source without changing a directory entry.
185
+ const scanEvidence = [];
186
+ const aclPaths = new Set();
187
+ function observeMetadata(path, direct = true) {
188
+ let identity;
189
+ try {
190
+ identity = recordIdentity(direct ? lstatSync(path) : statSync(path));
191
+ }
192
+ catch (error) {
193
+ if (!missing(error))
194
+ throw error;
195
+ identity = null;
196
+ }
197
+ scanEvidence.push({ path, direct, identity });
198
+ }
199
+ function observeDirectory(path, sameUser, direct = true) {
200
+ observeMetadata(path, direct);
201
+ const proof = safeDirectory(path, sameUser, direct);
202
+ if (sameUser)
203
+ aclPaths.add(path);
204
+ return proof;
205
+ }
206
+ function failure(code, error) {
207
+ if (!errors.includes(code))
208
+ errors.push(code);
209
+ if (['EACCES', 'EPERM'].includes(error?.code ?? ''))
210
+ inventory.permissionFailures++;
211
+ }
97
212
  try {
98
- entries = readdirSync(directory).sort();
213
+ directories.push({ directory: selected, chain: [observeDirectory(selected, false, false)], automatic: false });
214
+ inventory.selectedStatus = 'present';
99
215
  }
100
216
  catch (error) {
101
- if (missing(error))
102
- entries = [];
103
- else
104
- throw new Refusal('claude_discovery_failed', 1);
105
- }
106
- const sessions = [];
107
- for (const entry of entries) {
108
- if (!/^[0-9]+\.json$/.test(entry))
109
- continue;
110
- let record;
217
+ if (!missing(error)) {
218
+ inventory.selectedStatus = ['EACCES', 'EPERM'].includes(error.code ?? '') ? 'permission_denied' :
219
+ error instanceof Error && error.message === 'unsafe_directory' ? 'unsupported' : 'unknown';
220
+ failure('sessions_directory_unavailable', error);
221
+ }
222
+ }
223
+ if (process.platform === 'darwin' && !process.env.CLAUDE_CONFIG_DIR && !process.env.ANTHROPIC_CONFIG_DIR) {
224
+ const base = join(homedir(), 'Library/Application Support/orca/claude-profiles');
111
225
  try {
112
- const value = claudeRecord(join(directory, entry));
113
- if (!value || typeof value !== 'object' || Array.isArray(value))
114
- continue;
115
- record = value;
226
+ const baseProof = observeDirectory(base, true), before = recordIdentity(lstatSync(base));
227
+ const found = boundedEntries(base, CLAUDE_PROFILE_LIMIT);
228
+ if (found.limited)
229
+ failure('profile_inventory_limit');
230
+ for (const name of found.entries) {
231
+ const profile = join(base, name);
232
+ try {
233
+ const node = lstatSync(profile);
234
+ if (node.isFile())
235
+ continue; // Finder/metadata files are not profile homes.
236
+ const chain = [baseProof, observeDirectory(profile, true), observeDirectory(join(profile, 'home'), true),
237
+ observeDirectory(join(profile, 'home/sessions'), true)];
238
+ const directory = join(profile, 'home/sessions');
239
+ directories.push({ directory, chain, automatic: true });
240
+ inventory.directories.push(directory);
241
+ }
242
+ catch (error) {
243
+ if (!missing(error))
244
+ failure('profile_directory_unavailable', error);
245
+ }
246
+ }
247
+ if (!directoryUnchanged(baseProof) || recordIdentity(lstatSync(base)) !== before)
248
+ failure('profile_inventory_changed');
116
249
  }
117
- catch {
118
- continue;
250
+ catch (error) {
251
+ if (!missing(error))
252
+ failure('profile_inventory_unavailable', error);
119
253
  }
120
- const pid = record.pid;
121
- if (typeof pid !== 'number' || !Number.isSafeInteger(pid) || pid > 2147483647)
122
- continue;
123
- const matches = pid === Number(entry.slice(0, -5));
124
- let live = matches && process.platform !== 'win32' && alive(pid);
125
- if (matches && process.platform === 'win32') {
126
- const started = typeof record.startedAt === 'number' && Number.isSafeInteger(record.startedAt) && record.startedAt > 0 ? record.startedAt : NaN;
127
- const ticks = windowsProcessStart(pid);
128
- const actual = ticks === undefined ? NaN : Number((ticks - 116444736000000000n) / 10000n);
129
- live = Number.isFinite(started) && Number.isFinite(actual) && actual <= started + 2000;
254
+ }
255
+ // Resolve the strictest requirements before deduplicating aliases. A legacy
256
+ // default path can alias an automatic registry; scanning that alias first
257
+ // must not downgrade the automatic record ownership/write-mode checks.
258
+ const automaticDirectories = new Set();
259
+ for (const item of directories.filter(item => item.automatic)) {
260
+ try {
261
+ automaticDirectories.add(realpathSync(item.directory));
130
262
  }
131
- const socket = typeof record.messagingSocketPath === 'string' ? record.messagingSocketPath : '';
132
- let inbox = false;
133
- if (socket) {
134
- if (process.platform === 'win32')
135
- inbox = /^\\\\\.\\pipe\\[^\r\n]+$/i.test(socket);
136
- else
263
+ catch (error) {
264
+ failure('profile_directory_unavailable', error);
265
+ }
266
+ }
267
+ const multiple = directories.some(item => item.automatic) || directories.length > 1 || errors.length > 0;
268
+ const invalid = () => { inventory.invalidRecords++; if (multiple)
269
+ failure('session_record_unavailable'); };
270
+ let enumerated = 0;
271
+ const scanned = new Set();
272
+ for (const { directory, chain } of directories) {
273
+ try {
274
+ if (!chain.every(directoryUnchanged))
275
+ throw new Error('registry_changed');
276
+ const canonical = realpathSync(directory), scanKey = canonical + ':' + chain.at(-1).identity;
277
+ const privateRecord = automaticDirectories.has(canonical);
278
+ if (scanned.has(scanKey))
279
+ continue;
280
+ scanned.add(scanKey);
281
+ const before = recordIdentity(statSync(directory));
282
+ const found = boundedEntries(directory, CLAUDE_ENTRY_LIMIT - enumerated);
283
+ enumerated += found.entries.length;
284
+ if (found.limited)
285
+ failure('session_inventory_limit');
286
+ for (const entry of found.entries) {
287
+ if (!/^[0-9]+\.json$/.test(entry))
288
+ continue;
289
+ const path = join(directory, entry);
290
+ let read;
137
291
  try {
138
- inbox = statSync(socket).isSocket();
292
+ // Every numeric record, including invalid/unreachable ones, remains
293
+ // fenced: an in-place edit can introduce a competing identity without
294
+ // changing its directory's metadata. Never reread bodies in the fence.
295
+ observeMetadata(path);
296
+ if (privateRecord)
297
+ aclPaths.add(path);
298
+ read = claudeRecord(path, privateRecord);
299
+ }
300
+ catch (error) {
301
+ if (['EACCES', 'EPERM'].includes(error.code ?? ''))
302
+ failure('record_unavailable', error);
303
+ else if (error instanceof SyntaxError || error instanceof TypeError || missing(error))
304
+ invalid();
305
+ else {
306
+ inventory.unknownInspections++;
307
+ failure('record_unavailable');
308
+ }
309
+ continue;
139
310
  }
140
- catch { /* Inaccessible is not reachable. */ }
311
+ const value = read?.value;
312
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
313
+ invalid();
314
+ continue;
315
+ }
316
+ const record = value, pid = record.pid;
317
+ if (typeof pid !== 'number' || !Number.isSafeInteger(pid) || pid < 1 || pid > 2147483647) {
318
+ invalid();
319
+ continue;
320
+ }
321
+ inventory.records++;
322
+ const matches = pid === Number(entry.slice(0, -5));
323
+ let processUnknown = false, processAbsent = false;
324
+ const live = claudeLive(record, matches, () => { processUnknown = true; inventory.unknownInspections++; failure('process_unverified'); }, () => { processAbsent = true; });
325
+ const socket = typeof record.messagingSocketPath === 'string' ? record.messagingSocketPath : '';
326
+ let endpoint = null;
327
+ try {
328
+ if (socket && !socket.includes('\0') && process.platform !== 'win32') {
329
+ // Track both advertised alias and followed endpoint, including an
330
+ // observed absence. Retargeting an unselected alias can otherwise
331
+ // introduce a conflict after its registry record was inspected.
332
+ observeMetadata(socket);
333
+ observeMetadata(socket, false);
334
+ }
335
+ endpoint = endpointIdentity(socket);
336
+ if (endpoint && process.platform !== 'win32')
337
+ observeMetadata(String(JSON.parse(endpoint)[0]));
338
+ }
339
+ catch (error) {
340
+ if (!missing(error)) {
341
+ inventory.unknownInspections++;
342
+ failure('endpoint_unavailable', error);
343
+ }
344
+ }
345
+ const row = { agent: 'claude', pid, socket, alive: live, reachable: live && endpoint !== null };
346
+ for (const key of ['name', 'status', 'cwd', 'kind', 'version', 'tmux'])
347
+ row[key] = record[key] ?? null;
348
+ if (!matches)
349
+ row.staleReason = 'record_pid_mismatch';
350
+ else if (processUnknown)
351
+ row.staleReason = 'process_unverified';
352
+ else if (!live && process.platform === 'win32')
353
+ row.staleReason = processAbsent ? 'process_absent' : 'process_unverified';
354
+ claudeProofs.set(row, { directory, canonical, chain, record: path, recordIdentity: read.identity, privateRecord,
355
+ endpoint, startedAt: typeof record.startedAt === 'number' ? record.startedAt : null });
356
+ inventory.sessions.push(row);
357
+ }
358
+ if (!chain.every(directoryUnchanged) || realpathSync(directory) !== canonical ||
359
+ recordIdentity(statSync(directory)) !== before)
360
+ failure('sessions_directory_changed');
141
361
  }
142
- const row = { agent: 'claude', pid, socket, alive: live, reachable: live && inbox };
143
- for (const key of ['name', 'status', 'cwd', 'kind', 'version', 'tmux'])
144
- row[key] = record[key] ?? null;
145
- if (!matches)
146
- row.staleReason = 'record_pid_mismatch';
147
- else if (!live && process.platform === 'win32')
148
- row.staleReason = 'process_unverified';
149
- if (all || row.reachable)
150
- sessions.push(row);
151
- }
152
- return { sessions, discovery: { claude: { status: 'ok' } } };
362
+ catch (error) {
363
+ failure('sessions_directory_unavailable', error);
364
+ }
365
+ }
366
+ const aclStatus = inspectMacosAcls([...aclPaths]);
367
+ if (aclStatus !== 'clear')
368
+ failure(aclStatus === 'acl' ? 'claude_extended_acl' : 'claude_acl_unavailable');
369
+ for (const observed of scanEvidence) {
370
+ let current;
371
+ try {
372
+ current = recordIdentity(observed.direct ? lstatSync(observed.path) : statSync(observed.path));
373
+ }
374
+ catch (error) {
375
+ if (!missing(error)) {
376
+ failure('claude_inventory_changed', error);
377
+ continue;
378
+ }
379
+ current = null;
380
+ }
381
+ if (current !== observed.identity)
382
+ failure('claude_inventory_changed');
383
+ }
384
+ const frozenEvidence = Object.freeze(scanEvidence.map(item => Object.freeze({ ...item })));
385
+ const frozenAclPaths = Object.freeze([...aclPaths]);
386
+ for (const row of inventory.sessions) {
387
+ claudeInventories.set(row, frozenEvidence);
388
+ claudeAclPaths.set(row, frozenAclPaths);
389
+ }
390
+ // Exact registry aliases are scanned once. Divergent live PID, inbox-string or
391
+ // underlying socket claims are conflicts, independent of directory order.
392
+ const byPid = new Map(), bySocket = new Map(), byEndpoint = new Map();
393
+ const conflicts = new Set();
394
+ for (const row of inventory.sessions) {
395
+ if (!row.alive)
396
+ continue;
397
+ const proof = claudeProofs.get(row), endpoint = proof.endpoint;
398
+ const underlying = endpoint && process.platform !== 'win32' ? JSON.stringify(JSON.parse(endpoint).slice(-2)) : endpoint;
399
+ const peers = new Set([...(byPid.get(Number(row.pid)) ?? []), ...(row.socket ? bySocket.get(String(row.socket)) ?? [] : []),
400
+ ...(underlying ? byEndpoint.get(underlying) ?? [] : [])]);
401
+ for (const other of peers) {
402
+ conflicts.add(other);
403
+ conflicts.add(row);
404
+ }
405
+ byPid.set(Number(row.pid), [...(byPid.get(Number(row.pid)) ?? []), row]);
406
+ if (row.socket)
407
+ bySocket.set(String(row.socket), [...(bySocket.get(String(row.socket)) ?? []), row]);
408
+ if (underlying)
409
+ byEndpoint.set(underlying, [...(byEndpoint.get(underlying) ?? []), row]);
410
+ }
411
+ if (conflicts.size)
412
+ failure('conflicting_session_records');
413
+ for (const row of conflicts) {
414
+ row.reachable = false;
415
+ row.staleReason = 'conflicting_session_records';
416
+ }
417
+ return inventory;
418
+ }
419
+ // Private provenance is not serialized in ordinary rows and never becomes a
420
+ // public native-generation claim. It binds the selected registry and endpoint
421
+ // across async hooks; it is not authentication against a same-user writer.
422
+ // Metadata-only final fence: identity validation above/below can itself read
423
+ // registry files. Call this AFTER those reads, without recursively rediscovering
424
+ // or reading another record and opening another unfenced inventory window.
425
+ export function revalidateClaudeInventory(row, other) {
426
+ const rows = other ? [row, other] : [row];
427
+ const evidence = [], paths = new Set();
428
+ for (const selected of rows) {
429
+ const metadata = claudeInventories.get(selected), acls = claudeAclPaths.get(selected);
430
+ if (!metadata || !acls)
431
+ throw new Refusal('claude_discovery_incomplete', 1);
432
+ evidence.push(...metadata);
433
+ for (const path of acls)
434
+ paths.add(path);
435
+ }
436
+ const metadataUnchanged = () => {
437
+ for (const observed of evidence) {
438
+ let current;
439
+ try {
440
+ current = recordIdentity(observed.direct ? lstatSync(observed.path) : statSync(observed.path));
441
+ }
442
+ catch (error) {
443
+ if (!missing(error))
444
+ throw new Refusal('claude_discovery_incomplete', 1);
445
+ current = null;
446
+ }
447
+ if (current !== observed.identity)
448
+ throw new Refusal('claude_discovery_incomplete', 1);
449
+ }
450
+ };
451
+ // An ACL/path mutation while the synchronous helper is running must not be
452
+ // accepted from an earlier clear result. These remain observational checks,
453
+ // not an atomic filesystem snapshot or a universal kernel-I/O deadline.
454
+ metadataUnchanged();
455
+ if (inspectMacosAcls([...paths]) !== 'clear')
456
+ throw new Refusal('claude_discovery_incomplete', 1);
457
+ metadataUnchanged();
458
+ }
459
+ export function claudeSelectionIdentity(row) {
460
+ const proof = claudeProofs.get(row);
461
+ if (!proof)
462
+ throw new Refusal('target_changed', 1);
463
+ try {
464
+ if (!proof.chain.every(directoryUnchanged) || realpathSync(proof.directory) !== proof.canonical)
465
+ throw new Error();
466
+ const read = claudeRecord(proof.record, proof.privateRecord), value = read?.value;
467
+ if (!read || !value || read.identity !== proof.recordIdentity || value.pid !== row.pid ||
468
+ (value.messagingSocketPath ?? '') !== row.socket ||
469
+ (typeof value.startedAt === 'number' ? value.startedAt : null) !== proof.startedAt ||
470
+ !claudeLive(value, true) || endpointIdentity(String(row.socket)) !== proof.endpoint)
471
+ throw new Error();
472
+ return createHash('sha256').update(JSON.stringify(proof)).digest('hex');
473
+ }
474
+ catch {
475
+ throw new Refusal('target_changed', 1);
476
+ }
477
+ }
478
+ export function claudeReceiptProvenance(row) {
479
+ const proof = claudeProofs.get(row);
480
+ if (!proof || process.platform === 'win32')
481
+ throw new Refusal('receipt_bootstrap_unsupported', 1);
482
+ return { registryDirectory: proof.canonical, registryRecordPath: realpathSync(proof.record),
483
+ registryIdentity: createHash('sha256').update(proof.recordIdentity).digest('hex'),
484
+ socketPath: resolve(String(row.socket)), routeIdentity: claudeSelectionIdentity(row) };
485
+ }
486
+ export function claude(all) {
487
+ const inventory = claudeInventory();
488
+ return { sessions: inventory.sessions.filter(row => all || row.reachable),
489
+ discovery: { claude: inventory.errors.length ? { status: 'error', code: 'claude_discovery_incomplete', errors: inventory.errors } : { status: 'ok' } } };
153
490
  }
154
491
  // Shared bounded sources; listing accumulates diagnostics while writer inventory
155
492
  // keeps its stricter, fail-closed policy. No recursive scan or credential reads.