@rarog/server 1.0.1 → 1.1.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 (140) hide show
  1. package/README.md +18 -5
  2. package/node_modules/@rarog/shared/package.json +1 -1
  3. package/node_modules/@rarog/shared/src/decode.js +64 -3
  4. package/node_modules/@rarog/shared/src/protocol/files.js +33 -0
  5. package/node_modules/@rarog/shared/src/protocol/folders.js +27 -0
  6. package/node_modules/@rarog/shared/src/protocol/herdr.js +23 -0
  7. package/node_modules/@rarog/shared/src/protocol/inbox.js +38 -0
  8. package/node_modules/@rarog/shared/src/protocol/notes.js +7 -1
  9. package/node_modules/@rarog/shared/src/protocol.js +20 -47
  10. package/node_modules/@rarog/shared/src/rest.js +106 -12
  11. package/node_modules/@rarog/shared/src/sentences/herdr.js +0 -4
  12. package/node_modules/@rarog/shared/src/sentences/index.js +7 -1
  13. package/node_modules/@rarog/shared/src/sentences/rest.js +21 -0
  14. package/package.json +3 -3
  15. package/server/src/auth/admin.js +3 -1
  16. package/server/src/bootstrap/consent.js +99 -2
  17. package/server/src/bootstrap/folder-gate.js +55 -0
  18. package/server/src/bootstrap/http.js +3 -2
  19. package/server/src/bootstrap/inbox.js +29 -4
  20. package/server/src/bootstrap/sse.js +2 -1
  21. package/server/src/cli/doctor-no-hook.js +162 -0
  22. package/server/src/cli/doctor.js +2 -0
  23. package/server/src/cli/service-log.js +27 -0
  24. package/server/src/cli/service.js +5 -2
  25. package/server/src/cli/templates/launchd.plist +1 -1
  26. package/server/src/cli/templates/rarog.service +1 -1
  27. package/server/src/cli/update-channel.js +100 -0
  28. package/server/src/cli/update-provenance.js +37 -19
  29. package/server/src/cli/update-registry.js +160 -62
  30. package/server/src/cli/update.js +13 -3
  31. package/server/src/companion/turns-settle.js +4 -1
  32. package/server/src/companion/turns.js +36 -5
  33. package/server/src/config/files.js +32 -0
  34. package/server/src/config/flags.js +10 -1
  35. package/server/src/config/protected-dirs.js +2 -0
  36. package/server/src/config/roots.js +13 -8
  37. package/server/src/config/work-area.js +36 -12
  38. package/server/src/config-env.js +33 -0
  39. package/server/src/config.js +22 -2
  40. package/server/src/demo/control.js +9 -1
  41. package/server/src/demo/files.js +49 -0
  42. package/server/src/demo/inbox.js +73 -0
  43. package/server/src/demo/review-routes.js +6 -1
  44. package/server/src/device-effects.js +3 -1
  45. package/server/src/drivers/herdr/consent-no-hook-io.js +89 -0
  46. package/server/src/drivers/herdr/consent-no-hook.js +411 -0
  47. package/server/src/drivers/herdr/refusals.js +226 -0
  48. package/server/src/drivers/herdr/returned-prompt.js +172 -0
  49. package/server/src/drivers/herdr/screen-fallback.js +246 -0
  50. package/server/src/drivers/herdr-driver.js +193 -295
  51. package/server/src/files/file-index.js +248 -0
  52. package/server/src/files/ignored.js +119 -0
  53. package/server/src/files/listing.js +82 -0
  54. package/server/src/files/path-rule.js +199 -0
  55. package/server/src/files/refusals.js +50 -0
  56. package/server/src/files/send-file.js +115 -0
  57. package/server/src/files/session-download.js +51 -0
  58. package/server/src/files/session-files.js +38 -0
  59. package/server/src/files/session-gate.js +53 -0
  60. package/server/src/folder-gate/client.js +314 -0
  61. package/server/src/folder-gate/disk.js +455 -0
  62. package/server/src/folder-gate/folders.js +23 -0
  63. package/server/src/folder-gate/gate.js +220 -0
  64. package/server/src/folder-gate/helper.js +118 -0
  65. package/server/src/folder-gate/install.js +27 -0
  66. package/server/src/folder-gate/relay-worker.js +147 -0
  67. package/server/src/folder-gate/types.js +115 -0
  68. package/server/src/folder-gate/wire.js +170 -0
  69. package/server/src/fs-browse.js +55 -23
  70. package/server/src/fs-mkdir.js +3 -1
  71. package/server/src/git-status.js +16 -7
  72. package/server/src/git-watch.js +130 -19
  73. package/server/src/git-work-tree.js +3 -3
  74. package/server/src/herdr/audit.js +1 -1
  75. package/server/src/herdr/client.js +2 -2
  76. package/server/src/herdr/commands/discover.js +21 -9
  77. package/server/src/herdr/dialogs/consent-gate.js +28 -8
  78. package/server/src/herdr/dialogs/decide/sources.js +5 -2
  79. package/server/src/herdr/dialogs/hook/contract.js +16 -9
  80. package/server/src/herdr/dialogs/index.js +12 -2
  81. package/server/src/herdr/dialogs/layer1/cycle.js +43 -7
  82. package/server/src/herdr/dialogs/layer1/hook-list/hook-list.js +166 -86
  83. package/server/src/herdr/dialogs/layer1/hook-list/session-facts.js +135 -0
  84. package/server/src/herdr/dialogs/layer1/screen-key.js +52 -0
  85. package/server/src/herdr/dialogs/layer1/version-gate.js +13 -5
  86. package/server/src/herdr/dialogs/no-hook.js +63 -0
  87. package/server/src/herdr/dialogs/router.js +21 -6
  88. package/server/src/herdr/dialogs/screen/block.js +10 -0
  89. package/server/src/herdr/dialogs/screen/parse.js +33 -3
  90. package/server/src/herdr/dialogs/screen/resolve.js +9 -7
  91. package/server/src/herdr/dialogs/screen-fallback.js +55 -0
  92. package/server/src/herdr/dialogs/shadow/alive.js +9 -8
  93. package/server/src/herdr/jsonl-follow.js +55 -14
  94. package/server/src/herdr/jsonl-pending.js +25 -1
  95. package/server/src/herdr/provenance.js +3 -3
  96. package/server/src/herdr/socket.js +25 -28
  97. package/server/src/herdr/supervisor.js +13 -10
  98. package/server/src/herdr/transcript-path.js +36 -0
  99. package/server/src/herdr/trust.js +11 -8
  100. package/server/src/herdr/uploads-registry.js +3 -2
  101. package/server/src/herdr/uploads.js +170 -47
  102. package/server/src/inbox/card.js +18 -9
  103. package/server/src/inbox/dialogs.js +40 -12
  104. package/server/src/inbox/heads.js +55 -0
  105. package/server/src/inbox/inbox.js +24 -2
  106. package/server/src/inbox/index.js +3 -1
  107. package/server/src/index.js +44 -21
  108. package/server/src/install/repair.js +8 -0
  109. package/server/src/iroh/listener.js +3 -0
  110. package/server/src/iroh/log-budget.js +1 -0
  111. package/server/src/iroh/socket.js +2 -1
  112. package/server/src/log-timestamps.js +9 -4
  113. package/server/src/notes/store.js +3 -2
  114. package/server/src/router.js +20 -2
  115. package/server/src/routes/devices.js +2 -2
  116. package/server/src/routes/inbox.js +91 -0
  117. package/server/src/routes/projects.js +5 -1
  118. package/server/src/routes/sessions.js +145 -18
  119. package/server/src/routes/system.js +9 -4
  120. package/server/src/safe-read.js +86 -1
  121. package/server/src/sessions/companion-scope.js +16 -7
  122. package/server/src/sessions/demo-modules.js +16 -0
  123. package/server/src/sessions/diff-measure.js +30 -0
  124. package/server/src/sessions/done-retention.js +57 -0
  125. package/server/src/sessions/launch-gate.js +2 -2
  126. package/server/src/sessions/manager.js +78 -190
  127. package/server/src/sessions/project-scan.js +9 -3
  128. package/server/src/sessions/ring-buffer.js +5 -3
  129. package/server/src/sessions/seen-marks.js +9 -6
  130. package/server/src/sessions/session-git.js +31 -2
  131. package/server/src/sessions/session-scope.js +30 -0
  132. package/server/src/sessions/session.js +19 -0
  133. package/server/src/sessions/state-sentences.js +1 -1
  134. package/server/src/sessions/waiting-line.js +72 -0
  135. package/server/src/sse.js +143 -10
  136. package/server/src/term/herdr-backend.js +2 -2
  137. package/server/src/term/index.js +2 -15
  138. package/server/src/term/registry.js +4 -3
  139. package/server/src/term/ws.js +9 -1
  140. package/server/src/version.js +30 -0
@@ -73,14 +73,17 @@
73
73
  * process (the desk fallback sends such a request back at once, `layer1/desk.ts`), transient (read again after
74
74
  * {@link HOOK_LIST_TRANSIENT_RETRY_MS}, sooner than the desk fallback's 10 s) or neither (kept as long as a durable one,
75
75
  * but the request waits the 10 s).
76
+ *
77
+ * The same read also runs over the current content ({@link currentSessionHooks}): no start check, so `changed` never
78
+ * stops it, and it hands over the settings layers it read. The session facts (`session-facts.ts`) read
79
+ * `disableAllHooks`, `allowManagedHooksOnly` and Rarog's entry from those layers; the verdict above ignores them.
76
80
  */
77
81
  import { execFile } from 'node:child_process';
78
- import fs from 'node:fs/promises';
79
82
  import path from 'node:path';
80
83
  import { DISK_LAYOUT } from '../../../commands/registry.js';
81
84
  import { parseElapsed } from '../../shadow/liveness.js';
82
85
  import { HOOK_PERMISSION_EVENT } from '../../../hook-commands.js';
83
- import { readRegularFile } from '../../../../safe-read.js';
86
+ import { DIRECT_DISK } from '../../../../folder-gate/disk.js';
84
87
  /** Zapas na rozdzielczość `etime` (pełne sekundy) i czas samego `ps`. */
85
88
  export const HOOK_LIST_START_SLACK_MS = 2_000;
86
89
  /** Rejestr CLI pisze `startedAt` 1–7 s po starcie procesu (`cli-version.ts`); zapas do 10 s. */
@@ -105,10 +108,14 @@ const TRANSIENT_CODES = new Set([
105
108
  'io', 'no-process', 'process-start', 'no-registry-entry', 'no-registry-start', 'registry-file', 'budget',
106
109
  'unparseable',
107
110
  ]);
108
- /** Kind of a negative verdict's `why` by its code, the part before the first `:`. */
109
- export function hookListVerdictKind(why) {
111
+ /** The code of a negative verdict's `why`: the part before the first `:`. */
112
+ export function hookListWhyCode(why) {
110
113
  const at = why.indexOf(':');
111
- const code = at < 0 ? why : why.slice(0, at);
114
+ return at < 0 ? why : why.slice(0, at);
115
+ }
116
+ /** Kind of a negative verdict's `why` by its code ({@link hookListWhyCode}). */
117
+ export function hookListVerdictKind(why) {
118
+ const code = hookListWhyCode(why);
112
119
  if (DURABLE_CODES.has(code))
113
120
  return 'durable';
114
121
  return TRANSIENT_CODES.has(code) ? 'transient' : 'other';
@@ -287,38 +294,66 @@ function mentionsEvent(value, depth = 0) {
287
294
  }
288
295
  return false;
289
296
  }
290
- /** Wpisy `PermissionRequest` warstwy: tylko komendy z `accepted`; inaczej powód. */
291
- function foreignHookOf(layer, accepted) {
297
+ /**
298
+ * The layer's `PermissionRequest` handlers in file order; `'hooks-shape'` stands where the entry stops having the
299
+ * documented shape, and the walk ends there.
300
+ */
301
+ function* permissionHandlers(layer) {
292
302
  const hooks = layer['hooks'];
293
303
  if (hooks === undefined)
294
- return null;
295
- if (hooks === null || typeof hooks !== 'object' || Array.isArray(hooks))
296
- return 'hooks-shape';
304
+ return;
305
+ if (hooks === null || typeof hooks !== 'object' || Array.isArray(hooks)) {
306
+ yield 'hooks-shape';
307
+ return;
308
+ }
297
309
  const groups = hooks[HOOK_PERMISSION_EVENT];
298
310
  if (groups === undefined)
299
- return null;
300
- if (!Array.isArray(groups))
301
- return 'hooks-shape';
311
+ return;
312
+ if (!Array.isArray(groups)) {
313
+ yield 'hooks-shape';
314
+ return;
315
+ }
302
316
  for (const group of groups) {
303
- if (group === null || typeof group !== 'object' || Array.isArray(group))
304
- return 'hooks-shape';
305
- const handlers = group['hooks'];
306
- if (!Array.isArray(handlers))
307
- return 'hooks-shape';
317
+ const handlers = group === null || typeof group !== 'object' || Array.isArray(group)
318
+ ? undefined : group['hooks'];
319
+ if (!Array.isArray(handlers)) {
320
+ yield 'hooks-shape';
321
+ return;
322
+ }
308
323
  for (const handler of handlers) {
309
- if (handler === null || typeof handler !== 'object' || Array.isArray(handler))
310
- return 'hooks-shape';
311
- const h = handler;
312
- const args = h['args'];
313
- const command = h['command'];
314
- if (h['type'] !== 'command' || typeof command !== 'string' || !accepted.includes(command))
315
- return 'foreign';
316
- if (args !== undefined && !(Array.isArray(args) && args.length === 0))
317
- return 'foreign';
324
+ if (handler === null || typeof handler !== 'object' || Array.isArray(handler)) {
325
+ yield 'hooks-shape';
326
+ return;
327
+ }
328
+ yield handler;
318
329
  }
319
330
  }
331
+ }
332
+ /** Rarog's handler: a `command` hook with a command from `accepted` and no `args`. */
333
+ function isRarogHandler(h, accepted) {
334
+ const args = h['args'];
335
+ const command = h['command'];
336
+ return h['type'] === 'command' && typeof command === 'string' && accepted.includes(command)
337
+ && (args === undefined || (Array.isArray(args) && args.length === 0));
338
+ }
339
+ /** Wpisy `PermissionRequest` warstwy: tylko komendy z `accepted`; inaczej powód. */
340
+ function foreignHookOf(layer, accepted) {
341
+ for (const h of permissionHandlers(layer)) {
342
+ if (h === 'hooks-shape')
343
+ return 'hooks-shape';
344
+ if (!isRarogHandler(h, accepted))
345
+ return 'foreign';
346
+ }
320
347
  return null;
321
348
  }
349
+ /** Whether the layer holds Rarog's `PermissionRequest` handler ({@link isRarogHandler}), beside anything else. */
350
+ export function rarogHookIn(layer, accepted) {
351
+ for (const h of permissionHandlers(layer)) {
352
+ if (h !== 'hooks-shape' && isRarogHandler(h, accepted))
353
+ return true;
354
+ }
355
+ return false;
356
+ }
322
357
  const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
323
358
  /** Obiekt JSON z treści pliku albo `null` (brak pliku); nie-JSON i nie-obiekt = brak dowodu. */
324
359
  function objectOf(file, text) {
@@ -509,20 +544,62 @@ function upwards(dir) {
509
544
  current = parent;
510
545
  }
511
546
  }
547
+ /** The negative verdict of a read that threw. */
548
+ function verdictOf(err) {
549
+ if (err instanceof HookListNoProof)
550
+ return { ok: false, why: err.message };
551
+ const code = err.code;
552
+ return { ok: false, why: `io:${typeof code === 'string' ? code : 'error'}` };
553
+ }
512
554
  /** Werdykt listy hooków jednej sesji z jednego odczytu (opis modułu). */
513
555
  export async function sessionHookVerdict(input, io) {
514
556
  try {
515
- await collect(input, io);
557
+ await scanHooks(await readLayers(input, io, false), input, io);
516
558
  return { ok: true };
517
559
  }
518
560
  catch (err) {
519
- if (err instanceof HookListNoProof)
520
- return { ok: false, why: err.message };
521
- const code = err.code;
522
- return { ok: false, why: `io:${typeof code === 'string' ? code : 'error'}` };
561
+ return verdictOf(err);
523
562
  }
524
563
  }
525
- async function collect(input, io) {
564
+ /**
565
+ * The same read as {@link sessionHookVerdict} over the files as they are now: a file, link or marketplace refresh at or
566
+ * after the session start does not stop it, so past a `changed` it still says whether a foreign hook stands anywhere.
567
+ */
568
+ export async function currentSessionHooks(input, io) {
569
+ let read = null;
570
+ try {
571
+ read = await readLayers(input, io, true);
572
+ await scanHooks(read, input, io);
573
+ return { verdict: { ok: true }, layers: read.layers, settingSources: read.settingSources };
574
+ }
575
+ catch (err) {
576
+ return { verdict: verdictOf(err), layers: read?.layers ?? null, settingSources: read?.settingSources ?? false };
577
+ }
578
+ }
579
+ /**
580
+ * `cwd` of the CLI registry file of the session process, or `null` when the file is missing, does not parse or names
581
+ * another session. The CLI rewrites the file while the process lives (`status`, `updatedAt`, CLI 2.1.321), so its change
582
+ * is not a change of hooks and it skips the start check.
583
+ */
584
+ export async function sessionRegistryCwd(io, home, pid, sessionId) {
585
+ const registryText = await io.readFile(path.join(home, DISK_LAYOUT.configDir, 'sessions', `${pid}.json`));
586
+ let registryFile = null;
587
+ try {
588
+ registryFile = registryText === null ? null : JSON.parse(registryText);
589
+ }
590
+ catch {
591
+ registryFile = null;
592
+ }
593
+ const registryRecord = registryFile !== null && typeof registryFile === 'object' && !Array.isArray(registryFile)
594
+ ? registryFile : null;
595
+ const registryCwd = registryRecord?.['cwd'];
596
+ return registryRecord?.['sessionId'] !== sessionId || typeof registryCwd !== 'string' ? null : registryCwd;
597
+ }
598
+ /**
599
+ * The session process, its arguments and every settings layer (module header), up to the hook scan; `current` turns
600
+ * the start check off ({@link currentSessionHooks}).
601
+ */
602
+ async function readLayers(input, io, current) {
526
603
  if (input.platform !== 'darwin')
527
604
  throw new HookListNoProof('platform');
528
605
  const entry = input.entry;
@@ -542,25 +619,13 @@ async function collect(input, io) {
542
619
  const args = parseClaudeArgs(proc.args);
543
620
  if ('why' in args)
544
621
  throw new HookListNoProof(args.why);
545
- const reader = new Reader(io, startLow);
622
+ const changedFrom = current ? Number.POSITIVE_INFINITY : startLow;
623
+ const reader = new Reader(io, changedFrom);
546
624
  const claude = path.join(input.home, DISK_LAYOUT.configDir);
547
- // Plik rejestru sesji: `cwd` sesji i ta sama sesja pod tym pidem. CLI przepisuje go w trakcie życia procesu (pola
548
- // `status` i `updatedAt`, CLI 2.1.321), więc jego zmiana nie jest zmianą hooków i nie przechodzi przez sprawdzenie
549
- // startu.
550
- const registryText = await io.readFile(path.join(claude, 'sessions', `${entry.pid}.json`));
551
- let registryFile = null;
552
- try {
553
- registryFile = registryText === null ? null : JSON.parse(registryText);
554
- }
555
- catch {
556
- registryFile = null;
557
- }
558
- const registryRecord = registryFile !== null && typeof registryFile === 'object' && !Array.isArray(registryFile)
559
- ? registryFile : null;
560
- const registryCwd = registryRecord?.['cwd'];
561
- if (registryRecord?.['sessionId'] !== input.sessionId || typeof registryCwd !== 'string') {
625
+ // Plik rejestru sesji: `cwd` sesji i ta sama sesja pod tym pidem.
626
+ const registryCwd = await sessionRegistryCwd(io, input.home, entry.pid, input.sessionId);
627
+ if (registryCwd === null)
562
628
  throw new HookListNoProof('registry-file');
563
- }
564
629
  const cwds = [...new Set([registryCwd, ...input.cwds])];
565
630
  if (cwds.some((cwd) => !path.isAbsolute(cwd)))
566
631
  throw new HookListNoProof('cwd');
@@ -572,7 +637,7 @@ async function collect(input, io) {
572
637
  const addLayer = async (name, file, certain = false) => {
573
638
  const value = await reader.layer(file);
574
639
  if (value !== null)
575
- layers.push({ name, value, certain });
640
+ layers.push({ name, value, certain, file });
576
641
  };
577
642
  // Managed (macOS): preferencje MDM (systemowe i per użytkownik) = brak dowodu; pliki, katalog dopisków, kopia
578
643
  // z serwera.
@@ -600,13 +665,13 @@ async function collect(input, io) {
600
665
  // `--settings`.
601
666
  for (const one of args.settings) {
602
667
  if (one.kind === 'inline') {
603
- layers.push({ name: 'flag', value: one.json, certain: true });
668
+ layers.push({ name: 'flag', value: one.json, certain: true, file: null });
604
669
  }
605
670
  else {
606
671
  const value = await reader.layer(one.path);
607
672
  if (value === null)
608
673
  throw new HookListNoProof('settings-file');
609
- layers.push({ name: 'flag', value, certain: true });
674
+ layers.push({ name: 'flag', value, certain: true, file: one.path });
610
675
  }
611
676
  }
612
677
  // Użytkownik, projekt, local; `cwd` w linked worktree dokłada główny checkout (opis modułu).
@@ -628,6 +693,11 @@ async function collect(input, io) {
628
693
  for (const dir of [...localDirs].sort()) {
629
694
  await addLayer('local', path.join(dir, DISK_LAYOUT.configDir, DISK_LAYOUT.localSettings));
630
695
  }
696
+ return { reader, claude, layers, localDirs, changedFrom, settingSources: args.settingSources };
697
+ }
698
+ /** Hook entries of the layers, then plugins and definitions (module header): throws at the first doubt. */
699
+ async function scanHooks(read, input, io) {
700
+ const { reader, claude, layers, localDirs, changedFrom } = read;
631
701
  for (const layer of layers) {
632
702
  const foreign = foreignHookOf(layer.value, input.accepted);
633
703
  if (foreign !== null)
@@ -679,7 +749,7 @@ async function collect(input, io) {
679
749
  throw new HookListNoProof(`plugin-missing:${id}`);
680
750
  await reader.tree(installPath, [PLUGIN_IN_USE_DIR]);
681
751
  }
682
- await checkMarketplaceEntry(reader, { plugins, id, marketplaces, startLow });
752
+ await checkMarketplaceEntry(reader, { plugins, id, marketplaces, startLow: changedFrom });
683
753
  }
684
754
  await syncedTrees(io, reader, path.join(plugins, SYNCED_DIR));
685
755
  // Agenci, skille, komendy użytkownika i projektu (`cwd` i wyżej); skille z claude.ai w `skills/synced/`.
@@ -819,8 +889,10 @@ async function checkMarketplaceEntry(reader, ctx) {
819
889
  if (source['path'] !== location)
820
890
  throw new HookListNoProof(`marketplace-source:${market}`);
821
891
  const updated = typeof record['lastUpdated'] === 'string' ? Date.parse(record['lastUpdated']) : Number.NaN;
822
- if (!Number.isFinite(updated) || updated >= startLow)
892
+ // Over the current content (`startLow` infinite) the refresh time does not matter, also when it is unknown.
893
+ if (Number.isFinite(startLow) && (!Number.isFinite(updated) || updated >= startLow)) {
823
894
  throw new HookListNoProof(`marketplace-changed:${market}`);
895
+ }
824
896
  // `file`: sam plik marketplace'u, korzeń dwa katalogi wyżej (`<korzeń>/.claude-plugin/marketplace.json`).
825
897
  catalogFile = kind === 'directory' ? path.join(location, defaultFile) : location;
826
898
  localRoot = kind === 'directory' ? location : path.dirname(path.dirname(location));
@@ -854,32 +926,40 @@ function absent(err) {
854
926
  return null;
855
927
  throw err;
856
928
  }
929
+ /** Milliseconds with the fraction the number form of `stat` carries; the port's bigint `*Ms` drops it. */
930
+ const msOf = (ns) => Number(ns) / 1e6;
931
+ /** The disk side of {@link HookListIo} on a work-area disk: settings layers lie under home and in project folders. */
932
+ function hookListDiskIo(disk) {
933
+ return {
934
+ async lstat(file) {
935
+ const info = await disk.call('lstat', { path: file }).catch(absent);
936
+ if (info === null)
937
+ return null;
938
+ const kind = info.isSymbolicLink() ? 'link' : info.isFile() ? 'file' : info.isDirectory() ? 'dir' : 'other';
939
+ return { kind, size: Number(info.size), changedAt: Math.max(msOf(info.ctimeNs), msOf(info.mtimeNs)) };
940
+ },
941
+ readlink: (file) => disk.call('readlink', { path: file }),
942
+ // Odczyt przez `safe-read.ts`: FIFO albo urządzenie pod nazwą pliku ustawień nie zawiesza serwera. Nie-plik
943
+ // i plik ponad sufit to błąd z kodem, więc lista daje „brak dowodu”, a nie pustą warstwę.
944
+ async readFile(file) {
945
+ let read;
946
+ try {
947
+ read = await disk.call('readHead', { path: file, maxBytes: HOOK_LIST_MAX_FILE_BYTES, followSymlink: true });
948
+ }
949
+ catch (err) {
950
+ return absent(err);
951
+ }
952
+ if (read === null)
953
+ throw Object.assign(new Error(`not a regular file: ${file}`), { code: 'EFTYPE' });
954
+ if (read.truncated)
955
+ throw Object.assign(new Error(`over the read ceiling: ${file}`), { code: 'EFBIG' });
956
+ return read.bytes.toString('utf8');
957
+ },
958
+ readdir: (dir) => disk.call('readdirNames', { path: dir }).then((names) => [...names], absent),
959
+ };
960
+ }
857
961
  export const nodeHookListIo = {
858
- async lstat(file) {
859
- const info = await fs.lstat(file).catch(absent);
860
- if (info === null)
861
- return null;
862
- const kind = info.isSymbolicLink() ? 'link' : info.isFile() ? 'file' : info.isDirectory() ? 'dir' : 'other';
863
- return { kind, size: info.size, changedAt: Math.max(info.ctimeMs, info.mtimeMs) };
864
- },
865
- readlink: (file) => fs.readlink(file),
866
- // Odczyt przez `safe-read.ts`: FIFO albo urządzenie pod nazwą pliku ustawień nie zawiesza serwera. Nie-plik
867
- // i plik ponad sufit to błąd z kodem, więc lista daje „brak dowodu”, a nie pustą warstwę.
868
- async readFile(file) {
869
- let read;
870
- try {
871
- read = await readRegularFile(file, { maxBytes: HOOK_LIST_MAX_FILE_BYTES, followSymlink: true });
872
- }
873
- catch (err) {
874
- return absent(err);
875
- }
876
- if (read === null)
877
- throw Object.assign(new Error(`not a regular file: ${file}`), { code: 'EFTYPE' });
878
- if (read.truncated)
879
- throw Object.assign(new Error(`over the read ceiling: ${file}`), { code: 'EFBIG' });
880
- return read.bytes.toString('utf8');
881
- },
882
- readdir: (dir) => fs.readdir(dir).catch(absent),
962
+ ...hookListDiskIo(DIRECT_DISK),
883
963
  ps: (pid) => new Promise((resolve) => {
884
964
  execFile(PS_PATH, ['-ww', '-o', 'etime=,args=', '-p', String(pid)], {
885
965
  timeout: PS_TIMEOUT_MS, killSignal: 'SIGKILL', env: { LC_ALL: 'C' }, maxBuffer: 1024 * 1024,
@@ -896,11 +976,11 @@ export const nodeHookListIo = {
896
976
  }),
897
977
  };
898
978
  /** How long a negative verdict lives before the next read: transient ones shorter ({@link hookListVerdictKind}). */
899
- function retryOf(why) {
979
+ export function hookListRetryMs(why) {
900
980
  return hookListVerdictKind(why) === 'transient' ? HOOK_LIST_TRANSIENT_RETRY_MS : HOOK_LIST_RETRY_MS;
901
981
  }
902
982
  /** The session process a verdict was read for: registry pid and start; `''` without a registry entry. */
903
- function processOf(entry) {
983
+ export function sessionProcessKey(entry) {
904
984
  return entry === null ? '' : `${String(entry.pid)}@${String(entry.startedAt ?? '')}`;
905
985
  }
906
986
  const NO_ANSWER = { keys: new Set(), why: null };
@@ -925,8 +1005,8 @@ export function createSessionHookList(options) {
925
1005
  sessionId, home: options.home, accepted: options.accepted, entry, cwds: [...cwds],
926
1006
  platform: options.platform ?? process.platform, now: at,
927
1007
  }, io);
928
- const proc = processOf(entry);
929
- if (processOf(await options.entry(sessionId)) !== proc)
1008
+ const proc = sessionProcessKey(entry);
1009
+ if (sessionProcessKey(await options.entry(sessionId)) !== proc)
930
1010
  return null;
931
1011
  const before = cache.get(sessionId)?.verdict;
932
1012
  const done = { at, proc, cwds, verdict };
@@ -945,14 +1025,14 @@ export function createSessionHookList(options) {
945
1025
  const cwds = new Set(asked.map((dump) => dump.cwd));
946
1026
  const newest = Math.max(...asked.map((dump) => dump.startedAt));
947
1027
  const entry = await options.entry(sessionId);
948
- const proc = processOf(entry);
1028
+ const proc = sessionProcessKey(entry);
949
1029
  const cached = cache.get(sessionId);
950
1030
  // An `ok` over a wider scope holds for a narrower one; a negative verdict may come from a `cwd` this call does not
951
1031
  // ask about, so it holds only for the very same scope.
952
1032
  const fresh = cached !== undefined && cached.proc === proc && [...cwds].every((cwd) => cached.cwds.has(cwd))
953
1033
  && (cached.verdict.ok
954
1034
  ? cached.at >= newest
955
- : cached.cwds.size === cwds.size && clock() - cached.at < retryOf(cached.verdict.why));
1035
+ : cached.cwds.size === cwds.size && clock() - cached.at < hookListRetryMs(cached.verdict.why));
956
1036
  let found = fresh ? cached : null;
957
1037
  if (found === null) {
958
1038
  // One read per process and scope at a time; a call for another process or `cwd` does not wait for this one.
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Session facts for a consent dialog that has no hook dump: one read of the session process, its `cwd` from the
3
+ * session registry file, the call `cwd` from the transcript entry, the hook list verdict and the settings layers.
4
+ * Everything comes from the hook list read (`hook-list.ts`) scoped to the registry `cwd` read at the start of the
5
+ * query; this module adds the layer precedence and the cache. It only reads and writes no log line: the subagent hook
6
+ * list keeps its own cache and verdict log.
7
+ *
8
+ * The facts of one read hold while the session process, its registry `cwd` and the episode (the caller's identity of
9
+ * the dialog) stay the same; a negative read is read again in the same episode after its kind's retry time
10
+ * (`hookListRetryMs`), so a transient doubt can mend on the same card.
11
+ */
12
+ import path from 'node:path';
13
+ import { DISK_LAYOUT } from '../../../commands/registry.js';
14
+ import { currentSessionHooks, hookListRetryMs, hookListWhyCode, nodeHookListIo, rarogHookIn, sessionHookVerdict, sessionProcessKey, sessionRegistryCwd, } from './hook-list.js';
15
+ /** Settings precedence, highest first (Claude Code documentation, "Settings files and precedence"). */
16
+ const PRECEDENCE = ['managed', 'flag', 'local', 'project', 'user'];
17
+ /** Codes of a current read that found a foreign hook or a hook entry of another shape. */
18
+ const FOREIGN_CODES = new Set(['foreign', 'hooks-shape', 'hook-in', 'hook-escape']);
19
+ const DISABLE_ALL_HOOKS = 'disableAllHooks';
20
+ const ALLOW_MANAGED_HOOKS_ONLY = 'allowManagedHooksOnly';
21
+ /** The one value of `values`, `null` when they are not all the same boolean. */
22
+ function sameBoolean(values) {
23
+ const first = values[0];
24
+ return typeof first === 'boolean' && values.every((one) => one === first) ? first : null;
25
+ }
26
+ /**
27
+ * Whether a layer surely takes part in the session's settings, as opposed to a layer the read superset adds that may
28
+ * not. Surely: a layer the hook list marks `certain` (a `--settings` file, and the user `settings.json` without
29
+ * `--setting-sources`), and, without `--setting-sources` (Claude Code CLI reference: the sources to load), the project
30
+ * and local file of the session `cwd`. Claude Code documentation, "Where Claude Code keeps the local file in a git
31
+ * repository": the shared `.claude/settings.json` is read from the session's primary working directory, and the local
32
+ * file in the starting directory is read too (beside the one at the repository root, or as the only one outside a
33
+ * repository); local files above `cwd` and the main checkout's files may not be. No managed layer is sure: by default
34
+ * Claude Code applies only the highest-ranked managed source that delivers a policy key and ignores the rest even
35
+ * where the selected one leaves a key unset, and fetches remote settings only with an eligible credential (managed
36
+ * settings documentation, "How Claude Code combines managed sources").
37
+ */
38
+ function sureLayer(cwd, settingSources) {
39
+ const own = cwd === null || settingSources ? null : path.join(path.resolve(cwd), DISK_LAYOUT.configDir);
40
+ // Inline `--settings` JSON is not sure: `ps` loses argument bounds, so the same text may stand inside a prompt.
41
+ return (layer) => (layer.certain && !(layer.name === 'flag' && layer.file === null)) || (own !== null && ((layer.name === 'project' && layer.file === path.join(own, DISK_LAYOUT.settings))
42
+ || (layer.name === 'local' && layer.file === path.join(own, DISK_LAYOUT.localSettings))));
43
+ }
44
+ /**
45
+ * A boolean key after precedence over the read superset, fail-closed: tier by tier from the highest of `tiers`, the
46
+ * values of every layer that may be loaded count, down to and including the first tier where a surely loaded layer
47
+ * ({@link sureLayer}) sets the key; without such a tier the default `false` counts too. The key is the one boolean
48
+ * they all give, else `null`.
49
+ */
50
+ function settingOf(layers, key, tiers, sure) {
51
+ const values = [];
52
+ for (const tier of tiers) {
53
+ const setting = layers.filter((layer) => layer.name === tier && Object.hasOwn(layer.value, key));
54
+ values.push(...setting.map((layer) => layer.value[key]));
55
+ if (setting.some(sure))
56
+ return sameBoolean(values);
57
+ }
58
+ return sameBoolean([...values, false]);
59
+ }
60
+ function layerFactsOf(layers, sure, accepted) {
61
+ return {
62
+ rarogEntry: layers.some((layer) => rarogHookIn(layer.value, accepted)),
63
+ disableAllHooks: settingOf(layers, DISABLE_ALL_HOOKS, PRECEDENCE, sure),
64
+ allowManagedHooksOnly: settingOf(layers, ALLOW_MANAGED_HOOKS_ONLY, ['managed'], sure),
65
+ };
66
+ }
67
+ function foreignHookOf(current) {
68
+ if (current.ok)
69
+ return false;
70
+ return FOREIGN_CODES.has(hookListWhyCode(current.why)) ? true : null;
71
+ }
72
+ /** How long the facts hold within their episode: for good when both reads are `ok`, else the shortest retry time. */
73
+ function holdMs(facts) {
74
+ const whys = [facts.verdict, facts.current].flatMap((one) => (one.ok ? [] : [one.why]));
75
+ return whys.length === 0 ? Number.POSITIVE_INFINITY : Math.min(...whys.map(hookListRetryMs));
76
+ }
77
+ /** The call `cwd` of the query: absolute only, never a guess. */
78
+ const callCwdOf = (entryCwd) => entryCwd !== undefined && path.isAbsolute(entryCwd) ? entryCwd : undefined;
79
+ /**
80
+ * The session facts read over the same options as the session hook list (`createSessionHookList`), with a cache of
81
+ * its own (module header). The registry `cwd` is read on every call (one small file) to see a `cwd` change, and again
82
+ * at the end of a read: a read that ends on another `cwd` than it started with gives no facts.
83
+ */
84
+ export function createSessionFacts(options) {
85
+ const io = options.io ?? nodeHookListIo;
86
+ const clock = options.now ?? Date.now;
87
+ const cache = new Map();
88
+ const running = new Map();
89
+ /** `cwd` of the registry file of the session process, `null` without an entry or a readable file. */
90
+ const registryCwdOf = async (sessionId, entry) => entry === null ? null : sessionRegistryCwd(io, options.home, entry.pid, sessionId).catch(() => null);
91
+ async function compute(sessionId, entry, cwd, episode) {
92
+ const at = clock();
93
+ // Each scan reads the registry `cwd` again on its own; with the start `cwd` beside it, a `cwd` that moved during
94
+ // the read and back still has its directories scanned (a superset of them), so the facts never stand for a
95
+ // directory no scan read.
96
+ const input = (now) => ({
97
+ sessionId, home: options.home, accepted: options.accepted, entry, cwds: cwd === null ? [] : [cwd],
98
+ platform: options.platform ?? process.platform, now,
99
+ });
100
+ const verdict = await sessionHookVerdict(input(at), io);
101
+ const current = await currentSessionHooks(input(clock()), io);
102
+ const proc = sessionProcessKey(entry);
103
+ const end = await options.entry(sessionId);
104
+ if (sessionProcessKey(end) !== proc || await registryCwdOf(sessionId, end) !== cwd)
105
+ return null;
106
+ const facts = {
107
+ episode, process: entry, cwd, verdict, current: current.verdict, foreignHook: foreignHookOf(current.verdict),
108
+ layers: current.layers === null ? null
109
+ : layerFactsOf(current.layers, sureLayer(cwd, current.settingSources), options.accepted),
110
+ };
111
+ const done = { at, proc, cwd, episode, facts };
112
+ cache.set(sessionId, done);
113
+ return done;
114
+ }
115
+ return async (query) => {
116
+ const { sessionId, episode } = query;
117
+ const entry = await options.entry(sessionId);
118
+ const proc = sessionProcessKey(entry);
119
+ const cwd = await registryCwdOf(sessionId, entry);
120
+ const cached = cache.get(sessionId);
121
+ let found = cached !== undefined && cached.proc === proc && cached.cwd === cwd && cached.episode === episode
122
+ && clock() - cached.at < holdMs(cached.facts) ? cached : null;
123
+ if (found === null) {
124
+ // One read per process, `cwd` and episode at a time.
125
+ const key = JSON.stringify([sessionId, proc, cwd, episode]);
126
+ let job = running.get(key);
127
+ if (job === undefined) {
128
+ job = compute(sessionId, entry, cwd, episode).finally(() => running.delete(key));
129
+ running.set(key, job);
130
+ }
131
+ found = await job;
132
+ }
133
+ return found === null ? null : { ...found.facts, callCwd: callCwdOf(query.entryCwd) };
134
+ };
135
+ }
@@ -0,0 +1,52 @@
1
+ /** How long a key ties a late hook to it. */
2
+ export const SCREEN_KEY_TTL_MS = 60_000;
3
+ /** Slack before the episode start: the hook process may start a moment before the registry or the pane says so. */
4
+ export const SCREEN_KEY_START_SLACK_MS = 2_000;
5
+ /** Keys kept per session; a dialog series past it drops the oldest. */
6
+ const KEYS_PER_SESSION = 16;
7
+ /**
8
+ * The call the match reads for a new record: the hook start and the input digest from its registration on the socket
9
+ * when there is one, since the first dump the record comes from is not authenticated; the dump's own without it.
10
+ */
11
+ export function screenKeyCallOf(record, entry) {
12
+ return {
13
+ sessionId: record.sessionId, toolName: record.toolName,
14
+ inputSha256: entry?.inputSha256 ?? record.inputSha256, hookStartedAt: entry?.startedAt ?? record.hookStartedAt,
15
+ };
16
+ }
17
+ export function createConsentScreenKeys(now) {
18
+ const bySession = new Map();
19
+ const live = (sessionId) => {
20
+ const at = now();
21
+ const keys = (bySession.get(sessionId) ?? []).filter((key) => at - key.at <= SCREEN_KEY_TTL_MS);
22
+ if (keys.length === 0)
23
+ bySession.delete(sessionId);
24
+ else
25
+ bySession.set(sessionId, keys);
26
+ return keys;
27
+ };
28
+ return {
29
+ note: (sessionId, key) => {
30
+ bySession.set(sessionId, [...live(sessionId), key].slice(-KEYS_PER_SESSION));
31
+ },
32
+ answered: (call) => live(call.sessionId).some((key) => key.toolName === call.toolName
33
+ && key.inputSha256 === call.inputSha256 && call.hookStartedAt <= key.at
34
+ && call.hookStartedAt >= key.since - SCREEN_KEY_START_SLACK_MS),
35
+ };
36
+ }
37
+ /** `consent: screen fallback late hook — …`: the request of a hook that registered after the emergency key. */
38
+ export function screenKeyLateHookLine(sessionId, key, thread, release) {
39
+ return `consent: screen fallback late hook — session ${sessionId}, key ${key}, thread ${thread}, `
40
+ + `release ${release}`;
41
+ }
42
+ /**
43
+ * The request of a hook that registered after the emergency key answered its dialog: its `pending` record, written
44
+ * without publishing, is settled at once as when its dialog is gone, main thread and subagent alike, so the devices
45
+ * only get the settled card, never the approve button, and its hook is released. A release write that failed is
46
+ * retried by the cycle at the next observation with the key's dump; the record stays settled.
47
+ */
48
+ export function lateHook(record, port) {
49
+ const thread = record.agentId === null ? 'main' : 'subagent';
50
+ port.log(screenKeyLateHookLine(record.sessionId, record.key, thread, 'dialog-gone'));
51
+ return port.releaseHook(port.revoke(record, 'dialog-gone'));
52
+ }
@@ -1,8 +1,9 @@
1
1
  /**
2
2
  * The Claude Code version gate of the proof rule: on which releases a session counts the `channel` rule,
3
3
  * per request kind (main thread, subagent requests). The base is the package constant
4
- * {@link CONSENT_CHANNEL_MEASURED_CLI}; the canary file `<dataDir>/consent-canary.json` adds exact releases on which
5
- * the canary command measured the contract (`pass`) and takes away releases where it failed (`fail`).
4
+ * {@link CONSENT_CHANNEL_MEASURED_CLI}: releases up to its `cli` except the exact releases in its `excluded`. The
5
+ * canary file `<dataDir>/consent-canary.json` adds exact releases on which the canary command measured the contract
6
+ * (`pass`) and takes away releases where it failed (`fail`).
6
7
  *
7
8
  * This module reads the file through the regular-file gate (`safe-read.ts`) and never writes it; the gate with
8
9
  * its log line is `createConsentProofGate` in `observe.ts`. Any doubt about the file gives the package base alone,
@@ -114,8 +115,9 @@ export function createConsentCanaryFile(dataDir) {
114
115
  * 1. configuration `screen` (`RAROG_CONSENT_PROOF`), or the release unknown (no single process of the session in the
115
116
  * registry read, a string outside the release shape) → `screen`;
116
117
  * 2. `fail` → `screen`;
117
- * 3. the release not above {@link CONSENT_CHANNEL_MEASURED_CLI} → `channel`;
118
- * 4. `pass` → `channel`;
118
+ * 3. the release in the package base (not above `cli` of {@link CONSENT_CHANNEL_MEASURED_CLI}, not in its
119
+ * `excluded`) → `channel`;
120
+ * 4. `pass` → `channel`, also on an excluded release;
119
121
  * 5. the rest (`unmeasured`, no entry) → `screen`.
120
122
  *
121
123
  * MCP tools stay at `screen` in the request rule (`consentKeyRule`, `consentHiddenKeyRule` in `proof.ts`).
@@ -125,10 +127,16 @@ export function consentProofRuleOf(configured, cliVersion, result) {
125
127
  return 'screen';
126
128
  if (result === 'fail')
127
129
  return 'screen';
128
- if (compareCliVersions(cliVersion, CONSENT_CHANNEL_MEASURED_CLI.cli) <= 0)
130
+ if (inPackageBase(cliVersion))
129
131
  return 'channel';
130
132
  return result === 'pass' ? 'channel' : 'screen';
131
133
  }
134
+ /** Whether release `cliVersion` (in the release shape) is covered by {@link CONSENT_CHANNEL_MEASURED_CLI}. */
135
+ function inPackageBase(cliVersion) {
136
+ const { cli, excluded } = CONSENT_CHANNEL_MEASURED_CLI;
137
+ return compareCliVersions(cliVersion, cli) <= 0
138
+ && !excluded.some((release) => compareCliVersions(cliVersion, release) === 0);
139
+ }
132
140
  /** The entry of release `cliVersion` in the read; `null` = none (no file read, no exact entry). */
133
141
  export function consentCanaryEntry(canary, cliVersion) {
134
142
  if (canary.kind !== 'read' || cliVersion === undefined)