@rarog/server 1.0.1 → 1.1.0-beta.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 (78) hide show
  1. package/README.md +4 -3
  2. package/node_modules/@rarog/shared/package.json +1 -1
  3. package/node_modules/@rarog/shared/src/decode.js +49 -3
  4. package/node_modules/@rarog/shared/src/protocol/files.js +33 -0
  5. package/node_modules/@rarog/shared/src/protocol/inbox.js +38 -0
  6. package/node_modules/@rarog/shared/src/protocol.js +16 -17
  7. package/node_modules/@rarog/shared/src/rest.js +106 -12
  8. package/node_modules/@rarog/shared/src/sentences/rest.js +13 -0
  9. package/package.json +3 -3
  10. package/server/src/bootstrap/consent.js +88 -2
  11. package/server/src/bootstrap/http.js +3 -2
  12. package/server/src/bootstrap/inbox.js +29 -4
  13. package/server/src/bootstrap/sse.js +2 -1
  14. package/server/src/cli/doctor-no-hook.js +162 -0
  15. package/server/src/cli/doctor.js +2 -0
  16. package/server/src/cli/update-channel.js +100 -0
  17. package/server/src/cli/update-registry.js +160 -62
  18. package/server/src/cli/update.js +13 -3
  19. package/server/src/companion/turns-settle.js +4 -1
  20. package/server/src/companion/turns.js +36 -5
  21. package/server/src/config/files.js +32 -0
  22. package/server/src/config/flags.js +10 -1
  23. package/server/src/config-env.js +24 -0
  24. package/server/src/config.js +6 -2
  25. package/server/src/demo/files.js +49 -0
  26. package/server/src/demo/inbox.js +73 -0
  27. package/server/src/demo/review-routes.js +6 -1
  28. package/server/src/device-effects.js +3 -1
  29. package/server/src/drivers/herdr/consent-no-hook-io.js +89 -0
  30. package/server/src/drivers/herdr/consent-no-hook.js +316 -0
  31. package/server/src/drivers/herdr/refusals.js +226 -0
  32. package/server/src/drivers/herdr/returned-prompt.js +172 -0
  33. package/server/src/drivers/herdr-driver.js +116 -287
  34. package/server/src/files/file-index.js +246 -0
  35. package/server/src/files/ignored.js +119 -0
  36. package/server/src/files/listing.js +76 -0
  37. package/server/src/files/path-rule.js +145 -0
  38. package/server/src/files/refusals.js +36 -0
  39. package/server/src/files/send-file.js +115 -0
  40. package/server/src/files/session-download.js +51 -0
  41. package/server/src/files/session-files.js +38 -0
  42. package/server/src/files/session-gate.js +48 -0
  43. package/server/src/git-status.js +3 -2
  44. package/server/src/herdr/audit.js +1 -1
  45. package/server/src/herdr/dialogs/hook/contract.js +16 -9
  46. package/server/src/herdr/dialogs/index.js +6 -1
  47. package/server/src/herdr/dialogs/layer1/hook-list/hook-list.js +132 -59
  48. package/server/src/herdr/dialogs/layer1/hook-list/session-facts.js +135 -0
  49. package/server/src/herdr/dialogs/layer1/version-gate.js +13 -5
  50. package/server/src/herdr/dialogs/no-hook.js +63 -0
  51. package/server/src/herdr/dialogs/screen/block.js +10 -0
  52. package/server/src/herdr/dialogs/screen/parse.js +10 -1
  53. package/server/src/herdr/jsonl-pending.js +25 -1
  54. package/server/src/inbox/card.js +18 -9
  55. package/server/src/inbox/dialogs.js +40 -12
  56. package/server/src/inbox/heads.js +55 -0
  57. package/server/src/inbox/inbox.js +24 -2
  58. package/server/src/inbox/index.js +3 -1
  59. package/server/src/index.js +22 -18
  60. package/server/src/install/repair.js +8 -0
  61. package/server/src/log-timestamps.js +9 -4
  62. package/server/src/router.js +7 -1
  63. package/server/src/routes/devices.js +2 -2
  64. package/server/src/routes/inbox.js +91 -0
  65. package/server/src/routes/sessions.js +135 -14
  66. package/server/src/routes/system.js +5 -4
  67. package/server/src/safe-read.js +86 -1
  68. package/server/src/sessions/companion-scope.js +6 -2
  69. package/server/src/sessions/demo-modules.js +16 -0
  70. package/server/src/sessions/diff-measure.js +30 -0
  71. package/server/src/sessions/manager.js +64 -152
  72. package/server/src/sessions/ring-buffer.js +18 -3
  73. package/server/src/sessions/seen-marks.js +9 -6
  74. package/server/src/sessions/session-scope.js +30 -0
  75. package/server/src/sessions/session.js +20 -1
  76. package/server/src/sessions/waiting-line.js +72 -0
  77. package/server/src/sse.js +40 -6
  78. package/server/src/version.js +30 -0
@@ -73,6 +73,10 @@
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
82
  import fs from 'node:fs/promises';
@@ -105,10 +109,14 @@ const TRANSIENT_CODES = new Set([
105
109
  'io', 'no-process', 'process-start', 'no-registry-entry', 'no-registry-start', 'registry-file', 'budget',
106
110
  'unparseable',
107
111
  ]);
108
- /** Kind of a negative verdict's `why` by its code, the part before the first `:`. */
109
- export function hookListVerdictKind(why) {
112
+ /** The code of a negative verdict's `why`: the part before the first `:`. */
113
+ export function hookListWhyCode(why) {
110
114
  const at = why.indexOf(':');
111
- const code = at < 0 ? why : why.slice(0, at);
115
+ return at < 0 ? why : why.slice(0, at);
116
+ }
117
+ /** Kind of a negative verdict's `why` by its code ({@link hookListWhyCode}). */
118
+ export function hookListVerdictKind(why) {
119
+ const code = hookListWhyCode(why);
112
120
  if (DURABLE_CODES.has(code))
113
121
  return 'durable';
114
122
  return TRANSIENT_CODES.has(code) ? 'transient' : 'other';
@@ -287,38 +295,66 @@ function mentionsEvent(value, depth = 0) {
287
295
  }
288
296
  return false;
289
297
  }
290
- /** Wpisy `PermissionRequest` warstwy: tylko komendy z `accepted`; inaczej powód. */
291
- function foreignHookOf(layer, accepted) {
298
+ /**
299
+ * The layer's `PermissionRequest` handlers in file order; `'hooks-shape'` stands where the entry stops having the
300
+ * documented shape, and the walk ends there.
301
+ */
302
+ function* permissionHandlers(layer) {
292
303
  const hooks = layer['hooks'];
293
304
  if (hooks === undefined)
294
- return null;
295
- if (hooks === null || typeof hooks !== 'object' || Array.isArray(hooks))
296
- return 'hooks-shape';
305
+ return;
306
+ if (hooks === null || typeof hooks !== 'object' || Array.isArray(hooks)) {
307
+ yield 'hooks-shape';
308
+ return;
309
+ }
297
310
  const groups = hooks[HOOK_PERMISSION_EVENT];
298
311
  if (groups === undefined)
299
- return null;
300
- if (!Array.isArray(groups))
301
- return 'hooks-shape';
312
+ return;
313
+ if (!Array.isArray(groups)) {
314
+ yield 'hooks-shape';
315
+ return;
316
+ }
302
317
  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';
318
+ const handlers = group === null || typeof group !== 'object' || Array.isArray(group)
319
+ ? undefined : group['hooks'];
320
+ if (!Array.isArray(handlers)) {
321
+ yield 'hooks-shape';
322
+ return;
323
+ }
308
324
  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';
325
+ if (handler === null || typeof handler !== 'object' || Array.isArray(handler)) {
326
+ yield 'hooks-shape';
327
+ return;
328
+ }
329
+ yield handler;
318
330
  }
319
331
  }
332
+ }
333
+ /** Rarog's handler: a `command` hook with a command from `accepted` and no `args`. */
334
+ function isRarogHandler(h, accepted) {
335
+ const args = h['args'];
336
+ const command = h['command'];
337
+ return h['type'] === 'command' && typeof command === 'string' && accepted.includes(command)
338
+ && (args === undefined || (Array.isArray(args) && args.length === 0));
339
+ }
340
+ /** Wpisy `PermissionRequest` warstwy: tylko komendy z `accepted`; inaczej powód. */
341
+ function foreignHookOf(layer, accepted) {
342
+ for (const h of permissionHandlers(layer)) {
343
+ if (h === 'hooks-shape')
344
+ return 'hooks-shape';
345
+ if (!isRarogHandler(h, accepted))
346
+ return 'foreign';
347
+ }
320
348
  return null;
321
349
  }
350
+ /** Whether the layer holds Rarog's `PermissionRequest` handler ({@link isRarogHandler}), beside anything else. */
351
+ export function rarogHookIn(layer, accepted) {
352
+ for (const h of permissionHandlers(layer)) {
353
+ if (h !== 'hooks-shape' && isRarogHandler(h, accepted))
354
+ return true;
355
+ }
356
+ return false;
357
+ }
322
358
  const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
323
359
  /** Obiekt JSON z treści pliku albo `null` (brak pliku); nie-JSON i nie-obiekt = brak dowodu. */
324
360
  function objectOf(file, text) {
@@ -509,20 +545,62 @@ function upwards(dir) {
509
545
  current = parent;
510
546
  }
511
547
  }
548
+ /** The negative verdict of a read that threw. */
549
+ function verdictOf(err) {
550
+ if (err instanceof HookListNoProof)
551
+ return { ok: false, why: err.message };
552
+ const code = err.code;
553
+ return { ok: false, why: `io:${typeof code === 'string' ? code : 'error'}` };
554
+ }
512
555
  /** Werdykt listy hooków jednej sesji z jednego odczytu (opis modułu). */
513
556
  export async function sessionHookVerdict(input, io) {
514
557
  try {
515
- await collect(input, io);
558
+ await scanHooks(await readLayers(input, io, false), input, io);
516
559
  return { ok: true };
517
560
  }
518
561
  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'}` };
562
+ return verdictOf(err);
563
+ }
564
+ }
565
+ /**
566
+ * The same read as {@link sessionHookVerdict} over the files as they are now: a file, link or marketplace refresh at or
567
+ * after the session start does not stop it, so past a `changed` it still says whether a foreign hook stands anywhere.
568
+ */
569
+ export async function currentSessionHooks(input, io) {
570
+ let read = null;
571
+ try {
572
+ read = await readLayers(input, io, true);
573
+ await scanHooks(read, input, io);
574
+ return { verdict: { ok: true }, layers: read.layers, settingSources: read.settingSources };
575
+ }
576
+ catch (err) {
577
+ return { verdict: verdictOf(err), layers: read?.layers ?? null, settingSources: read?.settingSources ?? false };
523
578
  }
524
579
  }
525
- async function collect(input, io) {
580
+ /**
581
+ * `cwd` of the CLI registry file of the session process, or `null` when the file is missing, does not parse or names
582
+ * another session. The CLI rewrites the file while the process lives (`status`, `updatedAt`, CLI 2.1.321), so its change
583
+ * is not a change of hooks and it skips the start check.
584
+ */
585
+ export async function sessionRegistryCwd(io, home, pid, sessionId) {
586
+ const registryText = await io.readFile(path.join(home, DISK_LAYOUT.configDir, 'sessions', `${pid}.json`));
587
+ let registryFile = null;
588
+ try {
589
+ registryFile = registryText === null ? null : JSON.parse(registryText);
590
+ }
591
+ catch {
592
+ registryFile = null;
593
+ }
594
+ const registryRecord = registryFile !== null && typeof registryFile === 'object' && !Array.isArray(registryFile)
595
+ ? registryFile : null;
596
+ const registryCwd = registryRecord?.['cwd'];
597
+ return registryRecord?.['sessionId'] !== sessionId || typeof registryCwd !== 'string' ? null : registryCwd;
598
+ }
599
+ /**
600
+ * The session process, its arguments and every settings layer (module header), up to the hook scan; `current` turns
601
+ * the start check off ({@link currentSessionHooks}).
602
+ */
603
+ async function readLayers(input, io, current) {
526
604
  if (input.platform !== 'darwin')
527
605
  throw new HookListNoProof('platform');
528
606
  const entry = input.entry;
@@ -542,25 +620,13 @@ async function collect(input, io) {
542
620
  const args = parseClaudeArgs(proc.args);
543
621
  if ('why' in args)
544
622
  throw new HookListNoProof(args.why);
545
- const reader = new Reader(io, startLow);
623
+ const changedFrom = current ? Number.POSITIVE_INFINITY : startLow;
624
+ const reader = new Reader(io, changedFrom);
546
625
  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') {
626
+ // Plik rejestru sesji: `cwd` sesji i ta sama sesja pod tym pidem.
627
+ const registryCwd = await sessionRegistryCwd(io, input.home, entry.pid, input.sessionId);
628
+ if (registryCwd === null)
562
629
  throw new HookListNoProof('registry-file');
563
- }
564
630
  const cwds = [...new Set([registryCwd, ...input.cwds])];
565
631
  if (cwds.some((cwd) => !path.isAbsolute(cwd)))
566
632
  throw new HookListNoProof('cwd');
@@ -572,7 +638,7 @@ async function collect(input, io) {
572
638
  const addLayer = async (name, file, certain = false) => {
573
639
  const value = await reader.layer(file);
574
640
  if (value !== null)
575
- layers.push({ name, value, certain });
641
+ layers.push({ name, value, certain, file });
576
642
  };
577
643
  // Managed (macOS): preferencje MDM (systemowe i per użytkownik) = brak dowodu; pliki, katalog dopisków, kopia
578
644
  // z serwera.
@@ -600,13 +666,13 @@ async function collect(input, io) {
600
666
  // `--settings`.
601
667
  for (const one of args.settings) {
602
668
  if (one.kind === 'inline') {
603
- layers.push({ name: 'flag', value: one.json, certain: true });
669
+ layers.push({ name: 'flag', value: one.json, certain: true, file: null });
604
670
  }
605
671
  else {
606
672
  const value = await reader.layer(one.path);
607
673
  if (value === null)
608
674
  throw new HookListNoProof('settings-file');
609
- layers.push({ name: 'flag', value, certain: true });
675
+ layers.push({ name: 'flag', value, certain: true, file: one.path });
610
676
  }
611
677
  }
612
678
  // Użytkownik, projekt, local; `cwd` w linked worktree dokłada główny checkout (opis modułu).
@@ -628,6 +694,11 @@ async function collect(input, io) {
628
694
  for (const dir of [...localDirs].sort()) {
629
695
  await addLayer('local', path.join(dir, DISK_LAYOUT.configDir, DISK_LAYOUT.localSettings));
630
696
  }
697
+ return { reader, claude, layers, localDirs, changedFrom, settingSources: args.settingSources };
698
+ }
699
+ /** Hook entries of the layers, then plugins and definitions (module header): throws at the first doubt. */
700
+ async function scanHooks(read, input, io) {
701
+ const { reader, claude, layers, localDirs, changedFrom } = read;
631
702
  for (const layer of layers) {
632
703
  const foreign = foreignHookOf(layer.value, input.accepted);
633
704
  if (foreign !== null)
@@ -679,7 +750,7 @@ async function collect(input, io) {
679
750
  throw new HookListNoProof(`plugin-missing:${id}`);
680
751
  await reader.tree(installPath, [PLUGIN_IN_USE_DIR]);
681
752
  }
682
- await checkMarketplaceEntry(reader, { plugins, id, marketplaces, startLow });
753
+ await checkMarketplaceEntry(reader, { plugins, id, marketplaces, startLow: changedFrom });
683
754
  }
684
755
  await syncedTrees(io, reader, path.join(plugins, SYNCED_DIR));
685
756
  // Agenci, skille, komendy użytkownika i projektu (`cwd` i wyżej); skille z claude.ai w `skills/synced/`.
@@ -819,8 +890,10 @@ async function checkMarketplaceEntry(reader, ctx) {
819
890
  if (source['path'] !== location)
820
891
  throw new HookListNoProof(`marketplace-source:${market}`);
821
892
  const updated = typeof record['lastUpdated'] === 'string' ? Date.parse(record['lastUpdated']) : Number.NaN;
822
- if (!Number.isFinite(updated) || updated >= startLow)
893
+ // Over the current content (`startLow` infinite) the refresh time does not matter, also when it is unknown.
894
+ if (Number.isFinite(startLow) && (!Number.isFinite(updated) || updated >= startLow)) {
823
895
  throw new HookListNoProof(`marketplace-changed:${market}`);
896
+ }
824
897
  // `file`: sam plik marketplace'u, korzeń dwa katalogi wyżej (`<korzeń>/.claude-plugin/marketplace.json`).
825
898
  catalogFile = kind === 'directory' ? path.join(location, defaultFile) : location;
826
899
  localRoot = kind === 'directory' ? location : path.dirname(path.dirname(location));
@@ -896,11 +969,11 @@ export const nodeHookListIo = {
896
969
  }),
897
970
  };
898
971
  /** How long a negative verdict lives before the next read: transient ones shorter ({@link hookListVerdictKind}). */
899
- function retryOf(why) {
972
+ export function hookListRetryMs(why) {
900
973
  return hookListVerdictKind(why) === 'transient' ? HOOK_LIST_TRANSIENT_RETRY_MS : HOOK_LIST_RETRY_MS;
901
974
  }
902
975
  /** The session process a verdict was read for: registry pid and start; `''` without a registry entry. */
903
- function processOf(entry) {
976
+ export function sessionProcessKey(entry) {
904
977
  return entry === null ? '' : `${String(entry.pid)}@${String(entry.startedAt ?? '')}`;
905
978
  }
906
979
  const NO_ANSWER = { keys: new Set(), why: null };
@@ -925,8 +998,8 @@ export function createSessionHookList(options) {
925
998
  sessionId, home: options.home, accepted: options.accepted, entry, cwds: [...cwds],
926
999
  platform: options.platform ?? process.platform, now: at,
927
1000
  }, io);
928
- const proc = processOf(entry);
929
- if (processOf(await options.entry(sessionId)) !== proc)
1001
+ const proc = sessionProcessKey(entry);
1002
+ if (sessionProcessKey(await options.entry(sessionId)) !== proc)
930
1003
  return null;
931
1004
  const before = cache.get(sessionId)?.verdict;
932
1005
  const done = { at, proc, cwds, verdict };
@@ -945,14 +1018,14 @@ export function createSessionHookList(options) {
945
1018
  const cwds = new Set(asked.map((dump) => dump.cwd));
946
1019
  const newest = Math.max(...asked.map((dump) => dump.startedAt));
947
1020
  const entry = await options.entry(sessionId);
948
- const proc = processOf(entry);
1021
+ const proc = sessionProcessKey(entry);
949
1022
  const cached = cache.get(sessionId);
950
1023
  // An `ok` over a wider scope holds for a narrower one; a negative verdict may come from a `cwd` this call does not
951
1024
  // ask about, so it holds only for the very same scope.
952
1025
  const fresh = cached !== undefined && cached.proc === proc && [...cwds].every((cwd) => cached.cwds.has(cwd))
953
1026
  && (cached.verdict.ok
954
1027
  ? cached.at >= newest
955
- : cached.cwds.size === cwds.size && clock() - cached.at < retryOf(cached.verdict.why));
1028
+ : cached.cwds.size === cwds.size && clock() - cached.at < hookListRetryMs(cached.verdict.why));
956
1029
  let found = fresh ? cached : null;
957
1030
  if (found === null) {
958
1031
  // 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
+ }
@@ -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)
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Consent without a hook: the cause why a tool permission dialog in channel mode got no trace of Rarog's
3
+ * `PermissionRequest` hook, the two log lines that name it, and whether the card of the `off` path would carry the
4
+ * approve button. Pure functions over explicit arguments: the driver module `drivers/herdr/consent-no-hook.ts` gathers
5
+ * the facts and writes the lines. Nothing here gives or takes a button; the card stays as the decision built it.
6
+ */
7
+ import { cardShowsAll } from '../../drivers/tool-text.js';
8
+ import { hookListWhyCode } from './layer1/hook-list/hook-list.js';
9
+ /** Causes in the order they are checked: the first that holds names the dialog. */
10
+ export const NO_HOOK_CAUSES = [
11
+ 'hook-running', 'outside-work-area', 'hooks-disabled', 'not-in-session-hooks', 'unexplained',
12
+ ];
13
+ /**
14
+ * The first cause that holds: the hook process runs without a registration; the session `cwd` lies outside the work
15
+ * area; hooks are off by settings; the session's settings layers have no Rarog entry; otherwise `unexplained` (the CLI
16
+ * did not call the hook, or the hook left quietly for a reason the server cannot see). Only a certain value decides:
17
+ * the layer read is a superset, so only `rarogEntry: false` is sure, and only a `true` turns hooks off.
18
+ */
19
+ export function noHookCause(facts) {
20
+ if (facts.hookRunning === true)
21
+ return 'hook-running';
22
+ if (facts.outsideWorkArea === true)
23
+ return 'outside-work-area';
24
+ if (facts.disableAllHooks === true || facts.allowManagedHooksOnly === true)
25
+ return 'hooks-disabled';
26
+ if (facts.rarogEntry === false)
27
+ return 'not-in-session-hooks';
28
+ return 'unexplained';
29
+ }
30
+ /**
31
+ * Whether the card the `off` path shows would carry the approve button by today's rules: a consent card the driver
32
+ * understood (`input`), with the button (`canAllow`), whose whole text the card shows (`cardShowsAll`, the manager's
33
+ * rule for the button). Read from the card before the channel gate (`consentOnlyEvent`), which does not change it.
34
+ */
35
+ export function offPathApprove(event) {
36
+ return event.type === 'permission-request' && event.input !== null && event.canAllow !== false
37
+ && cardShowsAll(event.displayText, event.truncation);
38
+ }
39
+ /** Characters a log value may carry: an identifier, a name or a version, never a path, a command or free text. */
40
+ const TOKEN = /^[A-Za-z0-9_.:+-]{1,80}$/;
41
+ /** A value fit for a log line, or `?` for anything else (unknown, empty, a path, spaces, separators). */
42
+ export function logToken(value) {
43
+ return typeof value === 'string' && TOKEN.test(value) ? value : '?';
44
+ }
45
+ /** The hook list verdict as a log value: `ok` or the code of its reason, never the file it names; `?` without one. */
46
+ export function hooksToken(verdict) {
47
+ if (verdict === null)
48
+ return '?';
49
+ return verdict.ok ? 'ok' : logToken(hookListWhyCode(verdict.why));
50
+ }
51
+ /** `consent: no hook — …`, one per consent dialog episode without a hook trace. */
52
+ export function noHookLine(line) {
53
+ return `consent: no hook — session ${logToken(line.sessionId)}, cause ${line.cause}, tool ${logToken(line.tool)}, `
54
+ + `cli ${logToken(line.cli)}, mode ${logToken(line.mode)}, thread ${line.thread}, `
55
+ + `after ${String(Math.max(0, Math.round(line.afterMs)))} ms, hooks ${hooksToken(line.hooks)}, `
56
+ + `statusline ${line.statusline}, screen-button ${line.screenButton ? 'yes' : 'no'}`;
57
+ }
58
+ /** `consent: no approve button — …`, one per card identity whose approve button the channel gate took. */
59
+ export function noApproveButtonLine(line) {
60
+ return `consent: no approve button — session ${logToken(line.sessionId)}, reason ${logToken(line.reason)}, `
61
+ + `tool ${logToken(line.tool)}, channel ${logToken(line.channel)}, rule ${logToken(line.rule)}, `
62
+ + `cli ${logToken(line.cli)}`;
63
+ }
@@ -182,6 +182,16 @@ export function fileDialogTitle(block) {
182
182
  return 'edit';
183
183
  return block.title.tool === 'Write' ? 'write' : null;
184
184
  }
185
+ /**
186
+ * Whether the block's own title line (the line under its top rule, {@link DialogBlock.titleLine}) ends with the subagent
187
+ * suffix (` · from the Explore agent`). Only that line counts, never a line of the transcript above the block; an
188
+ * ambiguous block or one without a known title is not a subagent's.
189
+ */
190
+ export function blockFromSubagent(lines, block) {
191
+ if (block.ambiguous || block.titleLine < 0)
192
+ return false;
193
+ return SUBAGENT_TITLE_SUFFIX.test(unbox(lines[block.titleLine] ?? ''));
194
+ }
185
195
  /** Pierwsza niepusta linia pod kreską `rule`, przed `limit`, bez krawędzi ramki `╭──╮`; `-1` = brak. */
186
196
  export function lineBelow(lines, rule, limit) {
187
197
  for (let i = rule + 1; i < limit; i += 1) {
@@ -24,7 +24,7 @@ import { trimmedLines } from './text.js';
24
24
  import { DIALOG_TAIL_LINES, blockTopOf, dialogRegions, framedDialogText } from './region.js';
25
25
  import { OPTION_LINE_PATTERN, guideMap, isCompleteOptionSet, optionsCloseRegion, optionsIn, selectedOptionIn, selectedWithLabel, unbox, unframe, } from './options.js';
26
26
  import { contentEscalates } from '../policy/escalation.js';
27
- import { dialogBlock, fileDialogTitle, lineBelow, regionCallTrace, toolNaming } from './block.js';
27
+ import { blockFromSubagent, dialogBlock, fileDialogTitle, lineBelow, regionCallTrace, toolNaming, } from './block.js';
28
28
  import { PLAN_DIALOG_PATTERN, PLAN_EXIT_CONFIRM_PATTERN, SANDBOX_NETWORK_TOOL, dialogKind } from './kinds.js';
29
29
  import { FORM_IDENTITY } from './identity.js';
30
30
  import { blockKnownDialog } from './known.js';
@@ -38,6 +38,15 @@ export function screenOnlyDialog(text) {
38
38
  const dialog = parseOptions(text);
39
39
  return dialog !== null && dialog.toolName === SANDBOX_NETWORK_TOOL;
40
40
  }
41
+ /**
42
+ * Whether the dialog standing on screen is a subagent's: the title line of its block carries the subagent suffix
43
+ * ({@link blockFromSubagent}). No dialog with a complete option list = not a subagent's.
44
+ */
45
+ export function subagentDialogOnScreen(text) {
46
+ const lines = trimmedLines(text);
47
+ const found = optionRegion(lines);
48
+ return found !== null && blockFromSubagent(lines, dialogBlock(lines, found.firstOption));
49
+ }
41
50
  /**
42
51
  * Region opcji, z którego czyta {@link parseOptions}: pierwszy kandydat (od najwęższego), który widzi
43
52
  * spójną i KOMPLETNĄ listę opcji `1…N`; `null`, gdy żaden.
@@ -1,3 +1,25 @@
1
+ /**
2
+ * Wąski parser surowej linii jsonl — wyłącznie to, czego `parseImportLine` NIE zwraca:
3
+ * `id` i SUROWY `input` czekającego narzędzia, tryb uprawnień, model, effort i `cwd`.
4
+ *
5
+ * Dlaczego osobny parser, a nie rozszerzenie `transcript-import.ts`:
6
+ * tamten moduł celowo GUBI to, czego tu potrzebujemy. `assistantBlocksFrom` zamienia
7
+ * `tool_use` na blok prezentacyjny (`summary` + przycięty `detail`) i wyrzuca `id` oraz pełny
8
+ * `input` — bo jego zadaniem jest transkrypt na telefonie. Karta zgody potrzebuje czegoś
9
+ * dokładnie odwrotnego: PEŁNEGO inputu, żeby `classifyRisk` widział to samo, co widział przy
10
+ * SDK, i `id`, żeby dało się sparować z `tool_result`. Rozszerzenie tamtego parsera znaczyłoby
11
+ * zmianę pliku, który jest read-only dla wszystkich (i którego używa cała warstwa treści).
12
+ *
13
+ * Moduł jest CZYSTY: bez I/O, bez zegara, bez logów. Okno wejściowe wyznacza wołający
14
+ * (`HERDR_HISTORY_BYTES` ogona pliku).
15
+ *
16
+ * REGUŁA, KTÓRA JEST TU WAŻNIEJSZA NIŻ KOD: **tryb uprawnień z jsonl służy WYŁĄCZNIE do chipu
17
+ * w UI i nigdy do bramki wysyłki.** Wpisy `permission-mode` powstają PO turze, więc `shift+tab`
18
+ * naciśnięty przy biurku między turami jest w pliku niewidoczny — panel przełączony na
19
+ * `bypass permissions` wyglądałby w jsonl na `manual` przez całą następną turę. Do bramki
20
+ * (`commands/guard.ts`, reguła 4) tryb bierze się z odczytu stopki ekranu.
21
+ */
22
+ import path from 'node:path';
1
23
  import { EFFORT_LEVELS, MODEL_ID_PATTERN } from '@rarog/shared';
2
24
  import { asRecord } from '../drivers/tool-text.js';
3
25
  import { CLI_SHAPES } from './background/cli-shapes.js';
@@ -116,6 +138,8 @@ export function createPendingTracker() {
116
138
  const blocks = blocksOf(entry);
117
139
  if (type === 'assistant') {
118
140
  const at = asText(entry['timestamp']);
141
+ const cwd = asText(entry['cwd']);
142
+ const entryCwd = path.isAbsolute(cwd) ? { entryCwd: cwd } : {};
119
143
  for (const block of blocks) {
120
144
  if (block['type'] !== 'tool_use')
121
145
  continue;
@@ -125,7 +149,7 @@ export function createPendingTracker() {
125
149
  continue;
126
150
  if (settled.has(id) || open.some((tool) => tool.id === id))
127
151
  continue;
128
- open.push({ id, toolName, input: block['input'], at });
152
+ open.push({ id, toolName, input: block['input'], at, ...entryCwd });
129
153
  }
130
154
  return;
131
155
  }