hivecode-mcp 0.12.1 → 0.12.4

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.
package/hive-stop-hook.js CHANGED
@@ -1,241 +1,290 @@
1
- #!/usr/bin/env node
2
- /**
3
- * THE ANTI-IDLE GATE.
4
- *
5
- * A rule an agent is told to follow is advice. This is the same rule as a lock.
6
- *
7
- * THE PROBLEM. hive_wait exists so an agent never goes unreachable: block until someone needs
8
- * you, do the work, block again. It is in the tool description and it is now in the system
9
- * prompt (hive-instructions.js). Both are still instructions, and an agent that decides it is
10
- * finished simply emits a final answer instead of another tool call. Its process is alive, its
11
- * socket is up, and it is deaf. Everyone waiting on it waits forever, and nothing tells them.
12
- *
13
- * You cannot fix that with better wording, for the same reason a claim board that only warns
14
- * does not stop a write: it is enforcement or it is a suggestion.
15
- *
16
- * WHAT THIS IS. A Claude Code `Stop` hook. Claude Code runs it when the main agent is about to
17
- * end its turn. Returning {"decision":"block","reason":...} makes Claude Code refuse to stop and
18
- * feed `reason` back as the next input. The agent does not get a vote. So an agent that tries to
19
- * go idle while it has unread mail or unfinished accepted work is simply not allowed to.
20
- *
21
- * WHY IT READS DISK AND NOT THE RELAY. This runs on every turn boundary and has a hard timeout.
22
- * A network round trip inside that budget would make the hook the least reliable thing in the
23
- * session. It does not need one: the sync client already mirrors the room to HIVE_CHAT.md and
24
- * HIVE_TASKS.md on local disk. Reading those is microseconds, works with the relay unreachable,
25
- * and cannot itself desync the room because it only ever reads.
26
- *
27
- * IT BLOCKS ON THREE THINGS, and the middle one is the subtle one:
28
- *
29
- * - unread mail addressed to you
30
- * - a question you DID read and never answered ("read" is not "answered": the cursor advances
31
- * the moment a message is handed over, so an agent can absorb a direct question mid-work and
32
- * end its turn having left someone hanging, with nothing unread to block on)
33
- * - an accepted task still open
34
- *
35
- * FOUR GUARDS AGAINST TRAPPING THE AGENT IN A LOOP. A hook that blocks forever is worse than
36
- * no hook -- it burns the user's tokens and they cannot get their agent back:
37
- *
38
- * 1. stop_hook_active. Claude Code sets this when the stop it is asking about is ALREADY the
39
- * result of a previous block. We always allow then, so a block is never immediately
40
- * re-applied on top of itself.
41
- * 2. The watermark advances even when we block. A given message can cause exactly one block,
42
- * ever. If the agent ignores it, that is the human's problem to see, not ours to enforce.
43
- * 3. `nudged` -- the same one-block-per-message rule extended across BOTH reasons, so a
44
- * message cannot charge once as unread mail and again as an unanswered question. Keyed on
45
- * sender+timestamp, so a genuinely new question still gets its own single nudge.
46
- * 4. MAX_TASK_BLOCKS. Unlike a message, an open task stays open, so it would re-block on every
47
- * turn until completed -- including when it CANNOT be completed. After a few consecutive
48
- * task-only blocks we stand down and let the agent stop.
49
- *
50
- * Any failure at all -- no session, unreadable file, malformed JSON, unexpected shape -- exits 0
51
- * and allows the stop. The hook may make an agent more reliable; it must never make a session
52
- * unusable.
53
- *
54
- * Install with: npx hivecode-hook install
55
- */
56
- import fs from 'fs'
57
- import path from 'path'
58
- import { mentionsName, unansweredFor } from './hive-mailbox.js'
59
-
60
- // Consecutive turns we will block purely because a task is still open, before standing down.
61
- // Messages are not subject to this: the watermark already makes each one block at most once.
62
- const MAX_TASK_BLOCKS = 3
63
-
64
- const SESSION_FILE = '.hive-mcp-session.json' // written by hive-mcp.js on join
65
- const STATE_FILE = '.hive-stop-hook.json' // ours: watermark, task blocks, questions already nudged
66
-
67
- // A chat line: "- 19:07:27 Eve (ai): text". Anything else is a continuation of the message
68
- // above it (messages may contain newlines) or a header comment.
69
- const CHAT_LINE = /^- (\d{2}:\d{2}:\d{2})\s+(.+?) \((human|ai|system)\): ([\s\S]*)$/
70
- // A task line: "- [accepted] tmtofacav4mf Ganesh -> PM: do the thing (by Ganesh)"
71
- const TASK_LINE = /^- \[(\w+)\]\s+(\S+)\s+(.+?) -> (.+?): ([\s\S]*)$/
72
-
73
- const readJson = (p) => { try { return JSON.parse(fs.readFileSync(p, 'utf8')) } catch { return null } }
74
-
75
- /** Fold continuation lines into their message so a multi-line post counts once. */
76
- export function parseChat(src) {
77
- const out = []
78
- for (const line of String(src || '').split(/\r?\n/)) {
79
- const m = CHAT_LINE.exec(line)
80
- if (m) out.push({ at: m[1], by: m[2], kind: m[3], text: m[4] })
81
- else if (out.length && line.trim() && !line.startsWith('#')) out[out.length - 1].text += '\n' + line
82
- }
83
- return out
84
- }
85
-
86
- /** Accepted tasks pointed at `me` that nobody has marked done. */
87
- export function openTasksFor(src, me) {
88
- const out = []
89
- for (const line of String(src || '').split(/\r?\n/)) {
90
- const m = TASK_LINE.exec(line)
91
- // `done` and `completed` both appear in the wild depending on how the task was closed;
92
- // anything that is not explicitly accepted-and-open is not work we should block on.
93
- if (m && m[1] === 'accepted' && m[4].trim().toLowerCase() === String(me).toLowerCase()) {
94
- out.push({ id: m[2], from: m[3], text: m[5] })
95
- }
96
- }
97
- return out
98
- }
99
-
100
- /**
101
- * The whole decision, as a pure function of what is on disk, so the test can drive it without a
102
- * Claude Code session, a relay, or a room.
103
- *
104
- * Returns { block: boolean, reason?: string, seen: number, taskBlocks: number }.
105
- */
106
- export function decide({ chat, tasks, me, seen, taskBlocks, nudged = [] }) {
107
- const msgs = parseChat(chat)
108
- const nowSeen = msgs.length
109
- // A cursor past the end means this is a different (rebuilt or switched) room -- start over
110
- // rather than treating the whole history as unread and blocking on all of it.
111
- const from = seen > nowSeen ? 0 : seen
112
- const fresh = msgs.slice(from)
113
-
114
- const mail = fresh.filter((m) =>
115
- m.kind !== 'system' &&
116
- String(m.by).toLowerCase() !== String(me).toLowerCase() && // never block on our own post
117
- mentionsName(m.text, me))
118
-
119
- if (mail.length) {
120
- const quoted = mail.slice(0, 5).map((m) => ` ${m.by}: ${m.text.replace(/\s+/g, ' ').slice(0, 220)}`)
121
- const more = mail.length > 5 ? `\n ... and ${mail.length - 5} more` : ''
122
- return {
123
- block: true, seen: nowSeen, taskBlocks: 0,
124
- // Blocking here also spends this message's ONE nudge, so the debt branch below cannot
125
- // charge for the same message a second time. One block per message, whatever the reason.
126
- nudged: [...nudged, ...mail.map((m) => m.by + '|' + m.at)].slice(-200),
127
- reason: `You are in a Hivecode room and ${mail.length} message${mail.length > 1 ? 's' : ''} ` +
128
- `addressed to you arrived while you were working:\n\n${quoted.join('\n')}${more}\n\n` +
129
- `Do not stop -- they are waiting on a reply from you. Answer with hive_say (put @Name on ` +
130
- `it), then go back to hive_wait. hive_wait is your idle state; ending your turn makes you ` +
131
- `unreachable and nobody in the room finds out.`,
132
- }
133
- }
134
-
135
- // A DEBT IS NOT THE SAME AS UNREAD MAIL, and this is the gap the watermark alone leaves. The
136
- // cursor advances the instant a message is handed over, so an agent can read a direct
137
- // question, get absorbed in the work, and end its turn having left someone hanging -- with
138
- // nothing unread and nothing to block on. The person waiting has no way to find that out.
139
- //
140
- // ONE NUDGE PER QUESTION, EVER -- the same rule mail already follows, and it has to be the
141
- // same rule. A debt survives until it is answered, so anything weaker than remembering which
142
- // ones we already raised means the identical question blocks turn after turn, and a gate that
143
- // nags is a gate the user switches off. Keyed on sender+timestamp rather than on sender, so a
144
- // NEW question from someone we have already nudged about still gets its own one nudge.
145
- const owed = unansweredFor(msgs, me)
146
- const unnudged = owed.filter((o) => !nudged.includes(o.from + '|' + o.at))
147
- if (unnudged.length) {
148
- const quoted = unnudged.slice(0, 3).map((o) => ` ${o.from}: ${o.text.replace(/\s+/g, ' ').slice(0, 200)}`)
149
- return {
150
- block: true, seen: nowSeen, taskBlocks,
151
- // Recorded BEFORE returning, exactly as the watermark is, so a question cannot block a
152
- // second time even if whatever happens next goes wrong. Capped so the state file cannot
153
- // grow without bound in a long-lived room.
154
- nudged: [...nudged, ...unnudged.map((o) => o.from + '|' + o.at)].slice(-200),
155
- reason: `You are in a Hivecode room and ${unnudged.length} participant${unnudged.length > 1 ? 's are' : ' is'} ` +
156
- `still waiting on a reply from you:\n\n${quoted.join('\n')}\n\n` +
157
- `Answer with hive_say and name them. "Not yet — I am on X, I will come back to you" is a ` +
158
- `complete answer; silence is the one thing they cannot act on, and nothing tells them you ` +
159
- `stopped. Then call hive_wait.`,
160
- }
161
- }
162
-
163
- const open = openTasksFor(tasks, me)
164
- if (open.length && taskBlocks < MAX_TASK_BLOCKS) {
165
- const quoted = open.slice(0, 3).map((t) => ` [${t.id}] from ${t.from}: ${t.text.replace(/\s+/g, ' ').slice(0, 220)}`)
166
- return {
167
- block: true, seen: nowSeen, taskBlocks: taskBlocks + 1, nudged,
168
- reason: `You are in a Hivecode room with ${open.length} accepted task${open.length > 1 ? 's' : ''} ` +
169
- `still open:\n\n${quoted.join('\n')}\n\n` +
170
- `Finish the work and call hive_complete with the task id, or say why you are blocked with ` +
171
- `hive_say (@ the person who assigned it). Then call hive_wait. If you genuinely cannot ` +
172
- `proceed, say so in the room first -- do not just stop, nobody would learn that you had.`,
173
- }
174
- }
175
-
176
- // Standing down on something we have already blocked on MAX_TASK_BLOCKS times is not the same
177
- // as it being resolved, so hold the counter rather than resetting it while it is still there.
178
- // Debts and tasks share the counter deliberately: they are the same kind of obligation, and
179
- // two separate counters would let an agent be pinned for 2x MAX_TASK_BLOCKS turns.
180
- return { block: false, seen: nowSeen, taskBlocks: open.length ? taskBlocks : 0, nudged }
181
- }
182
-
183
- /** Walk up from `start` looking for the session file; the hook's cwd is usually but not always
184
- * the folder the MCP server was launched in. */
185
- function findSession(start) {
186
- let dir = path.resolve(start)
187
- for (let i = 0; i < 4; i++) {
188
- const p = path.join(dir, SESSION_FILE)
189
- if (fs.existsSync(p)) return { root: dir, session: readJson(p) }
190
- const up = path.dirname(dir)
191
- if (up === dir) break
192
- dir = up
193
- }
194
- return null
195
- }
196
-
197
- async function main() {
198
- let input = ''
199
- for await (const chunk of process.stdin) input += chunk
200
- const hook = (() => { try { return JSON.parse(input) } catch { return {} } })()
201
-
202
- // GUARD 1: this stop is already the product of a block. Never stack another on it.
203
- if (hook.stop_hook_active) return
204
-
205
- const found = findSession(hook.cwd || process.cwd())
206
- if (!found || !found.session || !found.session.dir || !found.session.name) return // not in a room
207
-
208
- const { root, session } = found
209
- const dir = path.isAbsolute(session.dir) ? session.dir : path.join(root, session.dir)
210
- const read = (f) => { try { return fs.readFileSync(path.join(dir, f), 'utf8') } catch { return '' } }
211
-
212
- const chat = read('HIVE_CHAT.md')
213
- if (!chat) return // room folder not mirrored yet; nothing to be sure about, so allow
214
-
215
- const statePath = path.join(root, STATE_FILE)
216
- const prev = readJson(statePath) || {}
217
- // Keyed by room: a folder rejoined against a different room must not inherit a watermark from
218
- // unrelated history -- the same reasoning as the persisted sync ancestor being room-keyed.
219
- const key = String(session.room || session.dir)
220
- const st = prev[key] || { seen: 0, taskBlocks: 0, nudged: [] }
221
-
222
- const d = decide({
223
- chat, tasks: read('HIVE_TASKS.md'), me: session.name,
224
- seen: Number(st.seen) || 0, taskBlocks: Number(st.taskBlocks) || 0,
225
- nudged: Array.isArray(st.nudged) ? st.nudged : [],
226
- })
227
-
228
- // GUARD 2: write the watermark BEFORE returning the block, so this message can never block a
229
- // second time even if what happens next goes wrong.
230
- try {
231
- prev[key] = { seen: d.seen, taskBlocks: d.taskBlocks, nudged: d.nudged || [], at: Date.now() }
232
- fs.writeFileSync(statePath, JSON.stringify(prev, null, 2))
233
- } catch { /* a watermark we cannot persist is a reason to allow, never to fail */ }
234
-
235
- if (d.block) process.stdout.write(JSON.stringify({ decision: 'block', reason: d.reason }))
236
- }
237
-
238
- // Only run when executed as the hook, so the test can import decide()/parseChat() cleanly.
239
- if (process.argv[1] && /hive-stop-hook\.js$/.test(process.argv[1])) {
240
- main().catch(() => { }).finally(() => process.exit(0))
241
- }
1
+ #!/usr/bin/env node
2
+ /**
3
+ * THE ANTI-IDLE GATE.
4
+ *
5
+ * A rule an agent is told to follow is advice. This is the same rule as a lock.
6
+ *
7
+ * THE PROBLEM. hive_wait exists so an agent never goes unreachable: block until someone needs
8
+ * you, do the work, block again. It is in the tool description and it is now in the system
9
+ * prompt (hive-instructions.js). Both are still instructions, and an agent that decides it is
10
+ * finished simply emits a final answer instead of another tool call. Its process is alive, its
11
+ * socket is up, and it is deaf. Everyone waiting on it waits forever, and nothing tells them.
12
+ *
13
+ * You cannot fix that with better wording, for the same reason a claim board that only warns
14
+ * does not stop a write: it is enforcement or it is a suggestion.
15
+ *
16
+ * WHAT THIS IS. A Claude Code `Stop` hook. Claude Code runs it when the main agent is about to
17
+ * end its turn. Returning {"decision":"block","reason":...} makes Claude Code refuse to stop and
18
+ * feed `reason` back as the next input. The agent does not get a vote. So an agent that tries to
19
+ * go idle while it has unread mail or unfinished accepted work is simply not allowed to.
20
+ *
21
+ * WHY IT READS DISK AND NOT THE RELAY. This runs on every turn boundary and has a hard timeout.
22
+ * A network round trip inside that budget would make the hook the least reliable thing in the
23
+ * session. It does not need one: the sync client already mirrors the room to HIVE_CHAT.md and
24
+ * HIVE_TASKS.md on local disk. Reading those is microseconds, works with the relay unreachable,
25
+ * and cannot itself desync the room because it only ever reads.
26
+ *
27
+ * IT BLOCKS ON THREE THINGS, and the middle one is the subtle one:
28
+ *
29
+ * - unread mail addressed to you
30
+ * - a question you DID read and never answered ("read" is not "answered": the cursor advances
31
+ * the moment a message is handed over, so an agent can absorb a direct question mid-work and
32
+ * end its turn having left someone hanging, with nothing unread to block on)
33
+ * - an accepted task still open
34
+ *
35
+ * FOUR GUARDS AGAINST TRAPPING THE AGENT IN A LOOP. A hook that blocks forever is worse than
36
+ * no hook -- it burns the user's tokens and they cannot get their agent back:
37
+ *
38
+ * 1. stop_hook_active. Claude Code sets this when the stop it is asking about is ALREADY the
39
+ * result of a previous block. We always allow then, so a block is never immediately
40
+ * re-applied on top of itself.
41
+ * 2. The watermark advances even when we block. A given message can cause exactly one block,
42
+ * ever. If the agent ignores it, that is the human's problem to see, not ours to enforce.
43
+ * 3. `nudged` -- the same one-block-per-message rule extended across BOTH reasons, so a
44
+ * message cannot charge once as unread mail and again as an unanswered question. Keyed on
45
+ * sender+timestamp, so a genuinely new question still gets its own single nudge.
46
+ * 4. MAX_TASK_BLOCKS. Unlike a message, an open task stays open, so it would re-block on every
47
+ * turn until completed -- including when it CANNOT be completed. After a few consecutive
48
+ * task-only blocks we stand down and let the agent stop.
49
+ *
50
+ * Any failure at all -- no session, unreadable file, malformed JSON, unexpected shape -- exits 0
51
+ * and allows the stop. The hook may make an agent more reliable; it must never make a session
52
+ * unusable.
53
+ *
54
+ * Install with: npx -y -p hivecode-mcp@latest hivecode-hook install
55
+ */
56
+ import fs from 'fs'
57
+ import path from 'path'
58
+ import { mentionsName, unansweredFor } from './hive-mailbox.js'
59
+ import { isArmed, listenCommand, listenHow, listenOrder } from './hive-listen.js'
60
+
61
+ // Consecutive turns we will block purely because a task is still open, before standing down.
62
+ // Messages are not subject to this: the watermark already makes each one block at most once.
63
+ const MAX_TASK_BLOCKS = 3
64
+
65
+ const SESSION_FILE = '.hive-mcp-session.json' // written by hive-mcp.js on join
66
+ const STATE_FILE = '.hive-stop-hook.json' // ours: watermark, task blocks, questions already nudged
67
+
68
+ // A chat line: "- 19:07:27 Eve (ai): text". Anything else is a continuation of the message
69
+ // above it (messages may contain newlines) or a header comment.
70
+ const CHAT_LINE = /^- (\d{2}:\d{2}:\d{2})\s+(.+?) \((human|ai|system)\): ([\s\S]*)$/
71
+ // A task line: "- [accepted] tmtofacav4mf Ganesh -> PM: do the thing (by Ganesh)"
72
+ const TASK_LINE = /^- \[(\w+)\]\s+(\S+)\s+(.+?) -> (.+?): ([\s\S]*)$/
73
+
74
+ const readJson = (p) => { try { return JSON.parse(fs.readFileSync(p, 'utf8')) } catch { return null } }
75
+
76
+ /** Fold continuation lines into their message so a multi-line post counts once. */
77
+ export function parseChat(src) {
78
+ const out = []
79
+ for (const line of String(src || '').split(/\r?\n/)) {
80
+ const m = CHAT_LINE.exec(line)
81
+ if (m) out.push({ at: m[1], by: m[2], kind: m[3], text: m[4] })
82
+ else if (out.length && line.trim() && !line.startsWith('#')) out[out.length - 1].text += '\n' + line
83
+ }
84
+ return out
85
+ }
86
+
87
+ /** Accepted tasks pointed at `me` that nobody has marked done. */
88
+ export function openTasksFor(src, me) {
89
+ const out = []
90
+ for (const line of String(src || '').split(/\r?\n/)) {
91
+ const m = TASK_LINE.exec(line)
92
+ // `done` and `completed` both appear in the wild depending on how the task was closed;
93
+ // anything that is not explicitly accepted-and-open is not work we should block on.
94
+ if (m && m[1] === 'accepted' && m[4].trim().toLowerCase() === String(me).toLowerCase()) {
95
+ out.push({ id: m[2], from: m[3], text: m[5] })
96
+ }
97
+ }
98
+ return out
99
+ }
100
+
101
+ // A TURN THAT ENDS WITH NO LISTENER RUNNING IS A DEAF AGENT NOBODY KNOWS IS DEAF (4 Oct 2026). The
102
+ // order to start one was said once, on the first quiet hive_wait, and an agent had to remember it
103
+ // after every wake; agents forget. So this gate also asks "is a listener running for you?"
104
+ // (hive-listen.js) before the turn ends. It rides on the SAME block as any mail -- one block per
105
+ // stop, never a second -- because a stop that was already blocked once is let through
106
+ // (stop_hook_active), and a listener order queued behind a mail block would never be said. An
107
+ // agent that ignores it MAX_LISTEN_BLOCKS turns running is let go: it cannot or will not, and a gate
108
+ // that nags is a gate the user switches off. Seeing a listener running resets the count.
109
+ const MAX_LISTEN_BLOCKS = 3
110
+
111
+ /**
112
+ * The whole decision, as a pure function of what is on disk, so the test can drive it without a
113
+ * Claude Code session, a relay, or a room.
114
+ *
115
+ * `listening`: true (a listener is running), false (none, and one can be started), or null (not
116
+ * applicable: no link on disk, a room that checks tokens, an app that is not woken by a background
117
+ * task). `listenLine`: the order to give when it is false.
118
+ *
119
+ * Returns { block: boolean, reason?: string, seen: number, taskBlocks: number, listenBlocks: number }.
120
+ */
121
+ export function decide(o) {
122
+ const d = obligations(o)
123
+ const { listening = null, listenLine = '' } = o
124
+ const listenBlocks = Number(o.listenBlocks) || 0
125
+ if (listening !== false || !listenLine) return { ...d, listenBlocks: listening ? 0 : listenBlocks }
126
+ if (listenBlocks >= MAX_LISTEN_BLOCKS) return { ...d, listenBlocks }
127
+ return { ...d, block: true, reason: d.block ? `${d.reason}\n\n${listenLine}` : listenLine, listenBlocks: listenBlocks + 1 }
128
+ }
129
+
130
+ function obligations({ chat, tasks, me, seen, taskBlocks, nudged = [] }) {
131
+ const msgs = parseChat(chat)
132
+ const nowSeen = msgs.length
133
+ // A cursor past the end means this is a different (rebuilt or switched) room -- start over
134
+ // rather than treating the whole history as unread and blocking on all of it.
135
+ const from = seen > nowSeen ? 0 : seen
136
+ const fresh = msgs.slice(from)
137
+
138
+ const mail = fresh.filter((m) =>
139
+ m.kind !== 'system' &&
140
+ String(m.by).toLowerCase() !== String(me).toLowerCase() && // never block on our own post
141
+ mentionsName(m.text, me))
142
+
143
+ if (mail.length) {
144
+ const quoted = mail.slice(0, 5).map((m) => ` ${m.by}: ${m.text.replace(/\s+/g, ' ').slice(0, 220)}`)
145
+ const more = mail.length > 5 ? `\n ... and ${mail.length - 5} more` : ''
146
+ return {
147
+ block: true, seen: nowSeen, taskBlocks: 0,
148
+ // Blocking here also spends this message's ONE nudge, so the debt branch below cannot
149
+ // charge for the same message a second time. One block per message, whatever the reason.
150
+ nudged: [...nudged, ...mail.map((m) => m.by + '|' + m.at)].slice(-200),
151
+ reason: `You are in a Hivecode room and ${mail.length} message${mail.length > 1 ? 's' : ''} ` +
152
+ `addressed to you arrived while you were working:\n\n${quoted.join('\n')}${more}\n\n` +
153
+ `Do not stop -- they are waiting on a reply from you. Answer with hive_say (put @Name on ` +
154
+ `it), then go back to hive_wait. hive_wait is your idle state; ending your turn makes you ` +
155
+ `unreachable and nobody in the room finds out.`,
156
+ }
157
+ }
158
+
159
+ // A DEBT IS NOT THE SAME AS UNREAD MAIL, and this is the gap the watermark alone leaves. The
160
+ // cursor advances the instant a message is handed over, so an agent can read a direct
161
+ // question, get absorbed in the work, and end its turn having left someone hanging -- with
162
+ // nothing unread and nothing to block on. The person waiting has no way to find that out.
163
+ //
164
+ // ONE NUDGE PER QUESTION, EVER -- the same rule mail already follows, and it has to be the
165
+ // same rule. A debt survives until it is answered, so anything weaker than remembering which
166
+ // ones we already raised means the identical question blocks turn after turn, and a gate that
167
+ // nags is a gate the user switches off. Keyed on sender+timestamp rather than on sender, so a
168
+ // NEW question from someone we have already nudged about still gets its own one nudge.
169
+ const owed = unansweredFor(msgs, me)
170
+ const unnudged = owed.filter((o) => !nudged.includes(o.from + '|' + o.at))
171
+ if (unnudged.length) {
172
+ const quoted = unnudged.slice(0, 3).map((o) => ` ${o.from}: ${o.text.replace(/\s+/g, ' ').slice(0, 200)}`)
173
+ return {
174
+ block: true, seen: nowSeen, taskBlocks,
175
+ // Recorded BEFORE returning, exactly as the watermark is, so a question cannot block a
176
+ // second time even if whatever happens next goes wrong. Capped so the state file cannot
177
+ // grow without bound in a long-lived room.
178
+ nudged: [...nudged, ...unnudged.map((o) => o.from + '|' + o.at)].slice(-200),
179
+ reason: `You are in a Hivecode room and ${unnudged.length} participant${unnudged.length > 1 ? 's are' : ' is'} ` +
180
+ `still waiting on a reply from you:\n\n${quoted.join('\n')}\n\n` +
181
+ `Answer with hive_say and name them. "Not yet — I am on X, I will come back to you" is a ` +
182
+ `complete answer; silence is the one thing they cannot act on, and nothing tells them you ` +
183
+ `stopped. Then call hive_wait.`,
184
+ }
185
+ }
186
+
187
+ const open = openTasksFor(tasks, me)
188
+ if (open.length && taskBlocks < MAX_TASK_BLOCKS) {
189
+ const quoted = open.slice(0, 3).map((t) => ` [${t.id}] from ${t.from}: ${t.text.replace(/\s+/g, ' ').slice(0, 220)}`)
190
+ return {
191
+ block: true, seen: nowSeen, taskBlocks: taskBlocks + 1, nudged,
192
+ reason: `You are in a Hivecode room with ${open.length} accepted task${open.length > 1 ? 's' : ''} ` +
193
+ `still open:\n\n${quoted.join('\n')}\n\n` +
194
+ `Finish the work and call hive_complete with the task id, or say why you are blocked with ` +
195
+ `hive_say (@ the person who assigned it). Then call hive_wait. If you genuinely cannot ` +
196
+ `proceed, say so in the room first -- do not just stop, nobody would learn that you had.`,
197
+ }
198
+ }
199
+
200
+ // Standing down on something we have already blocked on MAX_TASK_BLOCKS times is not the same
201
+ // as it being resolved, so hold the counter rather than resetting it while it is still there.
202
+ // Debts and tasks share the counter deliberately: they are the same kind of obligation, and
203
+ // two separate counters would let an agent be pinned for 2x MAX_TASK_BLOCKS turns.
204
+ return { block: false, seen: nowSeen, taskBlocks: open.length ? taskBlocks : 0, nudged }
205
+ }
206
+
207
+ /** Walk up from `start` looking for the session file; the hook's cwd is usually but not always
208
+ * the folder the MCP server was launched in. */
209
+ function findSession(start) {
210
+ let dir = path.resolve(start)
211
+ for (let i = 0; i < 4; i++) {
212
+ const p = path.join(dir, SESSION_FILE)
213
+ if (fs.existsSync(p)) return { root: dir, session: readJson(p) }
214
+ const up = path.dirname(dir)
215
+ if (up === dir) break
216
+ dir = up
217
+ }
218
+ return null
219
+ }
220
+
221
+ const APP = (/--app=(\S+)/.exec(process.argv.slice(2).join(' ')) || [])[1] || 'claude-code'
222
+
223
+ async function main() {
224
+ const allow = () => { if (APP === 'antigravity') process.stdout.write(JSON.stringify({ decision: 'stop' })) }
225
+ try {
226
+ let input = ''
227
+ for await (const chunk of process.stdin) input += chunk
228
+ const hook = (() => { try { return JSON.parse(input) } catch { return {} } })()
229
+
230
+ // GUARD 1: this stop is already the product of a block. Never stack another on it.
231
+ if (hook.stop_hook_active || Number(hook.executionNum) > 0) return allow()
232
+
233
+ const found = findSession(hook.cwd || (Array.isArray(hook.workspacePaths) && hook.workspacePaths[0]) || process.cwd())
234
+ if (!found || !found.session || !found.session.dir || !found.session.name) return allow() // not in a room
235
+
236
+ const { root, session } = found
237
+ // A passive participant never answers and the room waits on nobody passive: it owes no reply,
238
+ // no task, and no listener, so there is nothing to hold its turn open for.
239
+ if (session.passive) return allow()
240
+ const dir = path.isAbsolute(session.dir) ? session.dir : path.join(root, session.dir)
241
+ const read = (f) => { try { return fs.readFileSync(path.join(dir, f), 'utf8') } catch { return '' } }
242
+
243
+ const chat = read('HIVE_CHAT.md')
244
+ if (!chat) return allow() // room folder not mirrored yet; nothing to be sure about, so allow
245
+
246
+ const statePath = path.join(root, STATE_FILE)
247
+ const prev = readJson(statePath) || {}
248
+ // Keyed by room: a folder rejoined against a different room must not inherit a watermark from
249
+ // unrelated history -- the same reasoning as the persisted sync ancestor being room-keyed.
250
+ const key = String(session.room || session.dir)
251
+ const st = prev[key] || { seen: 0, taskBlocks: 0, nudged: [] }
252
+
253
+ // Is a listener running for this agent? Asked only where the agent could start one: an app that
254
+ // is woken when a background task ends, the room's link on disk, and a room that does not check
255
+ // tokens (the agent's shell does not hold the MCP server's token, so a listener could not join).
256
+ const cfg = readJson(path.join(dir, '.hive.json')) || {}
257
+ const how = listenHow(APP)
258
+ let listening = null, listenLine = ''
259
+ if (how && cfg.relay && cfg.room && !session.authed && !cfg.token) {
260
+ listening = isArmed({ name: session.name, room: cfg.room, session: String(hook.session_id || hook.conversationId || process.env.ANTIGRAVITY_CONVERSATION_ID || '') })
261
+ listenLine = listenOrder(how, listenCommand({ relay: cfg.relay, room: cfg.room, name: session.name }))
262
+ }
263
+
264
+ const d = decide({
265
+ chat, tasks: read('HIVE_TASKS.md'), me: session.name,
266
+ seen: Number(st.seen) || 0, taskBlocks: Number(st.taskBlocks) || 0,
267
+ nudged: Array.isArray(st.nudged) ? st.nudged : [],
268
+ listening, listenLine, listenBlocks: Number(st.listenBlocks) || 0,
269
+ })
270
+
271
+ // GUARD 2: write the watermark BEFORE returning the block, so this message can never block a
272
+ // second time even if what happens next goes wrong.
273
+ try {
274
+ prev[key] = { seen: d.seen, taskBlocks: d.taskBlocks, nudged: d.nudged || [], listenBlocks: d.listenBlocks, at: Date.now() }
275
+ fs.writeFileSync(statePath, JSON.stringify(prev, null, 2))
276
+ } catch { /* a watermark we cannot persist is a reason to allow, never to fail */ }
277
+
278
+ // Antigravity's Stop hook blocks with "continue" (its engine's own schema: stop | continue |
279
+ // block); Claude Code's with "block". Which app runs this is said in its hook entry (--app).
280
+ if (d.block) process.stdout.write(JSON.stringify({ decision: APP === 'antigravity' ? 'continue' : 'block', reason: d.reason }))
281
+ else allow()
282
+ } catch {
283
+ allow()
284
+ }
285
+ }
286
+
287
+ // Only run when executed as the hook, so the test can import decide()/parseChat() cleanly.
288
+ if (process.argv[1] && /hive-stop-hook\.js$/.test(process.argv[1])) {
289
+ main().catch(() => { }).finally(() => process.exit(0))
290
+ }