@rarog/server 1.1.0-beta.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 (93) hide show
  1. package/README.md +14 -2
  2. package/node_modules/@rarog/shared/package.json +1 -1
  3. package/node_modules/@rarog/shared/src/decode.js +16 -1
  4. package/node_modules/@rarog/shared/src/protocol/folders.js +27 -0
  5. package/node_modules/@rarog/shared/src/protocol/herdr.js +23 -0
  6. package/node_modules/@rarog/shared/src/protocol/notes.js +7 -1
  7. package/node_modules/@rarog/shared/src/protocol.js +5 -31
  8. package/node_modules/@rarog/shared/src/sentences/herdr.js +0 -4
  9. package/node_modules/@rarog/shared/src/sentences/index.js +7 -1
  10. package/node_modules/@rarog/shared/src/sentences/rest.js +8 -0
  11. package/package.json +2 -2
  12. package/server/src/auth/admin.js +3 -1
  13. package/server/src/bootstrap/consent.js +11 -0
  14. package/server/src/bootstrap/folder-gate.js +55 -0
  15. package/server/src/cli/service-log.js +27 -0
  16. package/server/src/cli/service.js +5 -2
  17. package/server/src/cli/templates/launchd.plist +1 -1
  18. package/server/src/cli/templates/rarog.service +1 -1
  19. package/server/src/cli/update-provenance.js +37 -19
  20. package/server/src/config/protected-dirs.js +2 -0
  21. package/server/src/config/roots.js +13 -8
  22. package/server/src/config/work-area.js +36 -12
  23. package/server/src/config-env.js +9 -0
  24. package/server/src/config.js +17 -1
  25. package/server/src/demo/control.js +9 -1
  26. package/server/src/drivers/herdr/consent-no-hook.js +103 -8
  27. package/server/src/drivers/herdr/screen-fallback.js +246 -0
  28. package/server/src/drivers/herdr-driver.js +78 -9
  29. package/server/src/files/file-index.js +5 -3
  30. package/server/src/files/listing.js +8 -2
  31. package/server/src/files/path-rule.js +95 -41
  32. package/server/src/files/refusals.js +14 -0
  33. package/server/src/files/session-gate.js +11 -6
  34. package/server/src/folder-gate/client.js +314 -0
  35. package/server/src/folder-gate/disk.js +455 -0
  36. package/server/src/folder-gate/folders.js +23 -0
  37. package/server/src/folder-gate/gate.js +220 -0
  38. package/server/src/folder-gate/helper.js +118 -0
  39. package/server/src/folder-gate/install.js +27 -0
  40. package/server/src/folder-gate/relay-worker.js +147 -0
  41. package/server/src/folder-gate/types.js +115 -0
  42. package/server/src/folder-gate/wire.js +170 -0
  43. package/server/src/fs-browse.js +55 -23
  44. package/server/src/fs-mkdir.js +3 -1
  45. package/server/src/git-status.js +13 -5
  46. package/server/src/git-watch.js +130 -19
  47. package/server/src/git-work-tree.js +3 -3
  48. package/server/src/herdr/client.js +2 -2
  49. package/server/src/herdr/commands/discover.js +21 -9
  50. package/server/src/herdr/dialogs/consent-gate.js +28 -8
  51. package/server/src/herdr/dialogs/decide/sources.js +5 -2
  52. package/server/src/herdr/dialogs/hook/contract.js +1 -1
  53. package/server/src/herdr/dialogs/index.js +7 -2
  54. package/server/src/herdr/dialogs/layer1/cycle.js +43 -7
  55. package/server/src/herdr/dialogs/layer1/hook-list/hook-list.js +34 -27
  56. package/server/src/herdr/dialogs/layer1/screen-key.js +52 -0
  57. package/server/src/herdr/dialogs/router.js +21 -6
  58. package/server/src/herdr/dialogs/screen/parse.js +23 -2
  59. package/server/src/herdr/dialogs/screen/resolve.js +9 -7
  60. package/server/src/herdr/dialogs/screen-fallback.js +55 -0
  61. package/server/src/herdr/dialogs/shadow/alive.js +9 -8
  62. package/server/src/herdr/jsonl-follow.js +55 -14
  63. package/server/src/herdr/provenance.js +3 -3
  64. package/server/src/herdr/socket.js +25 -28
  65. package/server/src/herdr/supervisor.js +13 -10
  66. package/server/src/herdr/transcript-path.js +36 -0
  67. package/server/src/herdr/trust.js +11 -8
  68. package/server/src/herdr/uploads-registry.js +3 -2
  69. package/server/src/herdr/uploads.js +170 -47
  70. package/server/src/index.js +22 -3
  71. package/server/src/iroh/listener.js +3 -0
  72. package/server/src/iroh/log-budget.js +1 -0
  73. package/server/src/iroh/socket.js +2 -1
  74. package/server/src/notes/store.js +3 -2
  75. package/server/src/router.js +13 -1
  76. package/server/src/routes/projects.js +5 -1
  77. package/server/src/routes/sessions.js +10 -4
  78. package/server/src/routes/system.js +4 -0
  79. package/server/src/safe-read.js +12 -12
  80. package/server/src/sessions/companion-scope.js +10 -5
  81. package/server/src/sessions/done-retention.js +57 -0
  82. package/server/src/sessions/launch-gate.js +2 -2
  83. package/server/src/sessions/manager.js +35 -59
  84. package/server/src/sessions/project-scan.js +9 -3
  85. package/server/src/sessions/ring-buffer.js +8 -21
  86. package/server/src/sessions/session-git.js +31 -2
  87. package/server/src/sessions/session.js +1 -1
  88. package/server/src/sessions/state-sentences.js +1 -1
  89. package/server/src/sse.js +121 -22
  90. package/server/src/term/herdr-backend.js +2 -2
  91. package/server/src/term/index.js +2 -15
  92. package/server/src/term/registry.js +4 -3
  93. package/server/src/term/ws.js +9 -1
@@ -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
  ? {}
@@ -62,7 +62,7 @@ export const HOOK_PAYLOAD_FIELDS = {
62
62
  * `fail`, an `unmeasured` kind, no run) goes onto `excluded`, a closed list of exact releases (`docs/dialogs.md`,
63
63
  * "Proof rule").
64
64
  */
65
- export const CONSENT_CHANNEL_MEASURED_CLI = { cli: '2.1.330', excluded: ['2.1.327'] };
65
+ export const CONSENT_CHANNEL_MEASURED_CLI = { cli: '2.1.331', excluded: ['2.1.327'] };
66
66
  /**
67
67
  * Programmatic Claude Code sessions: the environment variable the hook inherits from the CLI process, and the
68
68
  * values at which the hook exits right after reading stdin, without a trace (no dump, `hook-seen.json`,
@@ -21,6 +21,8 @@
21
21
  * - `screen-unavailable.ts` — the reason of a consent card without `channel` and without the approve button.
22
22
  * - `no-hook.ts` — consent without a hook: its cause, the `no hook` and `no approve button` log lines, and
23
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.
24
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”).
25
27
  * - `policy/escalation.ts` — słownik eskalacji (`docs/dialogs.md`, „Rules: what must not be relaxed”): treść, etykieta opcji, przełącznik trybu.
26
28
  * - `policy/terminal.ts` — dialogi tylko z terminala: lista, dopasowanie, sufit treści.
@@ -90,6 +92,8 @@
90
92
  * - `layer1/resume.ts` — resumption of the records a server restart interrupted (restart grace G): the wait for
91
93
  * the hook's second registration and the allow-button hold of a resumed `pending` record, in
92
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.
93
97
  * - `layer1/turns.ts` — settlement of consent turns: which turns the transcript review still reads and what one
94
98
  * turn's facts do to its records (record writes stay in `cycle.ts`).
95
99
  * - `layer1/observe.ts` — obserwacja jednej sesji (zrzuty, pula, `ps`, sygnały z wierzchem ekranu, karty bez
@@ -178,8 +182,9 @@ export { FORM_SUBMIT_GONE_MESSAGE, MULTI_SELECT_MESSAGE, NOTE_NOT_ALLOWED_MESSAG
178
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';
179
183
  export { askFormOnScreen, cliDialogOnScreen } from './presence.js';
180
184
  export { DIALOG_ROUTES, DIALOG_ROUTE_REASONS, routeAllowsDigit, routeDialog, routeHookOf, routeScreenOf, } from './router.js';
181
- export { consentDigitRefused, consentModeNow, consentOnlyEvent } from './consent-gate.js';
185
+ export { consentDigitOpenedBy, consentDigitRefused, consentModeNow, consentOnlyEvent } from './consent-gate.js';
182
186
  export { noApproveButtonLine, noHookCause, noHookLine, offPathApprove } from './no-hook.js';
187
+ export { screenFallbackGuard, screenFallbackHolds, screenFallbackKeyLine, screenFallbackRefusedLine, } from './screen-fallback.js';
183
188
  export { applyMultiSelectOverride, competingHook, hookMatchesPending, hookPendingFrom, olderBashHook, } from './cross-check.js';
184
189
  export { affirmativeOption, alwaysOption } from './policy/options.js';
185
190
  export { optionPolicy } from './policy/option-policy.js';
@@ -193,7 +198,7 @@ export { admittedHook, besideAtDecision, evaluationReqId, hookPendingFor, otherD
193
198
  export { dialogShapeOf } from './decide/reasons.js';
194
199
  export { FORM_SUBMIT_KEY, confirmFormSubmit } from './send/form-submit.js';
195
200
  export { ASK_USER_QUESTION_TOOL, resolveOptions } from './screen/resolve.js';
196
- export { parseOptions, subagentDialogOnScreen } from './screen/parse.js';
201
+ export { dialogThreadOnScreen, parseOptions, subagentDialogOnScreen } from './screen/parse.js';
197
202
  export { blockVisible } from './screen/block-visible.js';
198
203
  export { SANDBOX_NETWORK_TOOL } from './screen/kinds.js';
199
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
  }
@@ -79,12 +79,11 @@
79
79
  * `disableAllHooks`, `allowManagedHooksOnly` and Rarog's entry from those layers; the verdict above ignores them.
80
80
  */
81
81
  import { execFile } from 'node:child_process';
82
- import fs from 'node:fs/promises';
83
82
  import path from 'node:path';
84
83
  import { DISK_LAYOUT } from '../../../commands/registry.js';
85
84
  import { parseElapsed } from '../../shadow/liveness.js';
86
85
  import { HOOK_PERMISSION_EVENT } from '../../../hook-commands.js';
87
- import { readRegularFile } from '../../../../safe-read.js';
86
+ import { DIRECT_DISK } from '../../../../folder-gate/disk.js';
88
87
  /** Zapas na rozdzielczość `etime` (pełne sekundy) i czas samego `ps`. */
89
88
  export const HOOK_LIST_START_SLACK_MS = 2_000;
90
89
  /** Rejestr CLI pisze `startedAt` 1–7 s po starcie procesu (`cli-version.ts`); zapas do 10 s. */
@@ -927,32 +926,40 @@ function absent(err) {
927
926
  return null;
928
927
  throw err;
929
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
+ }
930
961
  export const nodeHookListIo = {
931
- async lstat(file) {
932
- const info = await fs.lstat(file).catch(absent);
933
- if (info === null)
934
- return null;
935
- const kind = info.isSymbolicLink() ? 'link' : info.isFile() ? 'file' : info.isDirectory() ? 'dir' : 'other';
936
- return { kind, size: info.size, changedAt: Math.max(info.ctimeMs, info.mtimeMs) };
937
- },
938
- readlink: (file) => fs.readlink(file),
939
- // Odczyt przez `safe-read.ts`: FIFO albo urządzenie pod nazwą pliku ustawień nie zawiesza serwera. Nie-plik
940
- // i plik ponad sufit to błąd z kodem, więc lista daje „brak dowodu”, a nie pustą warstwę.
941
- async readFile(file) {
942
- let read;
943
- try {
944
- read = await readRegularFile(file, { maxBytes: HOOK_LIST_MAX_FILE_BYTES, followSymlink: true });
945
- }
946
- catch (err) {
947
- return absent(err);
948
- }
949
- if (read === null)
950
- throw Object.assign(new Error(`not a regular file: ${file}`), { code: 'EFTYPE' });
951
- if (read.truncated)
952
- throw Object.assign(new Error(`over the read ceiling: ${file}`), { code: 'EFBIG' });
953
- return read.bytes.toString('utf8');
954
- },
955
- readdir: (dir) => fs.readdir(dir).catch(absent),
962
+ ...hookListDiskIo(DIRECT_DISK),
956
963
  ps: (pid) => new Promise((resolve) => {
957
964
  execFile(PS_PATH, ['-ww', '-o', 'etime=,args=', '-p', String(pid)], {
958
965
  timeout: PS_TIMEOUT_MS, killSignal: 'SIGKILL', env: { LC_ALL: 'C' }, maxBuffer: 1024 * 1024,
@@ -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,4 +1,5 @@
1
1
  import { HOOK_PERMISSION_REQUEST_EVENT, HOOK_QUESTION_TOOL } from './hook/contract.js';
2
+ import { screenFallbackHolds } from './screen-fallback.js';
2
3
  import { askFormOnScreen, cliDialogOnScreen } from './presence.js';
3
4
  /**
4
5
  * Werdykt rozdzielacza — ZAMKNIĘTA lista, bo wpisy dziennika mają się sumować:
@@ -93,16 +94,14 @@ const KNOWN_DIALOG_CARD_TOOLS = new Set(['dialog:trust', 'dialog:model']);
93
94
  * z ekranu, które bywa zgodą `WebFetch`) tylko przy klasie `input` albo `dialog` z rejestru. Przy `off` i `shadow`
94
95
  * nic się nie zmienia. Klawisz `escape` (odmowa) tej bramki nie przechodzi: niczego nie zatwierdza.
95
96
  *
96
- * Exception: the "Yes" button of a card that carries a measured consent mark under the
97
- * same registry class passes (sandbox network, MCP tool with user interaction). Neither has a working hook answer,
98
- * and the driver still checks the mark on a fresh screen and the registry right before the key.
97
+ * Two exceptions ({@link consentDigitException}) let the "Yes" button through; the driver checks each again on a fresh
98
+ * screen and the registry right before the key.
99
99
  */
100
100
  export function consentDigitBlocked(input) {
101
101
  if (input.mode === 'off' || input.mode === 'shadow')
102
102
  return false;
103
- if (input.cliDialog === 'permission' || input.cliDialog === 'sandbox') {
104
- return !(input.consent && input.measured?.cliDialog === input.cliDialog);
105
- }
103
+ if (input.cliDialog === 'permission' || input.cliDialog === 'sandbox')
104
+ return consentDigitException(input) === null;
106
105
  if (KNOWN_DIALOG_CARD_TOOLS.has(input.toolName))
107
106
  return false;
108
107
  if (input.consent)
@@ -111,6 +110,22 @@ export function consentDigitBlocked(input) {
111
110
  return false;
112
111
  return input.cliDialog !== 'input' && input.cliDialog !== 'dialog';
113
112
  }
113
+ /**
114
+ * The exception that lets the "Yes" button of a `permission` or `sandbox` card through in channel mode, or `null`:
115
+ * a measured consent mark under the same registry class (sandbox network, MCP tool with user interaction: neither has
116
+ * a working hook answer), else the emergency mark of a `permission` dialog without a hook, by the rule of
117
+ * `screen-fallback.ts` under the live mode and class. Never for an answer (`consent: false`).
118
+ */
119
+ export function consentDigitException(input) {
120
+ if (!input.consent)
121
+ return null;
122
+ if (input.measured !== undefined && input.measured.cliDialog === input.cliDialog)
123
+ return 'measured';
124
+ if (input.fallback !== undefined && screenFallbackHolds(input.fallback, input.mode, input.cliDialog)) {
125
+ return 'screen-fallback';
126
+ }
127
+ return null;
128
+ }
114
129
  /**
115
130
  * The hook dump as router input: only a tool permission request dump matters, i.e. the `PermissionRequest`
116
131
  * event (the CLI is about to ask) for a tool other than the question form. A `PreToolUse` dump (the tool input
@@ -47,6 +47,21 @@ export function subagentDialogOnScreen(text) {
47
47
  const found = optionRegion(lines);
48
48
  return found !== null && blockFromSubagent(lines, dialogBlock(lines, found.firstOption));
49
49
  }
50
+ /**
51
+ * The thread of the dialog standing on screen, read from the title line of its block: `subagent` with the subagent
52
+ * suffix, `main` without it, `null` when no title line can be read (no complete option list, an ambiguous block, the
53
+ * title above the pane edge), so that a missing suffix is never taken for the main thread.
54
+ */
55
+ export function dialogThreadOnScreen(text) {
56
+ const lines = trimmedLines(text);
57
+ const found = optionRegion(lines);
58
+ if (found === null)
59
+ return null;
60
+ const block = dialogBlock(lines, found.firstOption);
61
+ if (block.ambiguous || block.titleLine < 0)
62
+ return null;
63
+ return blockFromSubagent(lines, block) ? 'subagent' : 'main';
64
+ }
50
65
  /**
51
66
  * Region opcji, z którego czyta {@link parseOptions}: pierwszy kandydat (od najwęższego), który widzi
52
67
  * spójną i KOMPLETNĄ listę opcji `1…N`; `null`, gdy żaden.
@@ -132,9 +147,15 @@ export function parseOptions(text, opts) {
132
147
  * line of its own. The call trace in the region (`regionCallTrace`) guards the reverse mistake:
133
148
  * a signature sentence above a real consent dialog may not rename it to `ExitPlanMode`. The
134
149
  * sandbox network dialog is recognised by the block TITLE, under the same condition.
150
+ *
151
+ * The signature sentence is matched on the region lines joined by a space: a pane narrower than the sentence
152
+ * wraps it ("…is ready to" / "execute. Would you like to proceed?" at 50 columns, CLI 2.1.331), and a match
153
+ * within one line would leave the dialog `other`. A question form keeps its kind: the author of the question may
154
+ * quote the sentence, and the joined region would then rename the form to `ExitPlanMode`.
135
155
  */
136
- const regionText = region.join('\n');
137
- const planDialog = (PLAN_DIALOG_PATTERN.test(regionText) || PLAN_EXIT_CONFIRM_PATTERN.test(regionText))
156
+ const regionText = region.join(' ');
157
+ const planDialog = kind !== 'question'
158
+ && (PLAN_DIALOG_PATTERN.test(regionText) || PLAN_EXIT_CONFIRM_PATTERN.test(regionText))
138
159
  && !trace && (block.title === null || block.title.kind === 'plan');
139
160
  const networkDialog = !planDialog && block.title?.kind === 'network' && !trace;
140
161
  // A file dialog whose key footer a narrow pane cut or wrapped has lost its only kind marker (`screen/file-dialog.ts`).
@@ -40,12 +40,14 @@ function mcpWords(text) {
40
40
  return text.toLowerCase().split(/[\s_-]+/u).filter((word) => word !== '').join(' ');
41
41
  }
42
42
  /**
43
- * Czy tytuł narzędzia MCP z ekranu ({@link ScreenDialog.mcpTool}) jest TYM narzędziem z jsonl/hooka?
43
+ * Whether the MCP tool title on screen ({@link ScreenDialog.mcpTool}) is THIS tool from the jsonl entry or hook dump.
44
44
  *
45
- * Nazwa `mcp__<serwer>__<narzędzie>` traci przedrostek `<serwer>_` (serwer `catalog` nazywa narzędzia
46
- * `catalog_get_task`) i oba teksty idą do słów bez wielkości liter. Tytuł, który nie powtarza nazwy
47
- * (serwer nadał narzędziu inny tytuł), daje `false`: rozjazd, karta bez przycisków. Sam serwer
48
- * nie wystarcza: karta `delete_task` przeszłaby nad dialogiem `get_project_tree_layout`.
45
+ * Both texts become lower-case words. The title matches `<tool>` of `mcp__<server>__<tool>` without the `<server>_`
46
+ * prefix (server `catalog` names its tools `catalog_get_task`, title "Get Task") or the whole `<tool>`, when the
47
+ * title repeats the prefix ("Catalog get task"). A title that repeats neither (the server gave the tool another
48
+ * title) gives `false`: a mismatch, a card without buttons. The server alone is not enough: a `delete_task` card
49
+ * would pass over a `get_project_tree_layout` dialog. The two forms cannot tell `x_get` from `x_x_get` on one server
50
+ * (both read "X get"): the screen shows no raw tool name, so a server with a doubled prefix stays ambiguous.
49
51
  */
50
52
  export function mcpTitleMatches(toolName, screenTitle) {
51
53
  const match = MCP_TOOL_NAME_PATTERN.exec(toolName);
@@ -54,8 +56,8 @@ export function mcpTitleMatches(toolName, screenTitle) {
54
56
  if (server === undefined || tool === undefined || screenTitle === null)
55
57
  return false;
56
58
  const bare = tool.startsWith(`${server}_`) ? tool.slice(server.length + 1) : tool;
57
- const words = mcpWords(bare);
58
- return words !== '' && words === mcpWords(screenTitle);
59
+ const title = mcpWords(screenTitle);
60
+ return title !== '' && (title === mcpWords(bare) || title === mcpWords(tool));
59
61
  }
60
62
  /** Nazwa narzędzia, którego dialog jest FORMULARZEM pytania, a nie zgodą na wykonanie. */
61
63
  export const ASK_USER_QUESTION_TOOL = 'AskUserQuestion';