@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
@@ -4,8 +4,8 @@
4
4
  * writes, cannot move a read outside that directory. The lookup resolves the path and checks names with `lstat` only:
5
5
  * it opens no file, reads nothing inside `.git` and starts no git.
6
6
  */
7
- import { lstat, realpath } from 'node:fs/promises';
8
7
  import { dirname, join } from 'node:path';
8
+ import { DIRECT_DISK } from './folder-gate/disk.js';
9
9
  /**
10
10
  * The work tree for a read in `cwd`: walking up from `realpath(cwd)`, the first directory where `lstat` sees a `.git`
11
11
  * entry of any kind (a directory, the file of a linked worktree or a submodule, a symlink). `null` when no directory up
@@ -13,7 +13,7 @@ import { dirname, join } from 'node:path';
13
13
  * other than `ENOENT`: a name that cannot be checked is not taken for absent.
14
14
  */
15
15
  export async function gitWorkTree(cwd) {
16
- for (let dir = await realpath(cwd);; dir = dirname(dir)) {
16
+ for (let dir = await DIRECT_DISK.call('realpathNative', { path: cwd });; dir = dirname(dir)) {
17
17
  if (await hasGitEntry(dir))
18
18
  return dir;
19
19
  if (dirname(dir) === dir)
@@ -22,7 +22,7 @@ export async function gitWorkTree(cwd) {
22
22
  }
23
23
  async function hasGitEntry(dir) {
24
24
  try {
25
- await lstat(join(dir, '.git'));
25
+ await DIRECT_DISK.call('lstat', { path: join(dir, '.git') });
26
26
  return true;
27
27
  }
28
28
  catch (error) {
@@ -92,7 +92,7 @@ export function redactAuditText(value, secrets = []) {
92
92
  */
93
93
  export const HERDR_REFUSE_REASONS = REFUSE_REASONS;
94
94
  /**
95
- * Powody spoza drivera — do dziennika nie trafiają, bo `#auditRefusal` woła wyłącznie driver.
95
+ * Powody spoza drivera — do dziennika nie trafiają, bo `auditRefusal` woła wyłącznie driver.
96
96
  *
97
97
  * `in-flight` powstaje w blokadzie równoległych prób (`PendingInteractions`) i mówi „poczekaj,
98
98
  * decyzja z drugiego urządzenia właśnie leci" — to nie jest awaria ścieżki cyfrowej, więc
@@ -694,8 +694,8 @@ export function createHerdrClient(requester, opts = {}) {
694
694
  * (driver, supervisor w trybie odczytu), nie dostają nawet REFERENCJI do metod tworzących.
695
695
  * Bramką pozostaje `socket.ts` — każdy zapis tej fasady (`workspace.create`, `tab.create`,
696
696
  * `agent.start`, `pane.report_metadata`, `pane.rename`, `tab.rename`, `tab.close`,
697
- * `pane.close`) jest w `MUTATING_METHODS`, więc `RAROG_HERDR_SEND=0` i nieznany protokół
698
- * blokują je razem z `agent.prompt`.
697
+ * `pane.close`) jest w `MUTATING_METHODS`, so `RAROG_HERDR_SEND=0` blocks them together
698
+ * with `agent.prompt`.
699
699
  */
700
700
  export function createHerdrLaunchClient(requester) {
701
701
  const call = mappedCaller(requester);
@@ -33,10 +33,9 @@
33
33
  * Odczyt jest synchroniczny, bo woła go bramka wysyłki (`assertSendable` w managerze), a koszt to kilkaset
34
34
  * `stat` na pełny skan (`catalog.ts` ogranicza go do jednego na minutę).
35
35
  */
36
- import { readdirSync, realpathSync, statSync } from 'node:fs';
37
36
  import { dirname, join, resolve, sep } from 'node:path';
38
37
  import { COMMAND_TEXT_MAX } from '@rarog/shared';
39
- import { readRegularFileSync } from '../../safe-read.js';
38
+ import { DIRECT_DISK } from '../../folder-gate/disk.js';
40
39
  import { DISK_LAYOUT } from './registry.js';
41
40
  import { isCommandSegment } from './shape.js';
42
41
  /** Ile bajtów pliku skilla albo komendy czytamy: frontmatter stoi na początku, treść nie jest potrzebna. */
@@ -48,15 +47,28 @@ export const COMMAND_CATALOG_SKIP_FILE_LOG = 'command catalog: not reading file'
48
47
  /** Stempel ścieżki: `mtime/rozmiar/inode` albo `missing`. Wspólny dla skanu i sprawdzenia sygnatury. */
49
48
  export function stampOf(path) {
50
49
  try {
51
- const info = statSync(path, { throwIfNoEntry: false });
50
+ const info = statOrMissing(path);
52
51
  if (info === undefined)
53
52
  return 'missing';
54
- return `${String(info.mtimeMs)}/${String(info.size)}/${String(info.ino)}`;
53
+ // Nanoseconds: the port's stats are bigint, whose `mtimeMs` drops the fraction of a millisecond.
54
+ return `${String(info.mtimeNs)}/${String(info.size)}/${String(info.ino)}`;
55
55
  }
56
56
  catch {
57
57
  return 'unreadable';
58
58
  }
59
59
  }
60
+ /** `stat` through the port; `undefined` where `statSync` with `throwIfNoEntry: false` gives it (ENOENT, ENOTDIR). */
61
+ function statOrMissing(path) {
62
+ try {
63
+ return DIRECT_DISK.sync('stat', { path });
64
+ }
65
+ catch (err) {
66
+ const code = err?.code;
67
+ if (code === 'ENOENT' || code === 'ENOTDIR')
68
+ return undefined;
69
+ throw err;
70
+ }
71
+ }
60
72
  /** Stan jednego skanu: stemple, notatki i zebrani kandydaci. */
61
73
  class Scan {
62
74
  stamps = new Map();
@@ -77,7 +89,7 @@ class Scan {
77
89
  return [];
78
90
  let names;
79
91
  try {
80
- names = readdirSync(dir).sort();
92
+ names = [...DIRECT_DISK.sync('readdirNames', { path: dir })].sort();
81
93
  }
82
94
  catch (err) {
83
95
  this.note(`command catalog: not reading directory ${dir} (${codeOf(err)})`);
@@ -86,7 +98,7 @@ class Scan {
86
98
  return names.filter((name) => {
87
99
  const path = join(dir, name);
88
100
  try {
89
- const info = statSync(path, { throwIfNoEntry: false });
101
+ const info = statOrMissing(path);
90
102
  return info !== undefined && (kind === 'dir' ? info.isDirectory() : info.isFile());
91
103
  }
92
104
  catch {
@@ -105,7 +117,7 @@ class Scan {
105
117
  if (this.stamp(path) === 'missing')
106
118
  return null;
107
119
  try {
108
- const read = readRegularFileSync(path, { maxBytes: max, followSymlink: true });
120
+ const read = DIRECT_DISK.sync('readHead', { path, maxBytes: max, followSymlink: true });
109
121
  if (read === null) {
110
122
  this.note(`${COMMAND_CATALOG_SKIP_FILE_LOG} ${path} (not a regular file)`);
111
123
  return null;
@@ -419,8 +431,8 @@ function scanSynced(scan, home) {
419
431
  /** Czy `child` leży w `parent` po rozwiązaniu dowiązań (ścieżka instalacji pluginu z pliku CLI). */
420
432
  function insideReal(child, parent) {
421
433
  try {
422
- const real = realpathSync(child);
423
- const base = realpathSync(parent);
434
+ const real = DIRECT_DISK.sync('realpath', { path: child });
435
+ const base = DIRECT_DISK.sync('realpath', { path: parent });
424
436
  return real === base || real.startsWith(base.endsWith(sep) ? base : `${base}${sep}`);
425
437
  }
426
438
  catch {
@@ -1,4 +1,4 @@
1
- import { consentDigitBlocked } from './router.js';
1
+ import { consentDigitBlocked, consentDigitException } from './router.js';
2
2
  import { screenCardUnavailable } from './screen-unavailable.js';
3
3
  /** Tryb efektywny kanału zgód albo `null` (źródło rzuciło: tryb nieznany, liczony jak `main`). */
4
4
  export function consentModeNow(deps) {
@@ -18,18 +18,35 @@ export function consentModeNow(deps) {
18
18
  */
19
19
  export function consentDigitRefused(deps, cliDialog, card, consent) {
20
20
  try {
21
- return consentDigitBlocked({
22
- mode: consentModeNow(deps), cliDialog, toolName: card.toolName, consent,
23
- measured: card.measuredConsent,
24
- });
21
+ return consentDigitBlocked(gateInput(deps, cliDialog, card, consent));
25
22
  }
26
23
  catch {
27
24
  return true;
28
25
  }
29
26
  }
27
+ /**
28
+ * The exception that opens the "Yes" digit of the card in channel mode (`consentDigitException`), `null` without one,
29
+ * in `off` and `shadow` (no gate there) and on an exception.
30
+ */
31
+ export function consentDigitOpenedBy(deps, cliDialog, card) {
32
+ try {
33
+ return consentDigitException(gateInput(deps, cliDialog, card, true));
34
+ }
35
+ catch {
36
+ return null;
37
+ }
38
+ }
39
+ function gateInput(deps, cliDialog, card, consent) {
40
+ return {
41
+ mode: consentModeNow(deps), cliDialog, toolName: card.toolName, consent,
42
+ ...(card.measuredConsent === undefined ? {} : { measured: card.measuredConsent }),
43
+ ...(card.screenFallback === undefined ? {} : { fallback: card.screenFallback }),
44
+ };
45
+ }
30
46
  /**
31
47
  * Karta zgody w trybie kanału (`main`): bez przycisku zgody i bez „nie pytaj więcej”, bo cyfra i tak by nie wyszła
32
- * ({@link consentDigitRefused}). Każda inna karta i każdy inny tryb bez zmian. A consent card that has no approve
48
+ * ({@link consentDigitRefused}); a card the emergency mark opens keeps the approve button without "always". Każda
49
+ * inna karta i każdy inny tryb bez zmian. A consent card that has no approve
33
50
  * button for that or for its text also carries the reason (`unavailable`, `screen-unavailable.ts`).
34
51
  */
35
52
  export function consentOnlyEvent(event, active, deps, cliDialog, session) {
@@ -42,10 +59,13 @@ export function consentOnlyEvent(event, active, deps, cliDialog, session) {
42
59
  sessionCwd: session.cwd,
43
60
  });
44
61
  const reason = unavailable === undefined ? {} : { unavailable };
45
- if (!blocked)
46
- return { ...event, ...reason };
47
62
  const { alwaysLabel: _always, ...rest } = event;
48
63
  void _always;
64
+ // The emergency button approves this call once: the "always" option stays at the desk.
65
+ if (!blocked) {
66
+ const emergency = consentDigitOpenedBy(deps, cliDialog, active) === 'screen-fallback';
67
+ return emergency ? { ...rest, ...reason } : { ...event, ...reason };
68
+ }
49
69
  return { ...rest, canAllow: false, ...reason };
50
70
  }
51
71
  /** The desk release of the card's call key (`ActiveReq.origin.callKey`); no key, no source or an exception = `null`. */
@@ -36,10 +36,13 @@ export function expectedFor(input, source) {
36
36
  return {
37
37
  toolName: source.toolName,
38
38
  ...(command === null ? {} : { command }),
39
- // Katalog wywołania ze zrzutu hooka, a dla wpisu jsonl (bez `cwd`) katalog sesji z drivera.
39
+ // The call directory: the hook dump's, else the `cwd` field of the transcript entry (it follows a Bash `cd`, while
40
+ // the pane stays on the start directory), else the session directory from the driver.
40
41
  ...(fileChange === null
41
42
  ? {}
42
- : { fileCall: { change: fileChange, input: source.input, cwd: source.cwd ?? input.cwd ?? null } }),
43
+ : {
44
+ fileCall: { change: fileChange, input: source.input, cwd: source.cwd ?? source.entryCwd ?? input.cwd ?? null },
45
+ }),
43
46
  ...(command !== null && bashDoubleProof(input.pending, input.hookRaw) ? { doubleProof: true } : {}),
44
47
  ...(payload === null
45
48
  ? {}
@@ -47,15 +47,22 @@ export const HOOK_PAYLOAD_FIELDS = {
47
47
  suggestions: { field: 'permission_suggestions', cli: '2.1.322' },
48
48
  };
49
49
  /**
50
- * Wydanie CLI, na którym zmierzono precyzję przycisku zgody z kanału bez wierzchu ekranu: późne
51
- * `allow` hooka po decyzji przy biurku (po „Yes”, po „No” i SIGTERM; `Bash`, `Write`) nic nie wykonuje. To nie literał
52
- * pliku hooka, tylko fakt o jego zachowaniu w CLI: sesja, której jedyny proces ma w odczycie rejestru tej obserwacji
53
- * wyższe wydanie, liczy dowód regułą `screen`, chyba że plik kanarka ma dla tego wydania `pass` (bramka wersji
54
- * `layer1/version-gate.ts`). Ta stała to baza z paczki: obowiązuje też bez pliku kanarka. Wersję podbija
55
- * dopiero pomiar późnego `allow` wątku głównego na nowym CLI z tym samym wynikiem (`docs/dialogs.md`,
56
- * „PermissionRequest hook behavior”).
57
- */
58
- export const CONSENT_CHANNEL_MEASURED_CLI = { cli: '2.1.325' };
50
+ * The package base of the `channel` proof rule: the CLI release `cli` on which the precision of the channel approve
51
+ * button without the screen top was measured, and the releases under it the package does not cover (`excluded`).
52
+ * The measured contract: a late `allow` of the hook after a desk decision (after "Yes", after "No" and SIGTERM;
53
+ * `Bash`, `Write`) runs nothing, and a hidden subagent request runs only on its own `allow`, once (measured on the
54
+ * release `cli` by the consent canary, `pass` for both request kinds; `docs/dialogs.md`, "`PermissionRequest` hook
55
+ * behavior"). This is not a literal of the hook file but a fact about its behavior in the CLI, so the base holds
56
+ * without the canary file too. The version gate
57
+ * (`layer1/version-gate.ts`) gives `channel` to a release not above `cli` and not in `excluded`; any other release
58
+ * counts `screen` unless the canary file has `pass` for it and the request kind.
59
+ *
60
+ * `cli` goes up only after a canary run with `pass` for both request kinds (main thread and subagents) on the new
61
+ * release. In the same change every release between the old and the new `cli` without `pass` for both kinds (a
62
+ * `fail`, an `unmeasured` kind, no run) goes onto `excluded`, a closed list of exact releases (`docs/dialogs.md`,
63
+ * "Proof rule").
64
+ */
65
+ export const CONSENT_CHANNEL_MEASURED_CLI = { cli: '2.1.331', excluded: ['2.1.327'] };
59
66
  /**
60
67
  * Programmatic Claude Code sessions: the environment variable the hook inherits from the CLI process, and the
61
68
  * values at which the hook exits right after reading stdin, without a trace (no dump, `hook-seen.json`,
@@ -19,6 +19,10 @@
19
19
  * - `consent-gate.ts` — the digit gate of consent channel mode: effective mode, blocked digit, consent card without
20
20
  * its allow button.
21
21
  * - `screen-unavailable.ts` — the reason of a consent card without `channel` and without the approve button.
22
+ * - `no-hook.ts` — consent without a hook: its cause, the `no hook` and `no approve button` log lines, and
23
+ * whether the card of the `off` path has the approve button.
24
+ * - `screen-fallback.ts` — the emergency approve button of a consent dialog without a hook: one rule over the facts,
25
+ * the card mark, the key and refused key log lines.
22
26
  * - `policy/options.ts` — wybór opcji po treści etykiety: „ten jeden raz" i „zawsze" (`docs/dialogs.md`, „Rules: what must not be relaxed”).
23
27
  * - `policy/escalation.ts` — słownik eskalacji (`docs/dialogs.md`, „Rules: what must not be relaxed”): treść, etykieta opcji, przełącznik trybu.
24
28
  * - `policy/terminal.ts` — dialogi tylko z terminala: lista, dopasowanie, sufit treści.
@@ -88,11 +92,15 @@
88
92
  * - `layer1/resume.ts` — resumption of the records a server restart interrupted (restart grace G): the wait for
89
93
  * the hook's second registration and the allow-button hold of a resumed `pending` record, in
90
94
  * memory only; the transitions and the writes stay in `cycle.ts`.
95
+ * - `layer1/screen-key.ts` — the digits of the emergency approve button the cycle remembers for a minute, the match
96
+ * of a hook that registers after the key, and its `screen fallback late hook` line.
91
97
  * - `layer1/turns.ts` — settlement of consent turns: which turns the transcript review still reads and what one
92
98
  * turn's facts do to its records (record writes stay in `cycle.ts`).
93
99
  * - `layer1/observe.ts` — obserwacja jednej sesji (zrzuty, pula, `ps`, sygnały z wierzchem ekranu, karty bez
94
100
  * zrzutu) dla serwera i procesu pomiaru kanału.
95
101
  * - `layer1/hook-list/hook-list.ts` — the session's `PermissionRequest` hooks, read-only, as evidence.
102
+ * - `layer1/hook-list/session-facts.ts` — the session facts without a hook dump: process, `cwd`, call `cwd`, the hook
103
+ * list verdict and the settings layers past `changed`, cached per process, `cwd` and episode.
96
104
  * - `layer1/mode.ts` — tryb efektywny kanału zgód: `main` wyłącznie przy komplecie warunków (hook `ok`, oba
97
105
  * gniazda, próg buildu apki), inaczej `shadow` z powodem; `off` do rozstrzygnięcia po starcie
98
106
  * gniazd i po wyłączniku (do restartu); źródło trybu ze słuchaczem zmian.
@@ -174,7 +182,9 @@ export { FORM_SUBMIT_GONE_MESSAGE, MULTI_SELECT_MESSAGE, NOTE_NOT_ALLOWED_MESSAG
174
182
  export { ANSWERED_HOOK_SHIELD_MS, CLI_HOLD_MISSES, CLI_WAITING_PROBES, DECIDED_SHIELD_MS, FORM_FALLBACK_MISSES, FORM_FALLBACK_RETRY_DELAYS_MS, FORM_SUBMIT_CONFIRM_DELAY_MS, HOOK_ANSWER_POLL_MS, HOOK_ANSWER_WAIT_MS, SCREEN_ANSWER_REARM_DELAYS_MS, SHADOW_DEADLINE_MS, } from './timing.js';
175
183
  export { askFormOnScreen, cliDialogOnScreen } from './presence.js';
176
184
  export { DIALOG_ROUTES, DIALOG_ROUTE_REASONS, routeAllowsDigit, routeDialog, routeHookOf, routeScreenOf, } from './router.js';
177
- export { consentDigitRefused, consentModeNow, consentOnlyEvent } from './consent-gate.js';
185
+ export { consentDigitOpenedBy, consentDigitRefused, consentModeNow, consentOnlyEvent } from './consent-gate.js';
186
+ export { noApproveButtonLine, noHookCause, noHookLine, offPathApprove } from './no-hook.js';
187
+ export { screenFallbackGuard, screenFallbackHolds, screenFallbackKeyLine, screenFallbackRefusedLine, } from './screen-fallback.js';
178
188
  export { applyMultiSelectOverride, competingHook, hookMatchesPending, hookPendingFrom, olderBashHook, } from './cross-check.js';
179
189
  export { affirmativeOption, alwaysOption } from './policy/options.js';
180
190
  export { optionPolicy } from './policy/option-policy.js';
@@ -188,7 +198,7 @@ export { admittedHook, besideAtDecision, evaluationReqId, hookPendingFor, otherD
188
198
  export { dialogShapeOf } from './decide/reasons.js';
189
199
  export { FORM_SUBMIT_KEY, confirmFormSubmit } from './send/form-submit.js';
190
200
  export { ASK_USER_QUESTION_TOOL, resolveOptions } from './screen/resolve.js';
191
- export { parseOptions } from './screen/parse.js';
201
+ export { dialogThreadOnScreen, parseOptions, subagentDialogOnScreen } from './screen/parse.js';
192
202
  export { blockVisible } from './screen/block-visible.js';
193
203
  export { SANDBOX_NETWORK_TOOL } from './screen/kinds.js';
194
204
  export { matchKnownDialog } from './screen/known.js';
@@ -145,6 +145,7 @@ import { claimedDialogSignal, consentKeyRule, consentTopMissText, consentTopVerd
145
145
  import { consentReceiptConfirmable } from './receipt.js';
146
146
  import { consentFilesDir, consentSignedOf, readConsentRecords, writeConsentRecord } from './records.js';
147
147
  import { consentClaimKept, createConsentResume } from './resume.js';
148
+ import { createConsentScreenKeys, lateHook, screenKeyCallOf } from './screen-key.js';
148
149
  import { signConsentFile } from './sign.js';
149
150
  import { topFieldsOf } from './top.js';
150
151
  import { createConsentTurns } from './turns.js';
@@ -270,8 +271,8 @@ export function createConsentCycle(options) {
270
271
  const channelProofs = new Map();
271
272
  /**
272
273
  * Chwila odczytu najnowszego statusu rejestru CLI sesji bez `waiting: permission` przyjętego przez driver
273
- * ({@link noteRegistryNotWaiting}); dowód z kanału z odczytu nie późniejszego nie obowiązuje. Wpis per sesja zostaje
274
- * do końca procesu (liczba, nie treść).
274
+ * ({@link noteRegistryNotWaiting}); dowód z kanału z odczytu nie późniejszego nie obowiązuje. The per-session
275
+ * entry (a number, no content) stays until the process ends or the session is forgotten ({@link forgetSession}).
275
276
  */
276
277
  const registryNotWaitingAt = new Map();
277
278
  /** Sprawdzenie wierzchu per odczyt ekranu obserwacji przy wersji puli sesji ({@link topWinner}). */
@@ -294,6 +295,7 @@ export function createConsentCycle(options) {
294
295
  publish,
295
296
  });
296
297
  const { noteHeld, releasePending, deskFallback, mcpToDesk } = desk;
298
+ const screenKeys = createConsentScreenKeys(now);
297
299
  /**
298
300
  * Sloty, których zwolnienia hooka ({@link releaseHook}) nie dało się zapisać: następna obserwacja z żywym zrzutem
299
301
  * klucza próbuje jeszcze raz. W pamięci procesu: po restarcie hook starego procesu widzi nowy `bootId` i wychodzi sam.
@@ -965,7 +967,8 @@ export function createConsentCycle(options) {
965
967
  * (`pending` → `settled-at-desk`) i zwolnienie z urządzenia, którego plik nie powstał (`revoked: write-failed`).
966
968
  * Rekord subagenta z żywą rejestracją przy `gone` i po końcu biegu bez wyniku zostaje w `pending`: jego
967
969
  * `release` pisze powrót do biurka (`deskFallback`, `desk.ts`), a jego porażka idzie do pola `releaseFailed`, nie do
968
- * {@link releaseDue}.
970
+ * {@link releaseDue}. A hook tied to the emergency key (`lateHook`), a subagent's too, is settled and released here
971
+ * at its first observation, and a failed write of its release goes to {@link releaseDue}.
969
972
  * Hooka nie zwalniają: śmierć hooka, restart (stary hook widzi nowy `bootId` w `alive.json`), wyłącznik (`alive.json`
970
973
  * z trybem niższym niż `main`), koniec sesji silnika (`revokeSession`: CLI kończy swoje hooki, `hook-dead` zapomina
971
974
  * rejestrację), termin przejęcia (hook nie przejął podpisanego pliku przez 60 s) i plik odłożony jako nieważny
@@ -1135,7 +1138,14 @@ export function createConsentCycle(options) {
1135
1138
  if (record === undefined) {
1136
1139
  if (signal === 'dead')
1137
1140
  forgetDead(sessionId, key, deadWhy, hookProc);
1138
- if (dump === undefined || signal === 'dead' || signal === 'gone')
1141
+ if (dump === undefined || signal === 'dead')
1142
+ return null;
1143
+ // MCP with user interaction goes back at once: its pending card is written without publishing (`mcpToDesk`).
1144
+ const mcp = dump.mcpEmptySuggestions === true;
1145
+ const created = newRecord(dump);
1146
+ // A hook the emergency key already answered is settled also when this observation sees its dialog gone.
1147
+ const late = !mcp && screenKeys.answered(screenKeyCallOf(created, registry.entry(sessionId, key)));
1148
+ if (signal === 'gone' && !late)
1139
1149
  return null;
1140
1150
  dumps.set(slot, dump);
1141
1151
  verdicts.set(slot, evaluate(dump, effective));
@@ -1143,9 +1153,8 @@ export function createConsentCycle(options) {
1143
1153
  noteDesk();
1144
1154
  mark(true);
1145
1155
  createdAt.set(slot, now());
1146
- // MCP with user interaction goes back at once: its pending card is written without publishing (`mcpToDesk`).
1147
- const mcp = dump.mcpEmptySuggestions === true;
1148
- record = mcp ? mcpToDesk(commit(newRecord(dump), false, true)) : deskFallback(commit(newRecord(dump)));
1156
+ record = mcp || late ? commit(created, false, true) : deskFallback(commit(created));
1157
+ record = mcp ? mcpToDesk(record) : late ? lateHook(record, { log, revoke, releaseHook }) : record;
1149
1158
  return viewOf(record);
1150
1159
  }
1151
1160
  if (dump !== undefined)
@@ -1676,6 +1685,25 @@ export function createConsentCycle(options) {
1676
1685
  return false;
1677
1686
  return factLost(sessionId, dump.key, dump.startedAt);
1678
1687
  }
1688
+ async function forgetSession(sessionId) {
1689
+ const prefix = slotOf(sessionId, '');
1690
+ const passed = [...passedSlots].filter((slot) => slot.startsWith(prefix));
1691
+ await Promise.all([...new Set([...slotsOf(sessionId), ...passed])].map((slot) => enqueue(slot, () => {
1692
+ const record = records.get(slot);
1693
+ if (record !== undefined && turns.evidenceTargets()
1694
+ .some((turn) => turn.sessionId === sessionId && turn.keys.includes(record.key)))
1695
+ return;
1696
+ records.delete(slot);
1697
+ passedSlots.delete(slot);
1698
+ store.delete(sessionId, slot.slice(prefix.length));
1699
+ })));
1700
+ // A kept record still needs the session's proof-loss clocks, or it would allow again without a fresh observation.
1701
+ if ([...records.keys()].some((slot) => slot.startsWith(prefix)))
1702
+ return;
1703
+ reattachAt.delete(sessionId);
1704
+ reattachOpen.delete(sessionId);
1705
+ registryNotWaitingAt.delete(sessionId);
1706
+ }
1679
1707
  const turns = createConsentTurns({
1680
1708
  records, bootId, registry, slotOf, enqueue, subagentsOpen, commit, moveTo, claimed, claimedMatches, releaseHook,
1681
1709
  revoke, afterRevokeFile,
@@ -1686,6 +1714,7 @@ export function createConsentCycle(options) {
1686
1714
  revokeSession,
1687
1715
  decide,
1688
1716
  release,
1717
+ screenKey: (sessionId, key) => { screenKeys.note(sessionId, key); },
1689
1718
  confirmReceipt,
1690
1719
  retire,
1691
1720
  off,
@@ -1703,6 +1732,7 @@ export function createConsentCycle(options) {
1703
1732
  noteHookChecks,
1704
1733
  noteHookDead,
1705
1734
  endPool,
1735
+ forgetSession,
1706
1736
  pool,
1707
1737
  topWinner,
1708
1738
  proofLost,
@@ -1742,5 +1772,11 @@ export function createConsentCycle(options) {
1742
1772
  proofNotes: keysOf(proofNotes.keys()),
1743
1773
  };
1744
1774
  },
1775
+ diagnosticSession: (sessionId) => {
1776
+ const prefix = slotOf(sessionId, '');
1777
+ const passed = [...passedSlots].filter((slot) => slot.startsWith(prefix)).map((s) => s.slice(prefix.length));
1778
+ const clocks = { reattachAt: reattachAt.has(sessionId), registryNotWaitingAt: registryNotWaitingAt.has(sessionId) };
1779
+ return { passed, ...clocks };
1780
+ },
1745
1781
  };
1746
1782
  }