@nodii/dev 0.6.174 → 0.6.176
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/README.md +404 -20
- package/dist/accounts.js +62 -1
- package/dist/cli.js +255 -85
- package/dist/coordinator-items.js +235 -0
- package/dist/core.js +13 -2
- package/dist/flags.js +15 -2
- package/dist/freeze.js +35 -2
- package/dist/gather.js +14 -3
- package/dist/harness.js +2 -0
- package/dist/hook-handlers.js +127 -0
- package/dist/hooks.js +22 -6
- package/dist/issue-group.js +63 -0
- package/dist/lane-asks.js +115 -0
- package/dist/lane-messages.js +313 -0
- package/dist/lane-runtime.js +7 -1
- package/dist/lane-supervisor.js +366 -23
- package/dist/lane-switches.js +32 -0
- package/dist/lanes.js +105 -17
- package/dist/leeway.js +218 -0
- package/dist/managed-hooks.js +58 -6
- package/dist/nudges.js +55 -21
- package/dist/repo-policy.js +13 -1
- package/dist/resume-gate.js +150 -0
- package/dist/runtime-launcher.js +64 -4
- package/dist/safety.js +69 -6
- package/dist/session-kind.js +18 -5
- package/dist/setup.js +8 -5
- package/dist/starting.js +114 -21
- package/dist/tooling-docs.js +127 -0
- package/package.json +1 -1
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import { access, readFile, rm } from "node:fs/promises";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { devRequest, query } from "./core.js";
|
|
5
|
+
import { laneAsksOn } from "./lane-asks.js";
|
|
6
|
+
import { cachedGet, laneReadCache } from "./read-cache.js";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* hub-525 (MW1-37.2): the coordinator clears lane items first.
|
|
10
|
+
* Lanes ask questions and ask for leeway; Dev counts what waits on a machine's
|
|
11
|
+
* coordinator and says so in a response header on every answer to that
|
|
12
|
+
* coordinator. The CLI prints one line for it before each command's output,
|
|
13
|
+
* `coordinator items` lists the items, and the coordinator gate (a PreToolUse
|
|
14
|
+
* hook in the managed dispatcher) holds the coordinator's next nodii-dev write
|
|
15
|
+
* while an ask or a leeway has waited over 10 minutes.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
export const LANE_ITEMS_HEADER = "x-dev-lane-items";
|
|
19
|
+
const ITEMS_PATH = "/api/v1/coordinator/items";
|
|
20
|
+
// Asks and leeways gate after this long; waits and escalations never do.
|
|
21
|
+
export const GATE_AFTER_SECONDS = 10 * 60;
|
|
22
|
+
const GATE_CACHE_TTL_MS = 10_000;
|
|
23
|
+
const LINE_CACHE_KEY = "coordinator-items-line";
|
|
24
|
+
const LINE_CACHE_TTL_MS = 5 * 60_000;
|
|
25
|
+
const DETAIL_TIMEOUT_MS = 3_000;
|
|
26
|
+
const GATE_TIMEOUT_MS = 5_000;
|
|
27
|
+
|
|
28
|
+
// kind, singular, plural: in the order the line names them.
|
|
29
|
+
const KINDS = [["leeway", "leeway", "leeways"], ["ask", "question", "questions"], ["wait", "wait", "waits"], ["escalation", "escalation", "escalations"]];
|
|
30
|
+
|
|
31
|
+
/** `total=3;leeway=1;ask=2;wait=0;escalation=0;oldest=2040` as numbers, or null when there is nothing to say. */
|
|
32
|
+
export function parseLaneItemsHeader(value, env = process.env) {
|
|
33
|
+
if (typeof value !== "string" || !value.trim()) return null;
|
|
34
|
+
const fields = Object.fromEntries(value.split(";").map((part) => part.split("=").map((piece) => piece.trim())).filter(([name, number]) => name && /^\d+$/.test(number ?? "")).map(([name, number]) => [name, Number(number)]));
|
|
35
|
+
if (!Number.isInteger(fields.total) || fields.total <= 0) return null;
|
|
36
|
+
// Lane asks off (MW1-37.2): they are not counted, and questions alone are nothing to say.
|
|
37
|
+
const ask = laneAsksOn(env) ? (fields.ask ?? 0) : 0;
|
|
38
|
+
const total = fields.total - ((fields.ask ?? 0) - ask);
|
|
39
|
+
if (total <= 0) return null;
|
|
40
|
+
return { total, leeway: fields.leeway ?? 0, ask, wait: fields.wait ?? 0, escalation: fields.escalation ?? 0, oldest: fields.oldest ?? 0 };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const age = (seconds) => {
|
|
44
|
+
const minutes = Math.max(0, Math.floor(Number(seconds ?? 0) / 60));
|
|
45
|
+
return minutes >= 120 ? `${Math.round(minutes / 60)} h` : `${minutes} min`;
|
|
46
|
+
};
|
|
47
|
+
const deferred = (item, now) => Boolean(item?.deferredUntil) && Date.parse(item.deferredUntil) > now;
|
|
48
|
+
|
|
49
|
+
/** The one line a coordinator's command prints first. With no detail it is the counts alone. */
|
|
50
|
+
export function laneItemsLine(counts, items, { elapsedSeconds = 0, now = Date.now() } = {}) {
|
|
51
|
+
const parts = KINDS.filter(([kind]) => counts[kind] > 0).map(([kind, one, many]) => {
|
|
52
|
+
const open = (Array.isArray(items) ? items : []).filter((item) => item?.kind === kind && item.laneKey && !deferred(item, now));
|
|
53
|
+
const names = open.slice(0, 5).map((item) => (kind === "ask" ? `${item.laneKey} ${age(Number(item.ageSeconds ?? 0) + elapsedSeconds)}` : item.laneKey));
|
|
54
|
+
const more = open.length > 5 ? `, +${open.length - 5} more` : "";
|
|
55
|
+
return `${counts[kind]} ${counts[kind] === 1 ? one : many}${names.length ? ` (${names.join(", ")}${more})` : ""}`;
|
|
56
|
+
});
|
|
57
|
+
return `${counts.total} from lanes waiting on you${parts.length ? `: ${parts.join(", ")}` : ""} · nodii-dev coordinator items`;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// ─── The count line ─────────────────────────────────────────────────────────
|
|
61
|
+
|
|
62
|
+
let current = null;
|
|
63
|
+
let refreshing = false;
|
|
64
|
+
let printed = false;
|
|
65
|
+
|
|
66
|
+
/** A new command starts with nothing seen and nothing printed. */
|
|
67
|
+
export function resetLaneItemsNotice() {
|
|
68
|
+
current = null;
|
|
69
|
+
printed = false;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Called with each Dev response's header. The names in the line come from the
|
|
74
|
+
* cached `/coordinator/items` detail, read again when the header's total
|
|
75
|
+
* changes (or the cache is five minutes old); a failed read leaves the counts.
|
|
76
|
+
* Never throws.
|
|
77
|
+
*/
|
|
78
|
+
export async function observeLaneItems(header, { request = devRequest, cache = laneReadCache({ ttlMs: LINE_CACHE_TTL_MS }), now = Date.now } = {}) {
|
|
79
|
+
// The detail read's own answer carries the header too.
|
|
80
|
+
if (refreshing) return;
|
|
81
|
+
try {
|
|
82
|
+
const counts = parseLaneItemsHeader(header);
|
|
83
|
+
if (!counts) { current = null; return; }
|
|
84
|
+
let detail = await cache.get(LINE_CACHE_KEY);
|
|
85
|
+
if (!detail || detail.total !== counts.total) {
|
|
86
|
+
refreshing = true;
|
|
87
|
+
try {
|
|
88
|
+
const data = (await request("GET", ITEMS_PATH, undefined, { signal: AbortSignal.timeout(DETAIL_TIMEOUT_MS) })).data;
|
|
89
|
+
detail = { total: counts.total, at: now(), items: data?.items ?? [] };
|
|
90
|
+
await cache.set(LINE_CACHE_KEY, detail);
|
|
91
|
+
} catch {
|
|
92
|
+
detail = null;
|
|
93
|
+
} finally {
|
|
94
|
+
refreshing = false;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
current = laneItemsLine(counts, detail?.items ?? null, { elapsedSeconds: detail ? Math.max(0, Math.round((now() - detail.at) / 1000)) : 0, now: now() });
|
|
98
|
+
} catch {
|
|
99
|
+
current = null;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The line to print before this command's output, once; null when there is none. */
|
|
104
|
+
export function takeLaneItemsLine() {
|
|
105
|
+
if (!current || printed) return null;
|
|
106
|
+
printed = true;
|
|
107
|
+
return current;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// ─── coordinator items ──────────────────────────────────────────────────────
|
|
111
|
+
|
|
112
|
+
/** `nodii-dev coordinator items [--machine NAME|ID]`: what lanes wait on, each with the command that clears it. */
|
|
113
|
+
export async function coordinatorItemsCommand(flags, { request = devRequest, now = Date.now, env = process.env } = {}) {
|
|
114
|
+
const payload = await request("GET", `${ITEMS_PATH}${query({ machine: typeof flags.machine === "string" ? flags.machine : undefined })}`);
|
|
115
|
+
const data = payload.data ?? {};
|
|
116
|
+
// Lane asks off (MW1-37.2): none is listed or counted.
|
|
117
|
+
const asksOn = laneAsksOn(env);
|
|
118
|
+
const asksOff = asksOn ? "" : "Lane questions are off (NODII_DEV_LANE_ASKS): none is listed or counted.";
|
|
119
|
+
const items = (data.items ?? []).filter((item) => asksOn || item?.kind !== "ask");
|
|
120
|
+
const counts = data.counts ?? {};
|
|
121
|
+
const total = Math.max(0, Number(data.total ?? 0) - (asksOn ? 0 : Number(counts.ask ?? 0)));
|
|
122
|
+
if (!total && !items.length) return { payload, human: ["Nothing from lanes is waiting on you.", asksOff].filter(Boolean).join(" ") };
|
|
123
|
+
const count = (kind, one, many) => `${counts[kind] ?? 0} ${(counts[kind] ?? 0) === 1 ? one : many}`;
|
|
124
|
+
const lines = [`${total} from lanes waiting on you (oldest ${age(data.oldestSeconds)}): ${asksOn ? `${count("ask", "question", "questions")}, ` : ""}${count("leeway", "leeway", "leeways")}, ${count("wait", "wait", "waits")}, ${count("escalation", "escalation", "escalations")}.`];
|
|
125
|
+
for (const item of items) {
|
|
126
|
+
const note = deferred(item, now()) || item.deferredUntil ? ` (deferred until ${item.deferredUntil})` : item.gates ? "" : " (counted, never gates)";
|
|
127
|
+
lines.push(`${item.kind}\t${item.laneKey}\t${age(item.ageSeconds)}\t${String(item.summary ?? "").replace(/\s+/g, " ").trim()}${note}`);
|
|
128
|
+
if (item.command) lines.push(` ${item.command}`);
|
|
129
|
+
}
|
|
130
|
+
lines.push(
|
|
131
|
+
asksOn
|
|
132
|
+
? `Asks and leeways older than ${GATE_AFTER_SECONDS / 60} minutes hold your next nodii-dev write: answer, grant, refuse, or defer with a reason (nodii-dev lane defer <id> --reason TEXT [--minutes N]).`
|
|
133
|
+
: `Leeways older than ${GATE_AFTER_SECONDS / 60} minutes hold your next nodii-dev write: grant, refuse, or defer with a reason (nodii-dev lane defer <id> --reason TEXT [--minutes N]). ${asksOff}`,
|
|
134
|
+
);
|
|
135
|
+
return { payload, human: lines.join("\n") };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// ─── The coordinator gate ───────────────────────────────────────────────────
|
|
139
|
+
|
|
140
|
+
/** `coordinator start` writes this beside the config; the dispatcher checks it so only a coordinator session pays for the gate. */
|
|
141
|
+
export const coordinatorMarkerPath = (env = process.env) => join(dirname(env.NODII_DEV_CONFIG_PATH ?? join(homedir(), ".config/nodii-dev/config.json")), "coordinator.json");
|
|
142
|
+
|
|
143
|
+
const markerExists = async (env) => {
|
|
144
|
+
try { await access(coordinatorMarkerPath(env)); return true; } catch { return false; }
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
/** Remove the marker when it names this run (the coordinator session ended). */
|
|
148
|
+
export async function clearCoordinatorMarker(runId, { env = process.env } = {}) {
|
|
149
|
+
try {
|
|
150
|
+
const path = coordinatorMarkerPath(env);
|
|
151
|
+
if (JSON.parse(await readFile(path, "utf8"))?.runId === runId) await rm(path, { force: true });
|
|
152
|
+
} catch {}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// Commands that never write lane or issue state in Dev, or that a coordinator must always be able to run.
|
|
156
|
+
const NEVER_GATED = new Set(["hook", "heavy", "run", "help", "doctor", "whoami", "config", "login", "logout", "rulebook", "rules", "inbox", "coordinator", "harness", "setup", "watchdog", "test", "repo", "state", "heartbeat", "next", "gather", "chrome", "receipt", "sync"]);
|
|
157
|
+
const READ_ACTIONS = new Set(["list", "show", "get", "diff", "versions", "status", "find", "parked", "audit", "usage", "accounts", "entries", "check", "board", "watch", "history", "timings", "behind", "resolve", "methodology", "lane-state", "overrides", "reviews", "waits", "asks"]);
|
|
158
|
+
// The lane actions that clear an item, close out a lane or bring one back.
|
|
159
|
+
const LANE_ALLOWED = new Set(["answer", "defer", "resume", "close", "stop", "closeout"]);
|
|
160
|
+
// Lane actions with a subcommand: which of them write.
|
|
161
|
+
const LANE_SUB_WRITES = {
|
|
162
|
+
leeway: (sub) => !["grant", "refuse", "show", "list"].includes(sub),
|
|
163
|
+
amendments: (sub) => ["approve", "reject", "withdraw"].includes(sub),
|
|
164
|
+
freeze: (sub) => ["add", "drop", "swap"].includes(sub),
|
|
165
|
+
authority: (sub) => sub === "record",
|
|
166
|
+
};
|
|
167
|
+
const SUB_VERBS = new Set(["withdraw", "approve", "reject", "add", "drop", "swap", "record"]);
|
|
168
|
+
const INVOCATION = /(?:nodii-dev(?:\.js)?|@nodii\/dev(?:@[\w.-]+)?)["']?((?:\s+--?[\w-]+(?:=\S+)?)*)\s+([a-z][\w-]*)([^;&|\n]*)/g;
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* The nodii-dev write a Bash command makes, as "lane launch", or null. Reads,
|
|
172
|
+
* local commands and the commands that clear lane items are never writes here.
|
|
173
|
+
*/
|
|
174
|
+
export function gatedCommand(command) {
|
|
175
|
+
for (const [, , name, rest] of String(command ?? "").matchAll(INVOCATION)) {
|
|
176
|
+
if (NEVER_GATED.has(name)) continue;
|
|
177
|
+
const tokens = rest.trim().split(/\s+/).filter(Boolean);
|
|
178
|
+
if (tokens.some((token) => token === "--help" || token === "-h")) continue;
|
|
179
|
+
// The action is the first word; a flag's value is never one of ours, since flags follow the action.
|
|
180
|
+
const action = tokens[0] && !tokens[0].startsWith("-") ? tokens[0] : undefined;
|
|
181
|
+
const third = action && tokens[1] && !tokens[1].startsWith("-") ? tokens[1] : undefined;
|
|
182
|
+
if (!action) continue;
|
|
183
|
+
if (name === "lane") {
|
|
184
|
+
if (LANE_ALLOWED.has(action) || READ_ACTIONS.has(action)) continue;
|
|
185
|
+
if (LANE_SUB_WRITES[action]) {
|
|
186
|
+
if (!LANE_SUB_WRITES[action](third)) continue;
|
|
187
|
+
return `lane ${action}${SUB_VERBS.has(third) ? ` ${third}` : ""}`;
|
|
188
|
+
}
|
|
189
|
+
return `lane ${action}`;
|
|
190
|
+
}
|
|
191
|
+
if (READ_ACTIONS.has(action)) continue;
|
|
192
|
+
return `${name} ${action}`;
|
|
193
|
+
}
|
|
194
|
+
return null;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* PreToolUse on Bash and AskUserQuestion, for a coordinator session. Denies a
|
|
199
|
+
* nodii-dev write while an ask or a leeway has waited over 10 minutes
|
|
200
|
+
* undeferred, naming each with the command that clears it. A question to the
|
|
201
|
+
* operator is never denied (MW1-116: an override or a lock change is asked the
|
|
202
|
+
* moment it arises): it passes with the same items named as context. Fails
|
|
203
|
+
* open: when Dev cannot be read the call passes with a note.
|
|
204
|
+
* Returns { deny }, { context } or null.
|
|
205
|
+
*/
|
|
206
|
+
export async function coordinatorGate(payload, deps = {}) {
|
|
207
|
+
const tool = payload?.tool_name;
|
|
208
|
+
const what = tool === "AskUserQuestion" ? "asking the operator" : tool === "Bash" ? gatedCommand(payload?.tool_input?.command) : null;
|
|
209
|
+
if (!what) return null;
|
|
210
|
+
const env = deps.env ?? process.env;
|
|
211
|
+
if (!(await (deps.coordinatorMarker ?? markerExists)(env))) return null;
|
|
212
|
+
const now = (deps.now ?? Date.now)();
|
|
213
|
+
let items;
|
|
214
|
+
try {
|
|
215
|
+
const request = deps.request ?? devRequest;
|
|
216
|
+
const cache = "cache" in deps ? deps.cache : laneReadCache({ ttlMs: GATE_CACHE_TTL_MS });
|
|
217
|
+
const read = (method, path) => request(method, path, undefined, { signal: AbortSignal.timeout(GATE_TIMEOUT_MS) });
|
|
218
|
+
items = (await cachedGet(cache, read, ITEMS_PATH)).data?.items ?? [];
|
|
219
|
+
} catch {
|
|
220
|
+
return { context: "lane items unread: Dev unreachable" };
|
|
221
|
+
}
|
|
222
|
+
// Lane asks off (MW1-37.2): a question never holds the coordinator, since it could not clear one.
|
|
223
|
+
const asksOn = laneAsksOn(env);
|
|
224
|
+
const overdue = items.filter((item) => item?.gates === true && (asksOn || item.kind !== "ask") && Number(item.ageSeconds) > GATE_AFTER_SECONDS && !deferred(item, now));
|
|
225
|
+
if (!overdue.length) return null;
|
|
226
|
+
const lines = [
|
|
227
|
+
...overdue.flatMap((item) => [` ${item.kind} ${item.laneKey} (${age(item.ageSeconds)}): ${String(item.summary ?? "").replace(/\s+/g, " ").trim()}`, ...(item.command ? [` ${item.command}`] : [])]),
|
|
228
|
+
"Defer one with a reason: nodii-dev lane defer <id> --reason TEXT [--minutes N]. List them: nodii-dev coordinator items.",
|
|
229
|
+
];
|
|
230
|
+
const waited = `${overdue.length} lane item${overdue.length === 1 ? " has" : "s have"} waited over ${GATE_AFTER_SECONDS / 60} minutes.`;
|
|
231
|
+
// MW1-116: the operator question goes through; the coordinator is told what still waits.
|
|
232
|
+
if (tool === "AskUserQuestion")
|
|
233
|
+
return { context: [`nodii-dev coordinator gate (MW1-37.2): ${waited} Your question to the operator is not held (MW1-116); ${asksOn ? "answer, " : ""}grant, refuse or defer each right after it:`, ...lines].join("\n") };
|
|
234
|
+
return { deny: [`nodii-dev coordinator gate (MW1-37.2): ${waited} ${asksOn ? "Answer, grant" : "Grant"}, refuse or defer each before \`${what}\`:`, ...lines].join("\n") };
|
|
235
|
+
}
|
package/dist/core.js
CHANGED
|
@@ -4,7 +4,7 @@ import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
|
4
4
|
import { homedir, platform } from "node:os";
|
|
5
5
|
import { dirname, join } from "node:path";
|
|
6
6
|
|
|
7
|
-
export const VERSION = "0.6.
|
|
7
|
+
export const VERSION = "0.6.176";
|
|
8
8
|
export const configPath = () =>
|
|
9
9
|
process.env.NODII_DEV_CONFIG_PATH ??
|
|
10
10
|
join(homedir(), ".config/nodii-dev/config.json");
|
|
@@ -339,9 +339,20 @@ async function devFetch(method, path, bodyText, contentType, accept, extra = {},
|
|
|
339
339
|
return send(grant);
|
|
340
340
|
}
|
|
341
341
|
|
|
342
|
+
// MW1-37.2: Dev names the lane items waiting on a machine's coordinator in a
|
|
343
|
+
// response header. The CLI's entry point registers who reads it; it never
|
|
344
|
+
// fails a request.
|
|
345
|
+
let laneItemsObserver = null;
|
|
346
|
+
export function setLaneItemsObserver(observer) {
|
|
347
|
+
laneItemsObserver = observer;
|
|
348
|
+
}
|
|
349
|
+
|
|
342
350
|
/** A JSON call that keeps the status: `{ status, payload }`. Errors throw as devRawRequest's do. */
|
|
343
351
|
export async function devExchange(method, path, bodyText, { contentType = "application/json", headers = {}, signal } = {}) {
|
|
344
352
|
const { response, raw } = await devFetch(method, path, bodyText, contentType, "application/json", headers, signal);
|
|
353
|
+
if (laneItemsObserver) {
|
|
354
|
+
try { await laneItemsObserver(response.headers?.get?.("x-dev-lane-items") ?? null); } catch {}
|
|
355
|
+
}
|
|
345
356
|
let payload;
|
|
346
357
|
try {
|
|
347
358
|
payload = raw ? JSON.parse(raw) : {};
|
|
@@ -394,7 +405,7 @@ export async function checkLogin() {
|
|
|
394
405
|
export const encode = (value) => encodeURIComponent(value);
|
|
395
406
|
// Switches never take the next token as their value, so
|
|
396
407
|
// `docs upload --wait rulebook/` keeps rulebook/ as a path.
|
|
397
|
-
const SWITCHES = new Set(["confirm-raise", "actionable", "json", "wait", "pending", "dry-run", "check", "all", "fleet", "help", "yes", "mine", "no-browser", "include-drafts", "drafted", "library", "async", "sync", "force", "system", "delta", "probe", "no-probe", "not-required", "override", "critical", "no-embed", "behind", "write", "fetch"]);
|
|
408
|
+
const SWITCHES = new Set(["all-pending", "confirm-raise", "actionable", "json", "wait", "pending", "dry-run", "check", "all", "fleet", "help", "yes", "mine", "no-browser", "include-drafts", "drafted", "library", "async", "sync", "force", "system", "delta", "probe", "no-probe", "not-required", "override", "critical", "no-embed", "behind", "write", "fetch", "if-changed"]);
|
|
398
409
|
export function parseArgs(argv) {
|
|
399
410
|
const flags = {};
|
|
400
411
|
const args = [];
|
package/dist/flags.js
CHANGED
|
@@ -15,12 +15,21 @@ const WAIT = ["wait", "wait-minutes"];
|
|
|
15
15
|
export const COMMAND_FLAGS = {
|
|
16
16
|
"figma transfer": ["to", "reason"],
|
|
17
17
|
"coordinator start": ["machine", "account", "heartbeat-seconds"],
|
|
18
|
+
"coordinator items": ["machine"],
|
|
19
|
+
"lane ask": ["question", "options"],
|
|
20
|
+
"lane asks": ["machine", "state", "lane", "cursor", "limit"],
|
|
21
|
+
"lane answer": ["text"],
|
|
22
|
+
// NODII-DEV-CLI-191: lane-to-lane messaging.
|
|
23
|
+
"lane message": [...BODY, "issue"],
|
|
24
|
+
"lane inbox": ["all"],
|
|
25
|
+
"lane defer": ["reason", "minutes", "leeway"],
|
|
18
26
|
"coordinator heartbeat": ["machine", "run", "pid", "pid-started-at", "interval"],
|
|
19
27
|
"issues create": ["service", ...ISSUE_FIELDS],
|
|
20
28
|
"issues update": ISSUE_FIELDS,
|
|
21
29
|
"issues transition": ["to", "reason", "dev-check"],
|
|
22
30
|
"issues comment": BODY,
|
|
23
31
|
"issues claim": ["ttl"],
|
|
32
|
+
"issues group": ["objective", "service", "min", "max"],
|
|
24
33
|
"issues release": ["note"],
|
|
25
34
|
"lane launch": [
|
|
26
35
|
"machine", "coordinator-run", "machine-id", "repo", "branch", "base", "worktree", "owned-path",
|
|
@@ -29,7 +38,7 @@ export const COMMAND_FLAGS = {
|
|
|
29
38
|
],
|
|
30
39
|
"lane amend": ["objective", "scope", "rules", "reason"],
|
|
31
40
|
"lane fold": ["versions", "summary", "reason"],
|
|
32
|
-
"lane amendments": ["all", "state", "note"],
|
|
41
|
+
"lane amendments": ["all", "state", "note", "all-pending"],
|
|
33
42
|
"lane authority": ["kind", "quote", "at", "to-agent"],
|
|
34
43
|
"lane start": ["key", "issue", "title", "kind", "side", "repo", "branch", "worktree", "step-limit"],
|
|
35
44
|
"lane step": ["side", "start", "done", "block", "not-applicable", "reason", "reason-code", "note", "review", "delta"],
|
|
@@ -38,16 +47,19 @@ export const COMMAND_FLAGS = {
|
|
|
38
47
|
"receipt verify": ["commit"],
|
|
39
48
|
"sync pending": ["discard", "reason"],
|
|
40
49
|
"lane done-check": ["evidence"],
|
|
50
|
+
"lane finish": ["reason", "evidence"],
|
|
41
51
|
"lane ready": ["withdraw", "reason"],
|
|
42
52
|
"lane cap": ["confirm-raise", "reason"],
|
|
43
53
|
"lane heartbeat": ["note", "waiting-on"],
|
|
44
54
|
"lane waits": ["machine"],
|
|
45
|
-
"lane resume": ["override", "reason", "host-lost", "min-free-gb", "stagger-seconds", "profile", "class"],
|
|
55
|
+
"lane resume": ["override", "reason", "host-lost", "min-free-gb", "stagger-seconds", "profile", "class", "if-changed"],
|
|
46
56
|
"lane transfer": ["reason", "to-agent"],
|
|
47
57
|
"inbox ack": ["note"],
|
|
48
58
|
"lane stop": ["reason", "sweeper", "no-closeout", "no-closeout-push", "launched-in-error", "replaced-by"],
|
|
49
59
|
"lane closeout": ["reason"],
|
|
50
60
|
"lane repo": ["repo", "branch", "worktree", "read-only", "reason"],
|
|
61
|
+
// MW1-12.6: ask (--blocker, --repo, --reason), grant (--note, --source, --worktree), refuse (--note), list (--machine, --state, --lane, --cursor, --limit).
|
|
62
|
+
"lane leeway": ["blocker", "repo", "reason", "note", "source", "worktree", "machine", "state", "lane", "cursor", "limit"],
|
|
51
63
|
// hub-232: the honest close-out and the governor.
|
|
52
64
|
"lane close": ["delivered-by", "reason", "sweeper", "no-closeout"],
|
|
53
65
|
"governor show": ["machine-id"],
|
|
@@ -58,6 +70,7 @@ export const COMMAND_FLAGS = {
|
|
|
58
70
|
"repo policy": ["root"],
|
|
59
71
|
"test affected": ["base", "max-light", "run"],
|
|
60
72
|
"repo lint": ["root"],
|
|
73
|
+
"repo docs-check": ["root", "base"],
|
|
61
74
|
"lane review": ["file", "not-required", "decision", "question", "quote", "at", "treat", "ruling"],
|
|
62
75
|
"lane non-issue": ["reason", "reroute", "evidence", "commits", "branch"],
|
|
63
76
|
"drift file": ["service", "severity", "summary", ...BODY, "related-artifact-type", "related-artifact-id"],
|
package/dist/freeze.js
CHANGED
|
@@ -108,12 +108,42 @@ function checkedGatherClauses(clauses) {
|
|
|
108
108
|
|
|
109
109
|
export const GATHER_LOOKUP_IDS = ["figma-guidelines"];
|
|
110
110
|
|
|
111
|
+
// NODII-DEV-CLI-191: a Dev before hub d14dbbde caps a Freeze's issue body at
|
|
112
|
+
// 20,000 characters and each lane note at 4,000, though its Lane contract
|
|
113
|
+
// carries longer ones. Dev stores the body only as its first-sentence gist
|
|
114
|
+
// (AGENT-HARNESS-45), so sending the body cut to the cap loses nothing it
|
|
115
|
+
// stores; a long note goes as consecutive notes, split between words.
|
|
116
|
+
export const FREEZE_ISSUE_BODY_SEND_MAX = 20_000;
|
|
117
|
+
export const FREEZE_LANE_NOTE_SEND_MAX = 4_000;
|
|
118
|
+
|
|
119
|
+
function issueWithinCap(issue) {
|
|
120
|
+
if (!issue?.body || issue.body.length <= FREEZE_ISSUE_BODY_SEND_MAX) return issue;
|
|
121
|
+
return { ...issue, body: issue.body.slice(0, FREEZE_ISSUE_BODY_SEND_MAX).trimEnd() };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function notesWithinCap(notes) {
|
|
125
|
+
return notes.flatMap((note) => {
|
|
126
|
+
if (typeof note !== "string" || note.length <= FREEZE_LANE_NOTE_SEND_MAX) return [note];
|
|
127
|
+
const parts = [];
|
|
128
|
+
let rest = note;
|
|
129
|
+
while (rest.length > FREEZE_LANE_NOTE_SEND_MAX) {
|
|
130
|
+
const space = rest.lastIndexOf(" ", FREEZE_LANE_NOTE_SEND_MAX);
|
|
131
|
+
const cut = space > 0 ? space : FREEZE_LANE_NOTE_SEND_MAX;
|
|
132
|
+
parts.push(rest.slice(0, cut));
|
|
133
|
+
rest = rest.slice(space > 0 ? cut + 1 : cut);
|
|
134
|
+
}
|
|
135
|
+
if (rest) parts.push(rest);
|
|
136
|
+
return parts;
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
|
|
111
140
|
/** Build the stored contract; Delta Gather keeps lane-authored sections. */
|
|
112
141
|
export function freezeFromGather({
|
|
113
142
|
gather,
|
|
114
143
|
ask,
|
|
115
144
|
boundaries,
|
|
116
145
|
issue,
|
|
146
|
+
issueSet,
|
|
117
147
|
laneNotes,
|
|
118
148
|
doneCheck,
|
|
119
149
|
lookups = [],
|
|
@@ -136,11 +166,14 @@ export function freezeFromGather({
|
|
|
136
166
|
objective: {
|
|
137
167
|
// Dev's Lane contract names the ask; without one, Gather's objective.
|
|
138
168
|
ask: ask ?? gather.objective,
|
|
139
|
-
issue: issue === undefined ? (current?.objective?.issue ?? null) : issue,
|
|
140
|
-
|
|
169
|
+
issue: issueWithinCap(issue === undefined ? (current?.objective?.issue ?? null) : issue),
|
|
170
|
+
// NODII-DEV-CLI-191: the lane's other mapped issues, keys and titles only.
|
|
171
|
+
...((issueSet ?? current?.objective?.issueSet)?.length ? { issueSet: issueSet ?? current.objective.issueSet } : {}),
|
|
172
|
+
laneNotes: notesWithinCap(
|
|
141
173
|
laneNotes === undefined
|
|
142
174
|
? (current?.objective?.laneNotes ?? [])
|
|
143
175
|
: laneNotes,
|
|
176
|
+
),
|
|
144
177
|
doneCheck: effectiveDoneCheck,
|
|
145
178
|
},
|
|
146
179
|
boundaries,
|
package/dist/gather.js
CHANGED
|
@@ -581,9 +581,20 @@ const tags = (clause) => {
|
|
|
581
581
|
return parts.length ? ` [${parts.join("; ")}]` : "";
|
|
582
582
|
};
|
|
583
583
|
|
|
584
|
+
// A breadcrumb names where a clause sits; a SWAP breadcrumb carries the whole
|
|
585
|
+
// swap (24 KB across one lane's map), which `rules show <ID>` prints in full.
|
|
586
|
+
const CRUMB_MAX = 160;
|
|
587
|
+
const crumb = (text) => {
|
|
588
|
+
const flat = String(text ?? "").replace(/\s+/g, " ").trim();
|
|
589
|
+
return flat.length <= CRUMB_MAX ? flat : `${flat.slice(0, CRUMB_MAX - 1).trimEnd()}…`;
|
|
590
|
+
};
|
|
591
|
+
|
|
584
592
|
export function gatherText(payload, objective = "", reasons = {}) {
|
|
585
593
|
const data = payload?.data ?? payload ?? {};
|
|
586
|
-
|
|
594
|
+
// NODII-DEV-CLI-191: the objective and lane notes are in the contract
|
|
595
|
+
// above; the header no longer repeats them as JSON (4.7 KB on a long lane).
|
|
596
|
+
void objective;
|
|
597
|
+
const lines = ["Lane contract", data.laneContract ?? LANE_CONTRACT, "", "Clause map"];
|
|
587
598
|
for (const notice of data.notices ?? []) lines.push(`Notice: ${notice}`);
|
|
588
599
|
const documents = new Map();
|
|
589
600
|
for (const clause of data.clauses ?? []) {
|
|
@@ -597,13 +608,13 @@ export function gatherText(payload, objective = "", reasons = {}) {
|
|
|
597
608
|
const why = reasons instanceof Map ? reasons.get(document.code) : reasons[document.code];
|
|
598
609
|
lines.push(`${document.code}${why ? ` ← ${why}` : ""}`);
|
|
599
610
|
for (const section of document.sections.values()) {
|
|
600
|
-
lines.push(` ${section.breadcrumb}`);
|
|
611
|
+
lines.push(` ${crumb(section.breadcrumb)}`);
|
|
601
612
|
for (const clause of section.clauses)
|
|
602
613
|
lines.push(` ${clause.clauseId} ${clause.gist}${clause.counterInstinct ? " ⚑" : ""}${tags(clause)}`.trimEnd());
|
|
603
614
|
}
|
|
604
615
|
}
|
|
605
616
|
if (!documents.size) lines.push(" No clauses matched.");
|
|
606
|
-
lines.push("", 'Not sure something applies? nodii-dev rules find "<question>"');
|
|
617
|
+
lines.push("", 'Read a clause in full with `nodii-dev rules show <ID>`. Not sure something applies? nodii-dev rules find "<question>"');
|
|
607
618
|
return lines.join("\n");
|
|
608
619
|
}
|
|
609
620
|
|
package/dist/harness.js
CHANGED
|
@@ -13,6 +13,7 @@ import { CliError, devRequest, query } from "./core.js";
|
|
|
13
13
|
import { classifyClaudeManaged, claudeManagedSettingsPath, managedClaudeHookBundle, managedHookBundle, nodiiCommandArgs, refreshManagedDispatchers, writeManagedClaudeHookBundle, writeManagedHookBundle } from "./managed-hooks.js";
|
|
14
14
|
import { heartbeatSettingsSnippet } from "./hooks.js";
|
|
15
15
|
import { nudgeSettingsSnippet } from "./nudges.js";
|
|
16
|
+
import { toolingDocsSettingsSnippet } from "./tooling-docs.js";
|
|
16
17
|
import { codexSafetyHooksSnippet, regroundingHooksSnippet, safetySettingsSnippet } from "./safety.js";
|
|
17
18
|
|
|
18
19
|
/** What this CLI wrote, per path: { mode, sha256 }, or for merge-json the hook entries it `added`. */
|
|
@@ -202,6 +203,7 @@ export function withSafetyHooks(harness) {
|
|
|
202
203
|
hooks = addHookEntries(hooks, regroundingHooksSnippet().hooks);
|
|
203
204
|
hooks = addHookEntries(hooks, heartbeatSettingsSnippet().hooks);
|
|
204
205
|
hooks = addHookEntries(hooks, nudgeSettingsSnippet().hooks);
|
|
206
|
+
hooks = addHookEntries(hooks, toolingDocsSettingsSnippet().hooks);
|
|
205
207
|
assertNodiiHooks(hooks, ".claude/settings.json");
|
|
206
208
|
settings.content = JSON.stringify({ ...parsed, hooks });
|
|
207
209
|
settings.sha256 = sha(settings.content);
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { CliError, readConfig } from "./core.js";
|
|
2
|
+
import { unsupervisedHeartbeat } from "./hooks.js";
|
|
3
|
+
import { nudgeCandidate, nudgePre, steerAct, stewardSteerNudges } from "./nudges.js";
|
|
4
|
+
import { isLaneRunSession, isReviewSession } from "./review-session.js";
|
|
5
|
+
import { hookRuntime, recordHookFire, safetyContext, safetyPostHook, safetyPreHook } from "./safety.js";
|
|
6
|
+
import { activeSteward, isLaneConfig } from "./session-kind.js";
|
|
7
|
+
import { toolingDocsHook } from "./tooling-docs.js";
|
|
8
|
+
import { pendingAmendmentContext } from "./starting.js";
|
|
9
|
+
import { inboxHookContext } from "./lane-messages.js";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* NODII-DEV-CLI-191: the hook handlers the managed dispatcher runs in its
|
|
13
|
+
* own process instead of starting `nodii-dev hook ACTION` for each. `hook
|
|
14
|
+
* ACTION` runs the same functions, so both answer alike: the stdout lines, and
|
|
15
|
+
* for Claude a denial raised as exit 2 with its reason on stderr.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
const line = (event, fields) => JSON.stringify({ hookSpecificOutput: { hookEventName: event, ...fields } });
|
|
19
|
+
|
|
20
|
+
/** What `fail` prints for an error: the dispatcher reads it as a denial's reason. */
|
|
21
|
+
export const errorText = (error) => `${error.code}: ${error.message}${error.details ? `\n${JSON.stringify(error.details)}` : ""}`;
|
|
22
|
+
|
|
23
|
+
/** `hook safety-pre`. Only an evaluated safety rule may deny; every other failure is no output. */
|
|
24
|
+
export async function safetyPreAnswer(payloadText) {
|
|
25
|
+
let payload;
|
|
26
|
+
try {
|
|
27
|
+
payload = JSON.parse(payloadText);
|
|
28
|
+
await recordHookFire(payload).catch(() => {});
|
|
29
|
+
const nudges = (await safetyPreHook(payload)).nudges ?? [];
|
|
30
|
+
// Both runtimes show the model a PreToolUse nudge only as additionalContext;
|
|
31
|
+
// Claude keeps plain stdout of an exit-0 hook out of the model's context.
|
|
32
|
+
return { lines: nudges.length ? [line("PreToolUse", { additionalContext: nudges.join("\n") })] : [] };
|
|
33
|
+
} catch (error) {
|
|
34
|
+
// Discovery, parsing, git, config and Dev errors fail open and produce no output.
|
|
35
|
+
if (!String(error?.code ?? "").startsWith("SAFETY_")) return { lines: [] };
|
|
36
|
+
if (payload && hookRuntime(payload) === "codex")
|
|
37
|
+
return { lines: [line("PreToolUse", { permissionDecision: "deny", permissionDecisionReason: error?.message ?? String(error) })] };
|
|
38
|
+
return { lines: [], denial: new CliError(error?.code ?? "SAFETY_HOOK_FAILED", error?.message ?? String(error), 2, error?.details) };
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** `hook safety-post`: records, never answers. */
|
|
43
|
+
export async function safetyPostAnswer(payloadText) {
|
|
44
|
+
try {
|
|
45
|
+
const payload = JSON.parse(payloadText);
|
|
46
|
+
await recordHookFire(payload).catch(() => {});
|
|
47
|
+
await safetyPostHook(payload);
|
|
48
|
+
} catch {}
|
|
49
|
+
return { lines: [] };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* `hook nudge-pre`. Guideline nudges (AGENT-HARNESS-21) never block: any error,
|
|
54
|
+
* a payload they don't know or a session outside a lane ends in no output.
|
|
55
|
+
* It also carries the tool-call heartbeat of a session no lane supervisor
|
|
56
|
+
* beats for, at most once per 5 minutes (NODII-DEV-CLI-191).
|
|
57
|
+
*/
|
|
58
|
+
export async function nudgePreAnswer(payloadText, { heartbeat = unsupervisedHeartbeat } = {}) {
|
|
59
|
+
const lines = [];
|
|
60
|
+
let beat = null;
|
|
61
|
+
try {
|
|
62
|
+
const payload = JSON.parse(payloadText);
|
|
63
|
+
await recordHookFire(payload).catch(() => {});
|
|
64
|
+
beat = Promise.resolve().then(() => heartbeat(payload)).catch(() => null);
|
|
65
|
+
// Cite before you steer (MW1-95): a steward session, which is never a lane config.
|
|
66
|
+
if (!isLaneConfig() && steerAct(payload)) {
|
|
67
|
+
const config = await readConfig(false).catch(() => null);
|
|
68
|
+
const steward = await activeSteward(config?.agentId).catch(() => null);
|
|
69
|
+
const nudges = await stewardSteerNudges(payload, { steward });
|
|
70
|
+
if (nudges.length) lines.push(line("PreToolUse", { additionalContext: nudges.join("\n") }));
|
|
71
|
+
if (steward) return { lines };
|
|
72
|
+
}
|
|
73
|
+
// MW1-12.9: a lane that has not acknowledged an amendment (an answer, a leeway grant) is told here.
|
|
74
|
+
// NODII-DEV-CLI-191: unread lane messages, from the local inbox file alone (no Dev call).
|
|
75
|
+
const mail = isLaneConfig() ? await inboxHookContext().catch(() => null) : null;
|
|
76
|
+
const pending = isLaneConfig() ? await pendingAmendmentContext() : null;
|
|
77
|
+
const nudges = (await nudgeCandidate(payload)) ? await nudgePre(payload, await safetyContext(payload.cwd ?? process.cwd())).catch(() => []) : [];
|
|
78
|
+
const context = [mail, pending, ...nudges].filter(Boolean);
|
|
79
|
+
if (context.length) lines.push(line("PreToolUse", { additionalContext: context.join("\n") }));
|
|
80
|
+
} catch {
|
|
81
|
+
} finally {
|
|
82
|
+
await beat;
|
|
83
|
+
}
|
|
84
|
+
return { lines };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** `hook tooling-docs` (MW1-46.3). Reads git only, never Dev; any error is no output, so a broken check never holds a push. */
|
|
88
|
+
export async function toolingDocsAnswer(payloadText) {
|
|
89
|
+
try {
|
|
90
|
+
const verdict = await toolingDocsHook(JSON.parse(payloadText));
|
|
91
|
+
if (verdict?.deny) return { lines: [line("PreToolUse", { permissionDecision: "deny", permissionDecisionReason: verdict.deny })] };
|
|
92
|
+
} catch {}
|
|
93
|
+
return { lines: [] };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** hub-284: a reviewer, or a session in this run other than the lane's own, gets nothing from a lane-run hook. */
|
|
97
|
+
export async function spawnedSession(payloadText, { env = process.env } = {}) {
|
|
98
|
+
if (await isReviewSession()) return true;
|
|
99
|
+
if (!env.NODII_DEV_RUN_ID) return false;
|
|
100
|
+
let payload = null;
|
|
101
|
+
try { payload = JSON.parse(payloadText); } catch {}
|
|
102
|
+
return !(await isLaneRunSession(payload));
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The handlers with an in-process form, by `hook` action. */
|
|
106
|
+
export const HOOK_ANSWERS = { "safety-pre": safetyPreAnswer, "safety-post": safetyPostAnswer, "nudge-pre": nudgePreAnswer, "tooling-docs": toolingDocsAnswer };
|
|
107
|
+
// cli.js LANE_RUN_HOOKS, of the handlers above.
|
|
108
|
+
const LANE_RUN = new Set(["nudge-pre"]);
|
|
109
|
+
const EMPTY = { status: 0, stdout: "", stderr: "" };
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* One handler, in this process, answered as `nodii-dev hook ACTION` would exit:
|
|
113
|
+
* { status, stdout, stderr }. Null for a handler with no in-process form.
|
|
114
|
+
*/
|
|
115
|
+
export async function runHookInProcess(action, payloadText, { spawned = spawnedSession, heartbeat } = {}) {
|
|
116
|
+
if (!Object.hasOwn(HOOK_ANSWERS, action)) return null;
|
|
117
|
+
const answer = HOOK_ANSWERS[action];
|
|
118
|
+
try {
|
|
119
|
+
if (LANE_RUN.has(action) && (await spawned(payloadText))) return EMPTY;
|
|
120
|
+
const { lines, denial } = await answer(payloadText, heartbeat ? { heartbeat } : {});
|
|
121
|
+
const stdout = lines.map((text) => `${text}\n`).join("");
|
|
122
|
+
return denial ? { status: denial.exitCode ?? 1, stdout, stderr: `${errorText(denial)}\n` } : { ...EMPTY, stdout };
|
|
123
|
+
} catch {
|
|
124
|
+
// A hook that fails is no answer (nodii-dev.js exits 0 for it).
|
|
125
|
+
return EMPTY;
|
|
126
|
+
}
|
|
127
|
+
}
|
package/dist/hooks.js
CHANGED
|
@@ -5,6 +5,7 @@ import { execFile } from "node:child_process";
|
|
|
5
5
|
import { readFile, writeFile } from "node:fs/promises";
|
|
6
6
|
import { promisify } from "node:util";
|
|
7
7
|
import { safetySettingsSnippet } from "./safety.js";
|
|
8
|
+
import { laneSwitchOn } from "./lane-switches.js";
|
|
8
9
|
|
|
9
10
|
const execFileAsync = promisify(execFile);
|
|
10
11
|
|
|
@@ -219,10 +220,9 @@ export const settingsSnippet = () => {
|
|
|
219
220
|
} };
|
|
220
221
|
};
|
|
221
222
|
|
|
222
|
-
// MW1-34, MW5-17:
|
|
223
|
-
//
|
|
224
|
-
//
|
|
225
|
-
// the agent acted, which is what keeps `stuck` meaningful.
|
|
223
|
+
// MW1-34, MW5-17: a live lane is heartbeaten while its agent acts, about once a
|
|
224
|
+
// minute, and on stop. The lane heartbeat also refreshes the lane's run in Dev.
|
|
225
|
+
// It says the agent acted, which is what keeps `stuck` meaningful.
|
|
226
226
|
export const HEARTBEAT_STAMP = "nodii-lane-heartbeat-at";
|
|
227
227
|
export const HEARTBEAT_MIN_INTERVAL_MS = 60_000;
|
|
228
228
|
// hub-528: reading a lane costs hundreds of KB, so the hook keeps the lane it
|
|
@@ -234,11 +234,27 @@ export const HEARTBEAT_LANE_CACHE = "nodii-lane-heartbeat-lane.json";
|
|
|
234
234
|
export const HEARTBEAT_LANE_TTL_MS = 60 * 60_000;
|
|
235
235
|
export const HEARTBEAT_NO_LANE_TTL_MS = 5 * 60_000;
|
|
236
236
|
const LANE_ENDED = new Set(["LANE_NOT_FOUND", "LANE_TERMINAL"]);
|
|
237
|
-
|
|
237
|
+
// NODII-DEV-CLI-191: no heartbeat process on every tool call. A launched
|
|
238
|
+
// lane's supervisor beats the lane on its interval whenever the runtime wrote
|
|
239
|
+
// to its log or transcript (lane-supervisor.js), and the harness keeps one Stop
|
|
240
|
+
// beat. A session with no supervisor beats from nudge-pre, which already runs
|
|
241
|
+
// on each tool call, at most once per 5 minutes (Dev marks a lane quiet at 15).
|
|
242
|
+
export const HEARTBEAT_UNSUPERVISED_INTERVAL_MS = 5 * 60_000;
|
|
243
|
+
// Off unless NODII_DEV_STOP_ONLY_HEARTBEAT=1 until its clause is in force: the
|
|
244
|
+
// harness then keeps the tool-call beat as before, and neither the supervisor
|
|
245
|
+
// nor nudge-pre beats the lane.
|
|
246
|
+
export const heartbeatSettingsSnippet = (env = process.env) => {
|
|
238
247
|
const beat = [{ hooks: [{ type: "command", command: "nodii-dev hook lane-heartbeat" }] }];
|
|
239
|
-
return { hooks: { PostToolUse: beat, Stop: beat } };
|
|
248
|
+
return { hooks: laneSwitchOn("stopOnlyHeartbeat", env) ? { Stop: beat } : { PostToolUse: beat, Stop: beat } };
|
|
240
249
|
};
|
|
241
250
|
|
|
251
|
+
/** The tool-call beat for a session no lane supervisor beats for; a launched run (NODII_DEV_RUN_ID) sends none. */
|
|
252
|
+
export async function unsupervisedHeartbeat(payload, { env = process.env, ...options } = {}) {
|
|
253
|
+
if (!laneSwitchOn("stopOnlyHeartbeat", env)) return { heartbeated: false, reason: "the tool-call hook beats" };
|
|
254
|
+
if (env.NODII_DEV_RUN_ID) return { heartbeated: false, reason: "supervised run" };
|
|
255
|
+
return heartbeatFromHook(payload, { ...options, env, minIntervalMs: HEARTBEAT_UNSUPERVISED_INTERVAL_MS });
|
|
256
|
+
}
|
|
257
|
+
|
|
242
258
|
/** One rate-limited heartbeat for the worktree a hook fired in. The stamp is written first, so parallel tool calls send one. */
|
|
243
259
|
export async function heartbeatFromHook(payload, { request = devRequest, now = Date.now, minIntervalMs = HEARTBEAT_MIN_INTERVAL_MS, env = process.env } = {}) {
|
|
244
260
|
const cwd = payload?.cwd ?? process.cwd();
|