@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
@@ -0,0 +1,89 @@
1
+ /**
2
+ * The two system reads of the consent-without-hook detector (`consent-no-hook.ts`): whether `ps` shows Rarog's hook
3
+ * as a child of the session process, and how fresh the session's `statusLine` dump is. Each read gives an answer or
4
+ * "unknown"; neither throws, and neither reads a file's content.
5
+ */
6
+ import { execFile } from 'node:child_process';
7
+ import { stat } from 'node:fs/promises';
8
+ import { STATUSLINE_FRESH_MS } from '../../herdr/hook-config.js';
9
+ import { statuslinePath } from '../../herdr/statusline.js';
10
+ /** `ps` from an absolute path (macOS and Linux), without the server's `PATH`. */
11
+ const PS_PATH = '/bin/ps';
12
+ /** Every process with its parent and its arguments, unwrapped: the hook is a direct child of the session process. */
13
+ const PS_ARGS = ['-A', '-ww', '-o', 'ppid=,args='];
14
+ /**
15
+ * Ceiling of the `ps` run; it runs once per judgement of a consent dialog without a hook trace, off the card's path. A
16
+ * registry that stops saying `waiting: permission` during the facts read gives the episode one more judgement.
17
+ */
18
+ const PS_TIMEOUT_MS = 1_000;
19
+ /** Ceiling of the `ps` output (every process of the machine). */
20
+ const PS_MAX_BUFFER = 8 * 1024 * 1024;
21
+ const runPs = (args) => new Promise((resolve) => {
22
+ execFile(PS_PATH, [...args], { timeout: PS_TIMEOUT_MS, maxBuffer: PS_MAX_BUFFER, encoding: 'utf8' }, (err, out) => {
23
+ resolve(err === null ? out : null);
24
+ });
25
+ });
26
+ /** The interpreter of the hook command, by its name or its path. */
27
+ const NODE = /(?:^|\/)node$/;
28
+ /**
29
+ * Whether the arguments of one process are the hook command: `node`, then `script` as its first argument, then the end
30
+ * or a space. `ps` joins the arguments with spaces, so with whitespace in the interpreter or in `script` the bounds of
31
+ * the arguments are not settled: `null`.
32
+ */
33
+ function hookArgs(args, script) {
34
+ const needle = ` ${script}`;
35
+ for (let at = args.indexOf(needle); at !== -1; at = args.indexOf(needle, at + 1)) {
36
+ const end = at + needle.length;
37
+ if (end < args.length && args[end] !== ' ')
38
+ continue;
39
+ const interpreter = args.slice(0, at);
40
+ if (!NODE.test(interpreter))
41
+ continue;
42
+ return /\s/.test(interpreter) || /\s/.test(script) ? null : true;
43
+ }
44
+ return false;
45
+ }
46
+ /**
47
+ * Whether a child of the process `pid` runs the hook script `script` (`node <home>/.claude/hooks/rarog/rarog-pending.mjs
48
+ * --answer-wait=…`, measured on CLI 2.1.330: a direct child of the session's `claude` process, also for a subagent's
49
+ * dialog). `null` = `ps` unavailable, its output unreadable or a child whose arguments may be the hook but whose
50
+ * argument bounds `ps` does not settle: never "no hook".
51
+ */
52
+ export async function hookChildRunning(pid, script, run = runPs) {
53
+ const out = await run(PS_ARGS).catch(() => null);
54
+ if (out === null)
55
+ return null;
56
+ let rows = 0;
57
+ let unsettled = false;
58
+ for (const line of out.split('\n')) {
59
+ const row = /^\s*(\d+)\s+(.*)$/.exec(line);
60
+ if (row === null)
61
+ continue;
62
+ rows += 1;
63
+ if (Number(row[1]) !== pid)
64
+ continue;
65
+ const hook = hookArgs(row[2] ?? '', script);
66
+ if (hook === true)
67
+ return true;
68
+ if (hook === null)
69
+ unsettled = true;
70
+ }
71
+ // A run that lists no process at all did not list this machine's processes.
72
+ return rows === 0 || unsettled ? null : false;
73
+ }
74
+ /**
75
+ * Freshness of the session's `statusLine` dump (`<root>/<session>.json`) by its modification time: `fresh` within
76
+ * {@link STATUSLINE_FRESH_MS} of `now`, `stale` older, `none` without a regular file there. It is an observation in
77
+ * the log line, not a cause: the dump refreshes on events only.
78
+ */
79
+ export async function statuslineFreshness(root, engineSessionId, now) {
80
+ try {
81
+ const file = await stat(statuslinePath(root, engineSessionId));
82
+ if (!file.isFile())
83
+ return 'none';
84
+ return now - file.mtimeMs <= STATUSLINE_FRESH_MS ? 'fresh' : 'stale';
85
+ }
86
+ catch {
87
+ return 'none';
88
+ }
89
+ }
@@ -0,0 +1,411 @@
1
+ import { consentModeNow, noApproveButtonLine, noHookCause, noHookLine, offPathApprove, subagentDialogOnScreen, } from '../../herdr/dialogs/index.js';
2
+ import { consentChannelOpen } from '../../herdr/dialogs/hook/contract.js';
3
+ /**
4
+ * The grace from the episode start: a hook trace that comes within it means the hook came. Hooks that came were measured
5
+ * 6–528 ms after the block, and the hook process stands in `ps` 26–154 ms after the CLI registry enters `waiting`
6
+ * (CLI 2.1.330).
7
+ */
8
+ export const NO_HOOK_GRACE_MS = 3_000;
9
+ /**
10
+ * Evaluations per episode, the first one included. An evaluation reads the session facts and runs `ps`; one that ends
11
+ * without channel mode or the `permission` class goes again at the next registry signal, and a registry that flaps
12
+ * between no answer and `waiting: permission` during the reads would otherwise cost one facts read and one `ps` per
13
+ * flap. Past the budget the episode stays judged and gets no line.
14
+ */
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;
22
+ /** Reads of the session facts per episode: a read that ends on another process or `cwd` gives none and goes again. */
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;
31
+ /** Card identities remembered for the `no approve button` line; past the cap the memory starts again. */
32
+ const BUTTONLESS_MAX = 256;
33
+ let episodes = 0;
34
+ /** The call the card stands for: the jsonl entry or the hook call key; `undefined` = a card from the screen alone. */
35
+ const callIdOf = (card) => card.active.origin?.toolUseId ?? card.active.callId ?? card.active.origin?.callKey;
36
+ /**
37
+ * Whether the card shows the dialog of the episode: a card swap within one dialog (a degraded or screen card replaced
38
+ * by the jsonl card) keeps the episode, while another call or another dialog block starts a new one.
39
+ */
40
+ function sameDialog(episode, card) {
41
+ const callId = callIdOf(card);
42
+ if (episode.callId !== undefined && callId !== undefined && episode.callId !== callId)
43
+ return false;
44
+ const print = card.active.bodyPrint;
45
+ return episode.print === undefined || print === undefined || episode.print === print;
46
+ }
47
+ export class ConsentNoHook {
48
+ #deps;
49
+ #scheduler;
50
+ #inScope;
51
+ #cwd;
52
+ #port;
53
+ #episode = null;
54
+ /** End of the last episode, epoch; `0` before the first one (registrations of this process only). */
55
+ #since = 0;
56
+ /** Card identities that already have their `no approve button` line. */
57
+ #buttonless = new Set();
58
+ /** Within {@link handover}: the block changes hands, it does not end. */
59
+ #handingOver = false;
60
+ constructor(config, port) {
61
+ this.#deps = config.deps;
62
+ this.#scheduler = config.scheduler;
63
+ this.#inScope = config.inScope;
64
+ this.#cwd = config.cwd;
65
+ this.#port = port;
66
+ }
67
+ /**
68
+ * A card for the standing dialog, before the channel gate decides whether it goes out (`#showCard`). The same dialog
69
+ * keeps its episode; a new dialog closes the old one and opens its own that starts at the block start, or at this card
70
+ * when an earlier episode of the same block ended. The grace timer then orders the judgement.
71
+ */
72
+ noteCard(card) {
73
+ this.#observe(() => { this.#noteCard(card); });
74
+ }
75
+ #noteCard(card) {
76
+ if (this.#deps.consentNoHook === undefined || !this.#inScope || this.#port.disposed())
77
+ return;
78
+ const sessionId = this.#port.agentSessionId();
79
+ if (sessionId === '')
80
+ return;
81
+ const current = this.#episode;
82
+ if (current !== null && this.#stands(current) && sameDialog(current, card)) {
83
+ this.#describe(current, card);
84
+ return;
85
+ }
86
+ const now = this.#scheduler.now();
87
+ const sameBlock = current !== null && current.blockSeq === this.#port.blockedSeq();
88
+ // The previous dialog ended at Rarog's key after it opened, otherwise now, when another dialog replaced it; an
89
+ // episode the block end already ended keeps that moment.
90
+ const answeredAt = this.#port.answeredAt();
91
+ if (current !== null)
92
+ this.#end(current, answeredAt > current.openedAt ? Math.min(now, answeredAt) : now);
93
+ episodes += 1;
94
+ const t0 = sameBlock ? now : Math.min(now, this.#port.blockedAt());
95
+ const episode = {
96
+ id: `no-hook:${String(episodes)}`, sessionId, blockSeq: this.#port.blockedSeq(), t0, openedAt: now,
97
+ since: this.#since, callId: undefined, print: undefined, tool: card.active.toolName, screenButton: false,
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,
100
+ };
101
+ this.#describe(episode, card);
102
+ this.#episode = episode;
103
+ episode.timer = this.#scheduler.setTimeout(() => {
104
+ episode.timer = null;
105
+ if (episode.state === 'grace')
106
+ episode.state = 'due';
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
+ }
116
+ }, Math.max(0, t0 + NO_HOOK_GRACE_MS - now));
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
+ }
135
+ /**
136
+ * A card that goes out: when the channel gate took its approve button (the `off` path card would have it), one
137
+ * `consent: no approve button` line per card identity.
138
+ */
139
+ cardShown(card, event) {
140
+ this.#observe(() => { this.#cardShown(card, event); });
141
+ }
142
+ #cardShown(card, event) {
143
+ if (event.type !== 'permission-request' || event.canAllow !== false || !offPathApprove(card.event))
144
+ return;
145
+ const reqId = card.active.reqId;
146
+ if (this.#buttonless.has(reqId))
147
+ return;
148
+ if (this.#buttonless.size >= BUTTONLESS_MAX)
149
+ this.#buttonless.clear();
150
+ this.#buttonless.add(reqId);
151
+ const sessionId = this.#port.agentSessionId();
152
+ const rules = this.#proofRules(sessionId);
153
+ const thread = this.#threadOf(card);
154
+ this.#log(noApproveButtonLine({
155
+ sessionId, reason: event.unavailable ?? null, tool: card.active.toolName, channel: consentModeNow(this.#deps),
156
+ rule: rules === null ? null : rules[thread === 'main' ? 'main' : 'subagents'], cli: this.#port.cliVersion(),
157
+ }));
158
+ }
159
+ /**
160
+ * A registry signal came. `closed` (the registry says `active`) after the registry said `waiting: permission` within
161
+ * the episode is a desk decision, which ends it; an `active` before that is a read from before the dialog. Otherwise
162
+ * an episode past its grace that waited for the `permission` class is judged now.
163
+ */
164
+ registrySignal(closed = false) {
165
+ this.#observe(() => { this.#registrySignal(closed); });
166
+ }
167
+ #registrySignal(closed) {
168
+ const episode = this.#episode;
169
+ if (episode === null || episode.state === 'ended')
170
+ return;
171
+ if (closed && episode.waiting) {
172
+ this.#end(episode, this.#scheduler.now());
173
+ return;
174
+ }
175
+ if (this.#port.cliWaiting() === 'permission')
176
+ episode.waiting = true;
177
+ if (episode.state === 'due')
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); });
200
+ }
201
+ /**
202
+ * `drop` hands the effective block over within one block (herdr's own `blocked` follows the CLI registry
203
+ * hold): a block end signalled while the block is between its two holders does not end the episode, which keeps its
204
+ * start and its grace timer.
205
+ */
206
+ handover(drop) {
207
+ this.#handingOver = true;
208
+ try {
209
+ drop();
210
+ }
211
+ finally {
212
+ this.#handingOver = false;
213
+ }
214
+ }
215
+ /** The effective block ended: the dialog is gone or answered at the desk, so its episode ends. */
216
+ blockEnded() {
217
+ if (this.#handingOver)
218
+ return;
219
+ this.#observe(() => {
220
+ const episode = this.#episode;
221
+ if (episode !== null && episode.state !== 'ended')
222
+ this.#end(episode, this.#scheduler.now());
223
+ });
224
+ }
225
+ dispose() {
226
+ const episode = this.#episode;
227
+ this.#episode = null;
228
+ this.#observe(() => {
229
+ if (episode?.timer !== null && episode?.timer !== undefined)
230
+ this.#scheduler.clearTimeout(episode.timer);
231
+ });
232
+ }
233
+ /**
234
+ * One step of the detector, called from the card, the poll, the registry signal and the grace timer. The detector
235
+ * only observes, so its failure never reaches them: the episode may lose its line, the card and the block go on.
236
+ * The evaluation past the grace that reads the facts goes on after the step returned; its failure takes the same
237
+ * `#failed` line.
238
+ */
239
+ #observe(step) {
240
+ try {
241
+ step();
242
+ }
243
+ catch (err) {
244
+ this.#failed(err);
245
+ }
246
+ }
247
+ /** The line of a detector failure, by the error's name only. */
248
+ #failed(err) {
249
+ try {
250
+ this.#deps.logger?.(`consent: no hook detector failed (${err instanceof Error ? err.name : typeof err})`);
251
+ }
252
+ catch {
253
+ // The logger itself failed: nothing more to tell.
254
+ }
255
+ }
256
+ /** The card's tool, the `off` path button and the thread, from the latest card of the episode. */
257
+ #describe(episode, card) {
258
+ episode.callId ??= callIdOf(card);
259
+ episode.print ??= card.active.bodyPrint;
260
+ episode.tool = card.active.toolName;
261
+ episode.screenButton = offPathApprove(card.event);
262
+ episode.thread = this.#threadOf(card);
263
+ }
264
+ /** Whether the episode still stands: same session and block, no own key since it opened, not ended. */
265
+ #stands(episode) {
266
+ return episode.state !== 'ended' && !this.#port.disposed() && this.#port.agentSessionId() === episode.sessionId
267
+ && this.#port.blockedNow() && this.#port.blockedSeq() === episode.blockSeq
268
+ && this.#port.answeredAt() <= episode.openedAt;
269
+ }
270
+ /** Ends the episode at `at` (scheduler clock): the next episode's registration window starts there. */
271
+ #end(episode, at) {
272
+ if (episode.timer !== null)
273
+ this.#scheduler.clearTimeout(episode.timer);
274
+ episode.timer = null;
275
+ if (episode.state === 'ended')
276
+ return;
277
+ episode.state = 'ended';
278
+ this.#since = Math.max(this.#since, this.#epochOf(at));
279
+ }
280
+ /** A scheduler time as epoch ms: the scheduler and the epoch clock differ in tests. */
281
+ #epochOf(at) {
282
+ return this.#deps.now() - (this.#scheduler.now() - at);
283
+ }
284
+ /**
285
+ * The judgement past the grace: only in channel mode, for the `permission` class from the registry and without a hook trace.
286
+ * Without the class yet it waits for the next registry signal.
287
+ */
288
+ #judge(episode) {
289
+ const sources = this.#deps.consentNoHook;
290
+ if (sources === undefined || this.#episode !== episode || episode.state !== 'due')
291
+ return;
292
+ if (!this.#stands(episode)) {
293
+ this.#end(episode, this.#scheduler.now());
294
+ return;
295
+ }
296
+ if (!consentChannelOpen(consentModeNow(this.#deps)) || this.#port.cliWaiting() !== 'permission')
297
+ return;
298
+ episode.state = 'judged';
299
+ if (this.#traced(sources, episode))
300
+ return;
301
+ episode.evaluations += 1;
302
+ void this.#judgeFacts(sources, episode, true).catch((err) => { this.#failed(err); });
303
+ }
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) {
322
+ let facts = null;
323
+ for (let read = 0; read < FACTS_READS && facts === null; read += 1) {
324
+ facts = await sources.facts({ sessionId: episode.sessionId, episode: episode.id }).catch(() => null);
325
+ }
326
+ const pid = facts?.process?.pid;
327
+ const [hookRunning, statusline] = await Promise.all([
328
+ pid === undefined ? null : sources.hookRunning(pid).catch(() => null),
329
+ sources.statusline(episode.sessionId).catch(() => 'none'),
330
+ ]);
331
+ // The reads take time: a trace or an end (a desk decision included) that came meanwhile wins over the line, and
332
+ // without channel mode or the `permission` class now the judgement waits for the next registry signal again, while
333
+ // the episode has evaluations left.
334
+ if (this.#episode !== episode || !this.#stands(episode) || this.#traced(sources, episode))
335
+ return;
336
+ if (!consentChannelOpen(consentModeNow(this.#deps)) || this.#port.cliWaiting() !== 'permission') {
337
+ if (first && episode.evaluations < NO_HOOK_EVALUATIONS)
338
+ episode.state = 'due';
339
+ return;
340
+ }
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;
351
+ this.#log(noHookLine({
352
+ sessionId: episode.sessionId,
353
+ cause,
354
+ tool: episode.tool, cli: this.#port.cliVersion(), mode: this.#port.permissionMode(), thread: episode.thread,
355
+ afterMs: this.#scheduler.now() - episode.t0, hooks: facts?.verdict ?? null, statusline,
356
+ screenButton: episode.screenButton,
357
+ }));
358
+ }
359
+ /** A trace of the hook since the previous episode; a source that throws or cannot read counts as one. */
360
+ #traced(sources, episode) {
361
+ try {
362
+ return sources.hookTrace(episode.sessionId, episode.since) !== false;
363
+ }
364
+ catch {
365
+ return true;
366
+ }
367
+ }
368
+ /** The session `cwd` from the registry outside the work area; the pane's own `cwd` is in scope already. */
369
+ #outsideWorkArea(sources, cwd) {
370
+ if (cwd === null)
371
+ return null;
372
+ if (cwd === this.#cwd)
373
+ return false;
374
+ try {
375
+ return sources.outsideWorkArea(cwd);
376
+ }
377
+ catch {
378
+ return null;
379
+ }
380
+ }
381
+ #threadOf(card) {
382
+ if (card.active.origin?.agentId !== undefined)
383
+ return 'subagent';
384
+ const screen = this.#port.screenText();
385
+ return screen !== null && subagentDialogOnScreen(screen) ? 'subagent' : 'main';
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
+ }
396
+ #proofRules(sessionId) {
397
+ try {
398
+ return this.#deps.consentNoHook?.proofRules(sessionId) ?? null;
399
+ }
400
+ catch {
401
+ return null;
402
+ }
403
+ }
404
+ #log(line) {
405
+ this.#deps.logger?.(line);
406
+ }
407
+ /** Tells the port that the judgement changed; its failure stays here. */
408
+ #judged() {
409
+ this.#observe(() => { this.#port.judged?.(); });
410
+ }
411
+ }