@rarog/server 1.1.0-beta.1 → 1.1.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 (95) 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/cli/update-registry.js +31 -1
  21. package/server/src/cli/update.js +128 -6
  22. package/server/src/config/protected-dirs.js +2 -0
  23. package/server/src/config/roots.js +13 -8
  24. package/server/src/config/work-area.js +36 -12
  25. package/server/src/config-env.js +9 -0
  26. package/server/src/config.js +17 -1
  27. package/server/src/demo/control.js +9 -1
  28. package/server/src/drivers/herdr/consent-no-hook.js +103 -8
  29. package/server/src/drivers/herdr/screen-fallback.js +246 -0
  30. package/server/src/drivers/herdr-driver.js +78 -9
  31. package/server/src/files/file-index.js +5 -3
  32. package/server/src/files/listing.js +8 -2
  33. package/server/src/files/path-rule.js +95 -41
  34. package/server/src/files/refusals.js +14 -0
  35. package/server/src/files/session-gate.js +11 -6
  36. package/server/src/folder-gate/client.js +314 -0
  37. package/server/src/folder-gate/disk.js +455 -0
  38. package/server/src/folder-gate/folders.js +23 -0
  39. package/server/src/folder-gate/gate.js +220 -0
  40. package/server/src/folder-gate/helper.js +118 -0
  41. package/server/src/folder-gate/install.js +27 -0
  42. package/server/src/folder-gate/relay-worker.js +147 -0
  43. package/server/src/folder-gate/types.js +115 -0
  44. package/server/src/folder-gate/wire.js +170 -0
  45. package/server/src/fs-browse.js +55 -23
  46. package/server/src/fs-mkdir.js +3 -1
  47. package/server/src/git-status.js +13 -5
  48. package/server/src/git-watch.js +130 -19
  49. package/server/src/git-work-tree.js +3 -3
  50. package/server/src/herdr/client.js +2 -2
  51. package/server/src/herdr/commands/discover.js +21 -9
  52. package/server/src/herdr/dialogs/consent-gate.js +28 -8
  53. package/server/src/herdr/dialogs/decide/sources.js +5 -2
  54. package/server/src/herdr/dialogs/hook/contract.js +1 -1
  55. package/server/src/herdr/dialogs/index.js +7 -2
  56. package/server/src/herdr/dialogs/layer1/cycle.js +43 -7
  57. package/server/src/herdr/dialogs/layer1/hook-list/hook-list.js +34 -27
  58. package/server/src/herdr/dialogs/layer1/screen-key.js +52 -0
  59. package/server/src/herdr/dialogs/router.js +21 -6
  60. package/server/src/herdr/dialogs/screen/parse.js +23 -2
  61. package/server/src/herdr/dialogs/screen/resolve.js +9 -7
  62. package/server/src/herdr/dialogs/screen-fallback.js +55 -0
  63. package/server/src/herdr/dialogs/shadow/alive.js +9 -8
  64. package/server/src/herdr/jsonl-follow.js +55 -14
  65. package/server/src/herdr/provenance.js +3 -3
  66. package/server/src/herdr/socket.js +25 -28
  67. package/server/src/herdr/supervisor.js +13 -10
  68. package/server/src/herdr/transcript-path.js +36 -0
  69. package/server/src/herdr/trust.js +11 -8
  70. package/server/src/herdr/uploads-registry.js +3 -2
  71. package/server/src/herdr/uploads.js +170 -47
  72. package/server/src/index.js +22 -3
  73. package/server/src/iroh/listener.js +3 -0
  74. package/server/src/iroh/log-budget.js +1 -0
  75. package/server/src/iroh/socket.js +2 -1
  76. package/server/src/notes/store.js +3 -2
  77. package/server/src/router.js +13 -1
  78. package/server/src/routes/projects.js +5 -1
  79. package/server/src/routes/sessions.js +10 -4
  80. package/server/src/routes/system.js +4 -0
  81. package/server/src/safe-read.js +12 -12
  82. package/server/src/sessions/companion-scope.js +10 -5
  83. package/server/src/sessions/done-retention.js +57 -0
  84. package/server/src/sessions/launch-gate.js +2 -2
  85. package/server/src/sessions/manager.js +35 -59
  86. package/server/src/sessions/project-scan.js +9 -3
  87. package/server/src/sessions/ring-buffer.js +8 -21
  88. package/server/src/sessions/session-git.js +31 -2
  89. package/server/src/sessions/session.js +1 -1
  90. package/server/src/sessions/state-sentences.js +1 -1
  91. package/server/src/sse.js +121 -22
  92. package/server/src/term/herdr-backend.js +2 -2
  93. package/server/src/term/index.js +2 -15
  94. package/server/src/term/registry.js +4 -3
  95. package/server/src/term/ws.js +9 -1
@@ -13,8 +13,21 @@ export const NO_HOOK_GRACE_MS = 3_000;
13
13
  * flap. Past the budget the episode stays judged and gets no line.
14
14
  */
15
15
  export const NO_HOOK_EVALUATIONS = 3;
16
+ /**
17
+ * How long past the grace a card waits for the first judgement ({@link NoHookStanding.pending}): `ps` gives up after
18
+ * 1 s, but a facts read that hangs must not keep the card from the phone. Past it the card goes out without the
19
+ * emergency button, and a judgement that ends later can still give it to the same card.
20
+ */
21
+ export const NO_HOOK_JUDGE_WAIT_MS = 2_000;
16
22
  /** Reads of the session facts per episode: a read that ends on another process or `cwd` gives none and goes again. */
17
23
  const FACTS_READS = 2;
24
+ /**
25
+ * Judgements after the first, at a registry signal at most once per {@link NO_HOOK_REJUDGE_MS}, while the hook process
26
+ * stands in `ps` or the hook list is in doubt: the same card gets the emergency button once the fact mends. Past the
27
+ * budget (about a minute of signals) the doubt stays and the card stays without it.
28
+ */
29
+ export const NO_HOOK_REJUDGE_MAX = 40;
30
+ export const NO_HOOK_REJUDGE_MS = 1_000;
18
31
  /** Card identities remembered for the `no approve button` line; past the cap the memory starts again. */
19
32
  const BUTTONLESS_MAX = 256;
20
33
  let episodes = 0;
@@ -83,6 +96,7 @@ export class ConsentNoHook {
83
96
  id: `no-hook:${String(episodes)}`, sessionId, blockSeq: this.#port.blockedSeq(), t0, openedAt: now,
84
97
  since: this.#since, callId: undefined, print: undefined, tool: card.active.toolName, screenButton: false,
85
98
  thread: 'main', waiting: this.#port.cliWaiting() === 'permission', timer: null, evaluations: 0, state: 'grace',
99
+ judgement: null, restarting: false, judging: false, rejudged: 0, judgedAt: 0,
86
100
  };
87
101
  this.#describe(episode, card);
88
102
  this.#episode = episode;
@@ -91,8 +105,33 @@ export class ConsentNoHook {
91
105
  if (episode.state === 'grace')
92
106
  episode.state = 'due';
93
107
  this.#observe(() => { this.#judge(episode); });
108
+ this.#judged();
109
+ // A first judgement still reading its facts at the end of the wait lets the card go.
110
+ if (episode.judging && episode.state !== 'ended') {
111
+ episode.timer = this.#scheduler.setTimeout(() => {
112
+ episode.timer = null;
113
+ this.#judged();
114
+ }, NO_HOOK_JUDGE_WAIT_MS);
115
+ }
94
116
  }, Math.max(0, t0 + NO_HOOK_GRACE_MS - now));
95
117
  }
118
+ /** The standing episode, `null` without one; never throws. */
119
+ standing() {
120
+ try {
121
+ const episode = this.#episode;
122
+ if (episode === null || !this.#stands(episode))
123
+ return null;
124
+ return {
125
+ id: episode.id, sessionId: episode.sessionId, judgement: episode.judgement,
126
+ pending: episode.state === 'grace' || (episode.judging && episode.judgement === null
127
+ && this.#scheduler.now() < episode.t0 + NO_HOOK_GRACE_MS + NO_HOOK_JUDGE_WAIT_MS),
128
+ t0: this.#epochOf(episode.t0), since: episode.since, graceEnd: episode.t0 + NO_HOOK_GRACE_MS,
129
+ };
130
+ }
131
+ catch {
132
+ return null;
133
+ }
134
+ }
96
135
  /**
97
136
  * A card that goes out: when the channel gate took its approve button (the `off` path card would have it), one
98
137
  * `consent: no approve button` line per card identity.
@@ -137,6 +176,27 @@ export class ConsentNoHook {
137
176
  episode.waiting = true;
138
177
  if (episode.state === 'due')
139
178
  this.#judge(episode);
179
+ else if (this.#mendable(episode))
180
+ this.#rejudge(episode);
181
+ else if (episode.state === 'judged' && !episode.judging && episode.restarting && !this.#restarting()) {
182
+ // The restart grace ended past the judgement: no fact to read again, only the button to ask again.
183
+ episode.restarting = false;
184
+ this.#judged();
185
+ }
186
+ }
187
+ /** A judged episode whose `ps` or hook list refuses the button, with budget and pause left, and no read running. */
188
+ #mendable(episode) {
189
+ const judgement = episode.judgement;
190
+ return episode.state === 'judged' && judgement !== null && !episode.judging
191
+ && (judgement.hookRunning !== false || judgement.foreignHook !== false)
192
+ && episode.rejudged < NO_HOOK_REJUDGE_MAX && this.#scheduler.now() - episode.judgedAt >= NO_HOOK_REJUDGE_MS;
193
+ }
194
+ #rejudge(episode) {
195
+ const sources = this.#deps.consentNoHook;
196
+ if (sources === undefined || !this.#stands(episode) || this.#traced(sources, episode))
197
+ return;
198
+ episode.rejudged += 1;
199
+ void this.#judgeFacts(sources, episode, false).catch((err) => { this.#failed(err); });
140
200
  }
141
201
  /**
142
202
  * `drop` hands the effective block over within one block (herdr's own `blocked` follows the CLI registry
@@ -239,9 +299,26 @@ export class ConsentNoHook {
239
299
  if (this.#traced(sources, episode))
240
300
  return;
241
301
  episode.evaluations += 1;
242
- void this.#judgeFacts(sources, episode).catch((err) => { this.#failed(err); });
302
+ void this.#judgeFacts(sources, episode, true).catch((err) => { this.#failed(err); });
243
303
  }
244
- async #judgeFacts(sources, episode) {
304
+ /** The first judgement writes the `no hook` line; a later one only renews the facts of the emergency button. */
305
+ async #judgeFacts(sources, episode, first) {
306
+ episode.judging = true;
307
+ try {
308
+ await this.#judgeOnce(sources, episode, first);
309
+ }
310
+ finally {
311
+ episode.judging = false;
312
+ episode.judgedAt = this.#scheduler.now();
313
+ // The first judgement ended: the wait it had (grace timer callback) is over.
314
+ if (first && episode.timer !== null) {
315
+ this.#scheduler.clearTimeout(episode.timer);
316
+ episode.timer = null;
317
+ }
318
+ this.#judged();
319
+ }
320
+ }
321
+ async #judgeOnce(sources, episode, first) {
245
322
  let facts = null;
246
323
  for (let read = 0; read < FACTS_READS && facts === null; read += 1) {
247
324
  facts = await sources.facts({ sessionId: episode.sessionId, episode: episode.id }).catch(() => null);
@@ -257,18 +334,23 @@ export class ConsentNoHook {
257
334
  if (this.#episode !== episode || !this.#stands(episode) || this.#traced(sources, episode))
258
335
  return;
259
336
  if (!consentChannelOpen(consentModeNow(this.#deps)) || this.#port.cliWaiting() !== 'permission') {
260
- if (episode.evaluations < NO_HOOK_EVALUATIONS)
337
+ if (first && episode.evaluations < NO_HOOK_EVALUATIONS)
261
338
  episode.state = 'due';
262
339
  return;
263
340
  }
264
341
  const layers = facts?.layers ?? null;
342
+ const cause = noHookCause({
343
+ hookRunning, outsideWorkArea: this.#outsideWorkArea(sources, facts?.cwd ?? null),
344
+ disableAllHooks: layers?.disableAllHooks ?? null, allowManagedHooksOnly: layers?.allowManagedHooksOnly ?? null,
345
+ rarogEntry: layers?.rarogEntry ?? null,
346
+ });
347
+ episode.judgement = { cause, hookRunning, foreignHook: facts?.foreignHook ?? null };
348
+ episode.restarting = this.#restarting();
349
+ if (!first)
350
+ return;
265
351
  this.#log(noHookLine({
266
352
  sessionId: episode.sessionId,
267
- cause: noHookCause({
268
- hookRunning, outsideWorkArea: this.#outsideWorkArea(sources, facts?.cwd ?? null),
269
- disableAllHooks: layers?.disableAllHooks ?? null, allowManagedHooksOnly: layers?.allowManagedHooksOnly ?? null,
270
- rarogEntry: layers?.rarogEntry ?? null,
271
- }),
353
+ cause,
272
354
  tool: episode.tool, cli: this.#port.cliVersion(), mode: this.#port.permissionMode(), thread: episode.thread,
273
355
  afterMs: this.#scheduler.now() - episode.t0, hooks: facts?.verdict ?? null, statusline,
274
356
  screenButton: episode.screenButton,
@@ -302,6 +384,15 @@ export class ConsentNoHook {
302
384
  const screen = this.#port.screenText();
303
385
  return screen !== null && subagentDialogOnScreen(screen) ? 'subagent' : 'main';
304
386
  }
387
+ /** The server is within its restart grace; an exception counts as within. */
388
+ #restarting() {
389
+ try {
390
+ return this.#deps.consentNoHook?.restarting() ?? false;
391
+ }
392
+ catch {
393
+ return true;
394
+ }
395
+ }
305
396
  #proofRules(sessionId) {
306
397
  try {
307
398
  return this.#deps.consentNoHook?.proofRules(sessionId) ?? null;
@@ -313,4 +404,8 @@ export class ConsentNoHook {
313
404
  #log(line) {
314
405
  this.#deps.logger?.(line);
315
406
  }
407
+ /** Tells the port that the judgement changed; its failure stays here. */
408
+ #judged() {
409
+ this.#observe(() => { this.#port.judged?.(); });
410
+ }
316
411
  }
@@ -0,0 +1,246 @@
1
+ import { consentModeNow, dialogThreadOnScreen, offPathApprove, screenFallbackGuard, screenFallbackKeyLine, screenFallbackRefusedLine, } from '../../herdr/dialogs/index.js';
2
+ import { canonicalSha256 } from '../../herdr/dialogs/hook/canon.js';
3
+ export class ScreenFallback {
4
+ #deps;
5
+ #inScope;
6
+ #port;
7
+ #last = null;
8
+ /** The episode each mark was stamped in: a key may only answer the episode its card was judged in. */
9
+ #episodes = new WeakMap();
10
+ constructor(config, port) {
11
+ this.#deps = config.deps;
12
+ this.#inScope = config.inScope;
13
+ this.#port = port;
14
+ }
15
+ /**
16
+ * The card with the mark when the rule gives it the button now, without any mark otherwise. A card the rule does not
17
+ * concern comes back unchanged. The card is remembered for {@link judged}.
18
+ */
19
+ stamp(card) {
20
+ const mark = this.#markOf(card);
21
+ let stamped = card;
22
+ if (mark !== undefined)
23
+ stamped = { ...card, active: { ...card.active, screenFallback: mark } };
24
+ else if (card.active.screenFallback !== undefined) {
25
+ const { screenFallback: _old, ...active } = card.active;
26
+ void _old;
27
+ stamped = { ...card, active };
28
+ }
29
+ this.#last = { card: stamped, held: false };
30
+ return stamped;
31
+ }
32
+ /**
33
+ * Whether the card waits instead of going out: its episode is still in the grace (or in its first judgement) and the
34
+ * rule could still give it the button once the judgement comes. A fact that refuses the button already (mode, card,
35
+ * thread, class, a hook trace, the restart grace) lets the card go out at once.
36
+ */
37
+ waits(card) {
38
+ let held = false;
39
+ try {
40
+ const standing = this.#port.standing();
41
+ if (standing?.pending === true && this.#concerns(card)) {
42
+ held = screenFallbackGuard(this.#factsOf(card.active, offPathApprove(card.event), this.#port.screenText(), standing, true)) === null;
43
+ }
44
+ }
45
+ catch {
46
+ held = false;
47
+ }
48
+ if (this.#last?.card === card)
49
+ this.#last.held = held;
50
+ return held;
51
+ }
52
+ /**
53
+ * A judgement of the standing episode began or ended: whether the facade drops the card that stands and evaluates
54
+ * again. `true` for a card that waits, or when the button of the standing card differs from what the facts give now;
55
+ * the evaluation then builds the card again under the same `reqId` and publishes it with or without the button.
56
+ */
57
+ judged(active) {
58
+ try {
59
+ const last = this.#last;
60
+ if (last === null)
61
+ return false;
62
+ if (active === null)
63
+ return last.held;
64
+ if (active !== last.card.active)
65
+ return false;
66
+ return (this.#markOf(last.card) !== undefined) !== (active.screenFallback !== undefined);
67
+ }
68
+ catch {
69
+ return false;
70
+ }
71
+ }
72
+ /**
73
+ * The rule once more right before the key, on fresh facts: the call the transcript holds as waiting now, the live
74
+ * mode and class, the thread from the fresh screen `text`, the hook trace and the hook requests now, the judgement
75
+ * of the same episode the card was marked in, the restart grace. Synchronous, so the facade asks it after its last
76
+ * `await` before the key.
77
+ */
78
+ keyGuard(answered, text) {
79
+ const refuse = (guard) => ({ ok: false, guard });
80
+ try {
81
+ const mark = answered.screenFallback;
82
+ if (mark === undefined)
83
+ return refuse('card');
84
+ // The next call with the same input can stand in the same dialog frame before its episode is noted: the card
85
+ // then stands for a call that is no longer waiting, and the key would answer one that had no grace of its own.
86
+ if (this.#port.pendingCallId() !== mark.toolUseId)
87
+ return refuse('card');
88
+ const standing = this.#port.standing();
89
+ const judgement = standing?.judgement ?? null;
90
+ if (standing === null || judgement === null || this.#episodes.get(mark) !== standing.id) {
91
+ return refuse('judgement');
92
+ }
93
+ const guard = screenFallbackGuard(this.#factsOf(answered, mark.facts.card, text, standing));
94
+ if (guard !== null)
95
+ return refuse(guard);
96
+ return {
97
+ ok: true,
98
+ key: { toolName: answered.toolName, inputSha256: mark.inputSha256, at: this.#deps.now(), since: mark.since },
99
+ line: {
100
+ sessionId: standing.sessionId, tool: answered.toolName, cause: judgement.cause, card: answered.reqId,
101
+ toolUseId: mark.toolUseId,
102
+ },
103
+ };
104
+ }
105
+ catch {
106
+ return refuse('judgement');
107
+ }
108
+ }
109
+ /**
110
+ * The guard that takes the button of a marked card under the live mode and class, the ones the card gate read when
111
+ * it refused the digit; `mode` when the rule cannot be asked.
112
+ */
113
+ gateGuard(answered) {
114
+ const mark = answered.screenFallback;
115
+ if (mark === undefined)
116
+ return 'card';
117
+ try {
118
+ return screenFallbackGuard({
119
+ ...mark.facts, mode: consentModeNow(this.#deps), cliDialog: this.#port.cliWaiting(),
120
+ }) ?? 'mode';
121
+ }
122
+ catch {
123
+ return 'mode';
124
+ }
125
+ }
126
+ /**
127
+ * The digit is about to go: the consent cycle notes the key, so that a hook of this dialog whose request comes after
128
+ * the note goes back to the terminal at once. Synchronous, right before the key: the cycle ties only a record that
129
+ * comes after the note.
130
+ */
131
+ keyNoted(verdict) {
132
+ try {
133
+ this.#deps.consentNoHook?.screenKey?.(verdict.line.sessionId, { ...verdict.key, at: this.#deps.now() });
134
+ }
135
+ catch {
136
+ // The late hook then goes the desk fallback way.
137
+ }
138
+ }
139
+ /** The digit went out: the `screen fallback key` line. */
140
+ keySent(verdict) {
141
+ this.#log(screenFallbackKeyLine(verdict.line));
142
+ }
143
+ /** A tap of the button that sent no key: the `screen fallback refused` line. */
144
+ refused(answered, guard) {
145
+ this.#log(screenFallbackRefusedLine({
146
+ sessionId: this.#port.agentSessionId(), tool: answered.toolName, guard, card: answered.reqId,
147
+ }));
148
+ }
149
+ /**
150
+ * The mark the rule gives the card now, `undefined` without one. Only a consent card for a `tool_use` entry of the
151
+ * transcript (a card from the screen alone is tied to no call), never one with a measured consent mark (that path
152
+ * has its own key checks), and only within an episode judged past its grace.
153
+ */
154
+ #markOf(card) {
155
+ try {
156
+ const standing = this.#port.standing();
157
+ const judgement = standing?.judgement ?? null;
158
+ if (standing === null || judgement === null || !this.#concerns(card) || card.event.type !== 'permission-request') {
159
+ return undefined;
160
+ }
161
+ const facts = this.#factsOf(card.active, offPathApprove(card.event), this.#port.screenText(), standing);
162
+ const callId = card.active.callId;
163
+ if (screenFallbackGuard(facts) !== null || callId === undefined)
164
+ return undefined;
165
+ const { mode: _mode, cliDialog: _class, ...kept } = facts;
166
+ void _mode;
167
+ void _class;
168
+ const mark = {
169
+ facts: kept, cause: judgement.cause, toolUseId: callId, inputSha256: canonicalSha256(card.event.input),
170
+ since: standing.t0,
171
+ };
172
+ this.#episodes.set(mark, standing.id);
173
+ return mark;
174
+ }
175
+ catch {
176
+ return undefined;
177
+ }
178
+ }
179
+ /** A card the rule may concern: sources present, a pane in scope, a transcript entry, no measured mark. */
180
+ #concerns(card) {
181
+ return this.#deps.consentNoHook !== undefined && this.#inScope && card.active.callId !== undefined
182
+ && card.active.measuredConsent === undefined;
183
+ }
184
+ /**
185
+ * The facts of the rule for a card of the standing episode, with the mode and the class live. `hopeful` assumes that
186
+ * the facts the judgement brings come out well and that the class still on its way is `permission` (a card that waits
187
+ * for them). The cheap facts go first, with the trace, the hook requests and the restart grace at their most lenient:
188
+ * when they refuse already, the full facts refuse too, so the hook trace (a read of the disk) is not read and the
189
+ * facts that come back only name the refusal.
190
+ */
191
+ #factsOf(active, card, text, standing, hopeful = false) {
192
+ const sources = this.#deps.consentNoHook;
193
+ const judgement = standing.judgement;
194
+ const cliDialog = this.#port.cliWaiting();
195
+ const cheap = {
196
+ mode: consentModeNow(this.#deps), cliDialog: hopeful ? cliDialog ?? 'permission' : cliDialog, card,
197
+ thread: this.#threadOf(active, text), judged: hopeful || judgement !== null, trace: false, hookWaits: false,
198
+ hookRunning: hopeful ? false : judgement?.hookRunning ?? null,
199
+ foreignHook: hopeful ? false : judgement?.foreignHook ?? null, restarting: false,
200
+ };
201
+ if (screenFallbackGuard(cheap) !== null)
202
+ return cheap;
203
+ return {
204
+ ...cheap, trace: this.#trace(sources, standing), hookWaits: this.#hookWaits(), restarting: this.#restarting(sources),
205
+ };
206
+ }
207
+ /** `subagent` for a card from a subagent's dump, else the title of the dialog on screen; `null` = no title. */
208
+ #threadOf(active, text) {
209
+ if (active.origin?.agentId !== undefined)
210
+ return 'subagent';
211
+ return text === null ? null : dialogThreadOnScreen(text);
212
+ }
213
+ /** A hook trace of the session since the previous episode; an exception or no answer counts as one. */
214
+ #trace(sources, standing) {
215
+ try {
216
+ return sources?.hookTrace(standing.sessionId, standing.since) ?? null;
217
+ }
218
+ catch {
219
+ return null;
220
+ }
221
+ }
222
+ #hookWaits() {
223
+ try {
224
+ return this.#port.keyHookWaits();
225
+ }
226
+ catch {
227
+ return true;
228
+ }
229
+ }
230
+ #restarting(sources) {
231
+ try {
232
+ return sources?.restarting() ?? true;
233
+ }
234
+ catch {
235
+ return true;
236
+ }
237
+ }
238
+ #log(line) {
239
+ try {
240
+ this.#deps.logger?.(line);
241
+ }
242
+ catch {
243
+ // The logger itself failed: nothing more to tell.
244
+ }
245
+ }
246
+ }
@@ -21,6 +21,7 @@ import { CliReserve } from './herdr/cli-reserve.js';
21
21
  import { CommandDialogSettle } from './herdr/command-dialog-settle.js';
22
22
  import { ConsentChannel } from './herdr/consent-channel.js';
23
23
  import { ConsentNoHook } from './herdr/consent-no-hook.js';
24
+ import { ScreenFallback } from './herdr/screen-fallback.js';
24
25
  import { Layer2Cards, isLayer2Id, layer2HoldsKeys } from './herdr/layer2-card.js';
25
26
  import { Layer2Step } from './herdr/layer2-step.js';
26
27
  import { approveContext, auditRefusal, layer2KeyRefusal, refuseDecision, refuseNote, refuseSend, reportStaleDecision, } from './herdr/refusals.js';
@@ -288,6 +289,8 @@ export class HerdrDriver {
288
289
  #cliReserve;
289
290
  /** Consent without a hook and cards without the approve button, in the log: `drivers/herdr/consent-no-hook.ts`. */
290
291
  #noHook;
292
+ /** The emergency approve button of a consent dialog without a hook: `drivers/herdr/screen-fallback.ts`. */
293
+ #screenFallback;
291
294
  /** The port of the refusals and their audit funnel: `drivers/herdr/refusals.ts`. */
292
295
  #refusals;
293
296
  /** The wait behind a command dialog the driver confirmed: `drivers/herdr/command-dialog-settle.ts`. */
@@ -395,6 +398,18 @@ export class HerdrDriver {
395
398
  cliWaiting: () => this.#cliReserve.cliWaiting, screenText: () => this.#screenText,
396
399
  cliVersion: () => (this.#cliReserve.cliSignal?.kind === 'unknown' ? null : this.#cliReserve.cliSignal?.version ?? null),
397
400
  permissionMode: () => (this.#mode === 'unknown' ? null : this.#mode),
401
+ // The button of the standing card changed (or a card waits for it): the card goes out again under its `reqId`.
402
+ judged: () => {
403
+ if (this.#disposed || !this.#screenFallback.judged(this.#activeReq))
404
+ return;
405
+ this.#clearActive('screen fallback changed');
406
+ this.#scheduleEvaluate();
407
+ },
408
+ });
409
+ this.#screenFallback = new ScreenFallback({ deps, inScope: this.#inScope }, {
410
+ agentSessionId: () => this.#agentSessionId, cliWaiting: () => this.#cliReserve.cliWaiting,
411
+ screenText: () => this.#screenText, standing: () => this.#noHook.standing(),
412
+ keyHookWaits: () => this.#promptQueue.keyHookWaits(), pendingCallId: () => this.#pending?.id ?? null,
398
413
  });
399
414
  this.#promptQueue.restore(this.#engine === 'claude', () => ++this.#turnGuard.sendGeneration);
400
415
  if (this.#follower !== null)
@@ -1254,6 +1269,11 @@ export class HerdrDriver {
1254
1269
  */
1255
1270
  if (active.trustArrow !== undefined && decision === 'allow')
1256
1271
  return this.#approveTrustArrow(active, active.trustArrow);
1272
+ // The emergency button approves this one call: "don't ask again" stays at the desk.
1273
+ if (decision === 'allow-always' && active.screenFallback !== undefined) {
1274
+ this.#screenFallback.refused(active, 'always');
1275
+ return Promise.resolve(refuseDecision(this.#refusals, TERMINAL_ONLY_MESSAGE, 'screen fallback: once only', 'terminal-only'));
1276
+ }
1257
1277
  const option = decision === 'allow-always'
1258
1278
  ? alwaysOption(active.options)
1259
1279
  : affirmativeOption(active.options);
@@ -1634,30 +1654,57 @@ export class HerdrDriver {
1634
1654
  return STALE;
1635
1655
  // Tryb kanału (`main`): zgoda na narzędzie nie idzie cyfrą, także odpowiedź na potwierdzenie z ekranu.
1636
1656
  if (consentDigitRefused(this.#deps, this.#cliReserve.cliWaiting, answered, consent)) {
1657
+ // An emergency card that lost its button under the live mode or class: 410, and the card goes out again.
1658
+ if (consent && answered.screenFallback !== undefined) {
1659
+ return this.#fallbackLost(answered, this.#screenFallback.gateGuard(answered), null);
1660
+ }
1637
1661
  return refuseDecision(this.#refusals, TERMINAL_ONLY_MESSAGE, 'consent channel main: no digit for a consent', 'terminal-only');
1638
1662
  }
1639
1663
  const shadow = consent && this.#shadowChannel() !== undefined ? await this.#shadowStep('allow', answered) : null;
1640
1664
  // Digit that only the measured mark lets through: the send shield before the fresh read and the key.
1641
- const mark = consent
1642
- && consentDigitRefused(this.#deps, this.#cliReserve.cliWaiting, { ...answered, measuredConsent: undefined }, true)
1643
- ? answered.measuredConsent : undefined;
1644
- const shield = mark === undefined ? null : await this.#promptQueue.keyShield(mark.cliDialog);
1665
+ const bare = { ...answered, measuredConsent: undefined, screenFallback: undefined };
1666
+ const gated = consent && consentDigitRefused(this.#deps, this.#cliReserve.cliWaiting, bare, true);
1667
+ const mark = gated ? answered.measuredConsent : undefined;
1668
+ // Digit that only the emergency mark lets through: "Yes" alone, the same shields, then the rule on fresh facts,
1669
+ // which refuses whatever moved since the gate above. A marked card takes this path in every mode, and a mode that
1670
+ // left `main` or `all` since the card refuses the key: the card goes out again as the live mode gives it.
1671
+ const fallback = consent && mark === undefined && answered.screenFallback !== undefined;
1672
+ if (fallback && !gated)
1673
+ return this.#fallbackLost(answered, this.#screenFallback.gateGuard(answered), shadow);
1674
+ if (fallback && option.digit !== affirmativeOption(answered.options)?.digit) {
1675
+ this.#screenFallback.refused(answered, 'always');
1676
+ return refuseDecision(this.#refusals, TERMINAL_ONLY_MESSAGE, 'screen fallback: once only', 'terminal-only');
1677
+ }
1678
+ const shielded = mark?.cliDialog ?? (fallback ? 'permission' : null);
1679
+ const shield = shielded === null ? null : await this.#promptQueue.keyShield(shielded);
1680
+ if (shield !== null && fallback)
1681
+ return this.#fallbackLost(answered, shield, shadow);
1645
1682
  if (shield !== null) {
1646
1683
  return refuseDecision(this.#refusals, SCREEN_CHANGED_MESSAGE, `measured: ${shield}`, 'screen-changed');
1647
1684
  }
1648
1685
  const held = await this.#digitStillHolds(option, answered);
1649
1686
  if (!held.ok) {
1650
1687
  this.#shadowKeySent(shadow, false);
1688
+ if (fallback)
1689
+ this.#screenFallback.refused(answered, 'screen');
1651
1690
  return held.outcome;
1652
1691
  }
1692
+ // From here to the key nothing awaits: the rule, the channel card and the hook requests are asked last.
1693
+ const verdict = fallback ? this.#screenFallback.keyGuard(answered, this.#screenText) : null;
1694
+ if (verdict?.ok === false)
1695
+ return this.#fallbackLost(answered, verdict.guard, shadow);
1653
1696
  // Zgoda z karty, a dialog przejęła karta kanału zgód (także w trakcie świeżego odczytu): cyfra trafiłaby
1654
1697
  // w dialog, na który odpowiada hook. Bez klawisza; karta z ekranu wygasa (410).
1655
1698
  if (consent && this.#consentChannel.consentCardStands(true)) {
1656
1699
  this.#shadowKeySent(shadow, false);
1700
+ if (fallback)
1701
+ this.#screenFallback.refused(answered, 'channel-card');
1657
1702
  return STALE;
1658
1703
  }
1659
1704
  // Measured digit: a hook registration without a card can come during the fresh read, after the shield.
1660
- if (mark !== undefined && this.#promptQueue.keyHookWaits()) {
1705
+ if ((mark !== undefined || fallback) && this.#promptQueue.keyHookWaits()) {
1706
+ if (fallback)
1707
+ return this.#fallbackLost(answered, 'hook', shadow);
1661
1708
  return refuseDecision(this.#refusals, SCREEN_CHANGED_MESSAGE, 'measured: hook', 'screen-changed');
1662
1709
  }
1663
1710
  const live = held.dialog;
@@ -1676,7 +1723,13 @@ export class HerdrDriver {
1676
1723
  // Ekran, w który idzie cyfra: po klawiszu mówi też, który dialog rozstrzygnięto (`#clearHookAfterDecision`).
1677
1724
  const resolvedText = this.#screenText;
1678
1725
  const shot = { bodyPrint: live.bodyPrint, screenReqId: this.#screenIdentity(resolvedText) };
1679
- const sent = await this.#send(() => this.#deps.client.sendKeys(this.#paneId, [option.digit]), {
1726
+ const sent = await this.#send(() => {
1727
+ // The emergency key is noted right before it goes, with no await in between. A note of a key that then
1728
+ // fails stays for its minute: at worst a late hook of this dialog goes back to the terminal.
1729
+ if (verdict?.ok === true)
1730
+ this.#screenFallback.keyNoted(verdict);
1731
+ return this.#deps.client.sendKeys(this.#paneId, [option.digit]);
1732
+ }, {
1680
1733
  // `approve`, nie `send_keys`: to jest ZATWIERDZENIE dialogu z kontekstem decyzji
1681
1734
  // (`toolName` + `optionLabel`), a runbook kradzieży (`docs/security-model.md`)
1682
1735
  // grepuje `"method":"approve"`; wpis `send_keys` dałby
@@ -1692,6 +1745,8 @@ export class HerdrDriver {
1692
1745
  this.#shadowKeySent(shadow, sent);
1693
1746
  if (!sent)
1694
1747
  return refuseSend(this.#refusals);
1748
+ if (verdict?.ok === true)
1749
+ this.#screenFallback.keySent(verdict);
1695
1750
  /*
1696
1751
  * Tryb zatwierdzania z ŻYWEGO odczytu, nie z karty: `preview` jest
1697
1752
  * własnością POJEDYNCZEGO pytania, a formularz przełącza zakładki bez mignięcia
@@ -1723,6 +1778,15 @@ export class HerdrDriver {
1723
1778
  });
1724
1779
  return step.then((outcome) => outcome ?? STALE);
1725
1780
  }
1781
+ /** The emergency button lost before the key: no key, the refused line, 410, and the card goes out again. */
1782
+ #fallbackLost(answered, guard, shadow) {
1783
+ this.#shadowKeySent(shadow, false);
1784
+ this.#screenFallback.refused(answered, guard);
1785
+ if (this.#activeReq === answered)
1786
+ this.#clearActive('screen fallback lost');
1787
+ this.#scheduleEvaluate();
1788
+ return STALE;
1789
+ }
1726
1790
  /**
1727
1791
  * Zrzut hooka po WŁASNEJ cyfrze — kasujemy go dopiero wtedy, gdy jest ZUŻYTY.
1728
1792
  *
@@ -3130,6 +3194,8 @@ export class HerdrDriver {
3130
3194
  // Nowa blokada = nowy ekran i nowy identyfikator dialogu spoza jsonl.
3131
3195
  this.#blockedSeq += 1;
3132
3196
  this.#blockedAt = this.#scheduler.now();
3197
+ // A transcript not found yet is looked up now, and the evaluation waits for that lookup before the screen.
3198
+ this.#follower?.lookUpTranscript?.();
3133
3199
  this.#dropScreen();
3134
3200
  this.#reportBlocked();
3135
3201
  return;
@@ -3871,11 +3937,13 @@ export class HerdrDriver {
3871
3937
  * i zrzutu hooka), a WŁAŚCICIELEM stanu jest fasada — rozdzielenie tych dwóch kroków po
3872
3938
  * pięciu ścieżkach kończyłoby się kartą wysłaną bez zapamiętania (albo odwrotnie).
3873
3939
  */
3874
- #showCard(card) {
3940
+ #showCard(built) {
3941
+ this.#noHook.noteCard(built);
3942
+ // The emergency mark from the episode the detector just noted, before the channel gate reads the card.
3943
+ const card = this.#screenFallback.stamp(built);
3875
3944
  const event = consentOnlyEvent(card.event, card.active, this.#deps, this.#cliReserve.cliWaiting, {
3876
3945
  engineSessionId: this.#agentSessionId, cwd: this.#cwd,
3877
3946
  });
3878
- this.#noHook.noteCard(card);
3879
3947
  if (event.type === 'permission-request' && event.canAllow === false) {
3880
3948
  // Jedna karta na dialog: przy żywej karcie kanału zgód karta zgody bez przycisku zgody nie idzie do managera.
3881
3949
  if (this.#consentChannel.consentCardStands()) {
@@ -3888,7 +3956,8 @@ export class HerdrDriver {
3888
3956
  * (bramka „ta sama karta” nie zamraża oceny), a ocena na koniec czekania wystawia ją, jeśli karta kanału nie
3889
3957
  * przyszła.
3890
3958
  */
3891
- if (this.#consentChannel.consentCardWait()) {
3959
+ // Through the grace of a dialog without a hook trace the card waits too; the judgement orders the evaluation.
3960
+ if (this.#consentChannel.consentCardWait() || this.#screenFallback.waits(card)) {
3892
3961
  this.#undecided = null;
3893
3962
  return;
3894
3963
  }
@@ -1,6 +1,7 @@
1
1
  import { MAX_FILE_ENTRIES } from '@rarog/shared';
2
2
  import { listSessionDir } from './listing.js';
3
3
  import { FILES_DISK } from './path-rule.js';
4
+ import { isClosedFolder } from './refusals.js';
4
5
  import { filesSession } from './session-gate.js';
5
6
  export const FILE_INDEX_LIMITS = {
6
7
  maxFiles: 20_000, maxBodyBytes: 2 * 1024 * 1024, budgetMs: 3_000, maxEntries: MAX_FILE_ENTRIES,
@@ -138,8 +139,9 @@ class IndexBody {
138
139
  }
139
140
  /**
140
141
  * The walk of the session directory of `area`. A directory whose listing is refused (swapped, gone) is skipped; a
141
- * refused session directory is the answer. The budget runs from before the git read and is checked between two
142
- * directories, so the session directory is always listed.
142
+ * refused session directory is the answer, and so is a guarded folder that closes during the walk: an index cut
143
+ * there would read as complete. The budget runs from before the git read and is checked between two directories, so
144
+ * the session directory is always listed.
143
145
  */
144
146
  async function walk(area, maxBytes, run, limits, now, disk) {
145
147
  const startedAt = now();
@@ -160,7 +162,7 @@ async function walk(area, maxBytes, run, limits, now, disk) {
160
162
  const dir = queue[next];
161
163
  const listing = await listSessionDir(area, dir.rel, { maxBytes, maxEntries: limits.maxEntries }, disk);
162
164
  if (!listing.ok) {
163
- if (dir.rel === '')
165
+ if (dir.rel === '' || isClosedFolder(listing.refusal))
164
166
  return listing;
165
167
  continue;
166
168
  }
@@ -1,8 +1,9 @@
1
1
  import path from 'node:path';
2
2
  import { MAX_FILE_ENTRIES, compareFileEntries } from '@rarog/shared';
3
3
  import { insideWorkArea } from '../config/work-area.js';
4
+ import { FolderGateError } from '../folder-gate/types.js';
4
5
  import { FILES_DISK, inAreaText, isHiddenName, resolveSessionDir, stillSessionDir, } from './path-rule.js';
5
- import { NOT_FOUND } from './refusals.js';
6
+ import { NOT_FOUND, closedFolder } from './refusals.js';
6
7
  /** The name as a string when its bytes are valid UTF-8, otherwise `null`. */
7
8
  function utf8Name(bytes) {
8
9
  const name = bytes.toString('utf8');
@@ -11,13 +12,16 @@ function utf8Name(bytes) {
11
12
  /**
12
13
  * The entries of the directory, read through its identity: `[]` for a directory the server may not read (`EACCES`,
13
14
  * `EPERM`), as in the directory browser; `null` (404) when the read cannot be bound to the directory the walk found
14
- * (another platform, another directory under the path now) or fails otherwise. Never a read by path.
15
+ * (another platform, another directory under the path now) or fails otherwise; the refusal of a guarded folder the
16
+ * folder gate holds closed, never an empty listing. Never a read by path.
15
17
  */
16
18
  async function entriesOf(dir, disk) {
17
19
  try {
18
20
  return await disk.readdirByIdentity(dir);
19
21
  }
20
22
  catch (error) {
23
+ if (error instanceof FolderGateError)
24
+ return error;
21
25
  const code = error?.code;
22
26
  return code === 'EACCES' || code === 'EPERM' ? [] : null;
23
27
  }
@@ -55,6 +59,8 @@ export async function listSessionDir(area, rel, opts, disk = FILES_DISK) {
55
59
  const read = await entriesOf(dir.value, disk);
56
60
  if (read === null)
57
61
  return { ok: false, refusal: NOT_FOUND };
62
+ if (read instanceof FolderGateError)
63
+ return { ok: false, refusal: closedFolder(read) };
58
64
  const pending = [];
59
65
  for (const entry of read) {
60
66
  const name = utf8Name(entry.name);