@nodii/dev 0.6.208 → 0.6.209
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 +105 -38
- package/dist/cli.js +64 -39
- package/dist/coordinator-items.js +31 -36
- package/dist/coordinator-watch.js +3 -1
- package/dist/core.js +72 -9
- package/dist/figma-scope.js +31 -6
- package/dist/flags.js +6 -4
- package/dist/harness.js +105 -2
- package/dist/impact.js +304 -12
- package/dist/lane-asks.js +22 -87
- package/dist/lane-messages.js +63 -1
- package/dist/lane-switches.js +1 -1
- package/dist/lanes.js +26 -5
- package/dist/managed-version.js +90 -11
- package/dist/nodii-dev.js +2 -0
- package/dist/process-tree.js +18 -0
- package/dist/rulings.js +77 -0
- package/dist/safety.js +3 -1
- package/dist/session-kind.js +164 -15
- package/dist/setup.js +1 -1
- package/dist/starting.js +2 -2
- package/dist/surface.js +10 -3
- package/dist/watchdog.js +108 -5
- package/package.json +1 -1
|
@@ -2,22 +2,23 @@ import { access, readFile, rm } from "node:fs/promises";
|
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
3
|
import { dirname, join } from "node:path";
|
|
4
4
|
import { devRequest, query } from "./core.js";
|
|
5
|
-
import { laneAsksOn } from "./lane-asks.js";
|
|
6
5
|
import { cachedGet, laneReadCache } from "./read-cache.js";
|
|
7
6
|
|
|
8
7
|
/**
|
|
9
8
|
* hub-525 (MW1-37.2): the coordinator clears lane items first.
|
|
10
|
-
* Lanes ask
|
|
9
|
+
* Lanes ask for leeway and wait; Dev counts what waits on a machine's
|
|
11
10
|
* coordinator and says so in a response header on every answer to that
|
|
12
11
|
* coordinator. The CLI prints one line for it before each command's output,
|
|
13
12
|
* `coordinator items` lists the items, and the coordinator gate (a PreToolUse
|
|
14
13
|
* hook in the managed dispatcher) holds the coordinator's next nodii-dev write
|
|
15
|
-
* while
|
|
14
|
+
* while a leeway has waited over 10 minutes. Lane questions are retired
|
|
15
|
+
* (DEV-PROCESS-5, row 29b): an `ask` item Dev still serves is never listed,
|
|
16
|
+
* counted or gated, since no command clears it.
|
|
16
17
|
*/
|
|
17
18
|
|
|
18
19
|
export const LANE_ITEMS_HEADER = "x-dev-lane-items";
|
|
19
20
|
const ITEMS_PATH = "/api/v1/coordinator/items";
|
|
20
|
-
//
|
|
21
|
+
// Leeways gate after this long; waits and escalations never do.
|
|
21
22
|
export const GATE_AFTER_SECONDS = 10 * 60;
|
|
22
23
|
const GATE_CACHE_TTL_MS = 10_000;
|
|
23
24
|
const LINE_CACHE_KEY = "coordinator-items-line";
|
|
@@ -26,18 +27,19 @@ const DETAIL_TIMEOUT_MS = 3_000;
|
|
|
26
27
|
const GATE_TIMEOUT_MS = 5_000;
|
|
27
28
|
|
|
28
29
|
// kind, singular, plural: in the order the line names them.
|
|
29
|
-
const KINDS = [["leeway", "leeway", "leeways"], ["
|
|
30
|
+
const KINDS = [["leeway", "leeway", "leeways"], ["wait", "wait", "waits"], ["escalation", "escalation", "escalations"]];
|
|
31
|
+
// Lane questions are retired (DEV-PROCESS-5, row 29b): what Dev still counts as one is left out.
|
|
32
|
+
const RETIRED_KIND = "ask";
|
|
30
33
|
|
|
31
|
-
/** `total=3;leeway=1;
|
|
32
|
-
export function parseLaneItemsHeader(value
|
|
34
|
+
/** `total=3;leeway=1;wait=2;escalation=0;oldest=2040` as numbers, or null when there is nothing to say. */
|
|
35
|
+
export function parseLaneItemsHeader(value) {
|
|
33
36
|
if (typeof value !== "string" || !value.trim()) return null;
|
|
34
37
|
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
38
|
if (!Number.isInteger(fields.total) || fields.total <= 0) return null;
|
|
36
|
-
//
|
|
37
|
-
const
|
|
38
|
-
const total = fields.total - ((fields.ask ?? 0) - ask);
|
|
39
|
+
// Retired questions are not counted, and questions alone are nothing to say.
|
|
40
|
+
const total = fields.total - (fields[RETIRED_KIND] ?? 0);
|
|
39
41
|
if (total <= 0) return null;
|
|
40
|
-
return { total, leeway: fields.leeway ?? 0,
|
|
42
|
+
return { total, leeway: fields.leeway ?? 0, wait: fields.wait ?? 0, escalation: fields.escalation ?? 0, oldest: fields.oldest ?? 0 };
|
|
41
43
|
}
|
|
42
44
|
|
|
43
45
|
const age = (seconds) => {
|
|
@@ -47,10 +49,10 @@ const age = (seconds) => {
|
|
|
47
49
|
const deferred = (item, now) => Boolean(item?.deferredUntil) && Date.parse(item.deferredUntil) > now;
|
|
48
50
|
|
|
49
51
|
/** The one line a coordinator's command prints first. With no detail it is the counts alone. */
|
|
50
|
-
export function laneItemsLine(counts, items, {
|
|
52
|
+
export function laneItemsLine(counts, items, { now = Date.now() } = {}) {
|
|
51
53
|
const parts = KINDS.filter(([kind]) => counts[kind] > 0).map(([kind, one, many]) => {
|
|
52
54
|
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) =>
|
|
55
|
+
const names = open.slice(0, 5).map((item) => item.laneKey);
|
|
54
56
|
const more = open.length > 5 ? `, +${open.length - 5} more` : "";
|
|
55
57
|
return `${counts[kind]} ${counts[kind] === 1 ? one : many}${names.length ? ` (${names.join(", ")}${more})` : ""}`;
|
|
56
58
|
});
|
|
@@ -94,7 +96,7 @@ export async function observeLaneItems(header, { request = devRequest, cache = l
|
|
|
94
96
|
refreshing = false;
|
|
95
97
|
}
|
|
96
98
|
}
|
|
97
|
-
current = laneItemsLine(counts, detail?.items ?? null, {
|
|
99
|
+
current = laneItemsLine(counts, detail?.items ?? null, { now: now() });
|
|
98
100
|
} catch {
|
|
99
101
|
current = null;
|
|
100
102
|
}
|
|
@@ -110,28 +112,22 @@ export function takeLaneItemsLine() {
|
|
|
110
112
|
// ─── coordinator items ──────────────────────────────────────────────────────
|
|
111
113
|
|
|
112
114
|
/** `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
|
|
115
|
+
export async function coordinatorItemsCommand(flags, { request = devRequest, now = Date.now } = {}) {
|
|
114
116
|
const payload = await request("GET", `${ITEMS_PATH}${query({ machine: typeof flags.machine === "string" ? flags.machine : undefined })}`);
|
|
115
117
|
const data = payload.data ?? {};
|
|
116
|
-
//
|
|
117
|
-
const
|
|
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");
|
|
118
|
+
// Retired questions (DEV-PROCESS-5, row 29b): none is listed or counted.
|
|
119
|
+
const items = (data.items ?? []).filter((item) => item?.kind !== RETIRED_KIND);
|
|
120
120
|
const counts = data.counts ?? {};
|
|
121
|
-
const total = Math.max(0, Number(data.total ?? 0) -
|
|
122
|
-
if (!total && !items.length) return { payload, human:
|
|
121
|
+
const total = Math.max(0, Number(data.total ?? 0) - Number(counts[RETIRED_KIND] ?? 0));
|
|
122
|
+
if (!total && !items.length) return { payload, human: "Nothing from lanes is waiting on you." };
|
|
123
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)}): ${
|
|
124
|
+
const lines = [`${total} from lanes waiting on you (oldest ${age(data.oldestSeconds)}): ${count("leeway", "leeway", "leeways")}, ${count("wait", "wait", "waits")}, ${count("escalation", "escalation", "escalations")}.`];
|
|
125
125
|
for (const item of items) {
|
|
126
126
|
const note = deferred(item, now()) || item.deferredUntil ? ` (deferred until ${item.deferredUntil})` : item.gates ? "" : " (counted, never gates)";
|
|
127
127
|
lines.push(`${item.kind}\t${item.laneKey}\t${age(item.ageSeconds)}\t${String(item.summary ?? "").replace(/\s+/g, " ").trim()}${note}`);
|
|
128
128
|
if (item.command) lines.push(` ${item.command}`);
|
|
129
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
|
-
);
|
|
130
|
+
lines.push(`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 <leeway id> --reason TEXT [--minutes N]).`);
|
|
135
131
|
return { payload, human: lines.join("\n") };
|
|
136
132
|
}
|
|
137
133
|
|
|
@@ -154,9 +150,9 @@ export async function clearCoordinatorMarker(runId, { env = process.env } = {})
|
|
|
154
150
|
|
|
155
151
|
// Commands that never write lane or issue state in Dev, or that a coordinator must always be able to run.
|
|
156
152
|
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"
|
|
153
|
+
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"]);
|
|
158
154
|
// The lane actions that clear an item, close out a lane or bring one back.
|
|
159
|
-
const LANE_ALLOWED = new Set(["
|
|
155
|
+
const LANE_ALLOWED = new Set(["defer", "resume", "close", "stop", "closeout"]);
|
|
160
156
|
// Lane actions with a subcommand: which of them write.
|
|
161
157
|
const LANE_SUB_WRITES = {
|
|
162
158
|
leeway: (sub) => !["grant", "refuse", "show", "list"].includes(sub),
|
|
@@ -196,7 +192,7 @@ export function gatedCommand(command) {
|
|
|
196
192
|
|
|
197
193
|
/**
|
|
198
194
|
* PreToolUse on Bash and AskUserQuestion, for a coordinator session. Denies a
|
|
199
|
-
* nodii-dev write while
|
|
195
|
+
* nodii-dev write while a leeway has waited over 10 minutes
|
|
200
196
|
* undeferred, naming each with the command that clears it. A question to the
|
|
201
197
|
* operator is never denied (MW1-116: an override or a lock change is asked the
|
|
202
198
|
* moment it arises): it passes with the same items named as context. Fails
|
|
@@ -219,17 +215,16 @@ export async function coordinatorGate(payload, deps = {}) {
|
|
|
219
215
|
} catch {
|
|
220
216
|
return { context: "lane items unread: Dev unreachable" };
|
|
221
217
|
}
|
|
222
|
-
//
|
|
223
|
-
const
|
|
224
|
-
const overdue = items.filter((item) => item?.gates === true && (asksOn || item.kind !== "ask") && Number(item.ageSeconds) > GATE_AFTER_SECONDS && !deferred(item, now));
|
|
218
|
+
// A retired question never holds the coordinator, since no command clears one.
|
|
219
|
+
const overdue = items.filter((item) => item?.gates === true && item.kind !== RETIRED_KIND && Number(item.ageSeconds) > GATE_AFTER_SECONDS && !deferred(item, now));
|
|
225
220
|
if (!overdue.length) return null;
|
|
226
221
|
const lines = [
|
|
227
222
|
...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.",
|
|
223
|
+
"Defer one with a reason: nodii-dev lane defer <leeway id> --reason TEXT [--minutes N]. List them: nodii-dev coordinator items.",
|
|
229
224
|
];
|
|
230
225
|
const waited = `${overdue.length} lane item${overdue.length === 1 ? " has" : "s have"} waited over ${GATE_AFTER_SECONDS / 60} minutes.`;
|
|
231
226
|
// MW1-116: the operator question goes through; the coordinator is told what still waits.
|
|
232
227
|
if (tool === "AskUserQuestion")
|
|
233
|
-
return { context: [`nodii-dev coordinator gate (MW1-37.2): ${waited} Your question to the operator is not held (MW1-116);
|
|
234
|
-
return { deny: [`nodii-dev coordinator gate (MW1-37.2): ${waited}
|
|
228
|
+
return { context: [`nodii-dev coordinator gate (MW1-37.2): ${waited} Your question to the operator is not held (MW1-116); grant, refuse or defer each right after it:`, ...lines].join("\n") };
|
|
229
|
+
return { deny: [`nodii-dev coordinator gate (MW1-37.2): ${waited} Grant, refuse or defer each before \`${what}\`:`, ...lines].join("\n") };
|
|
235
230
|
}
|
|
@@ -664,9 +664,11 @@ export async function watchServicePath({ home = homedir(), os = platform(), exec
|
|
|
664
664
|
* the keychain).
|
|
665
665
|
*/
|
|
666
666
|
export async function installWatch({
|
|
667
|
-
home = homedir(), uid = process.getuid?.(), os = platform(), env = process.env, runtime = process.execPath, entry =
|
|
667
|
+
home = homedir(), uid = process.getuid?.(), os = platform(), env = process.env, runtime = process.execPath, entry = null,
|
|
668
668
|
configFile = configPath(), execute = execFile, config = readConfig, request = devRequest, requireCoordinator = true,
|
|
669
669
|
} = {}) {
|
|
670
|
+
// The daemon runs the managed copy `harness update` keeps current (CLI-15).
|
|
671
|
+
entry ??= (await (await import("./managed-version.js")).managedEntry()) ?? resolve(process.argv[1]);
|
|
670
672
|
if (os !== "darwin" && os !== "linux")
|
|
671
673
|
throw new CliError("WATCH_UNSUPPORTED", `coordinator watch installs with launchd on macOS and with a systemd user service on Linux; ${os} is not supported.`, 2);
|
|
672
674
|
if (requireCoordinator) {
|
package/dist/core.js
CHANGED
|
@@ -4,7 +4,7 @@ import { chmod, lstat, mkdir, readFile, rename, rm, writeFile } from "node:fs/pr
|
|
|
4
4
|
import { homedir, platform } from "node:os";
|
|
5
5
|
import { basename, dirname, join } from "node:path";
|
|
6
6
|
|
|
7
|
-
export const VERSION = "0.6.
|
|
7
|
+
export const VERSION = "0.6.209";
|
|
8
8
|
export const configPath = () =>
|
|
9
9
|
process.env.NODII_DEV_CONFIG_PATH ??
|
|
10
10
|
join(homedir(), ".config/nodii-dev/config.json");
|
|
@@ -166,6 +166,57 @@ const refusalMessage = (raw) => {
|
|
|
166
166
|
}
|
|
167
167
|
};
|
|
168
168
|
|
|
169
|
+
// O3 item 4 (DEC-0569): what Dev's requests cost this machine. Each request
|
|
170
|
+
// adds {n, ms} to one small JSON beside the config (the nodii-dev directory
|
|
171
|
+
// lane configs under agents/ share), bucketed by what sent it: a hook, a
|
|
172
|
+
// Gather, or any other command. The sweep's machine report carries it, so it
|
|
173
|
+
// costs no Dev call. Best effort: no fsync, and a failed write is dropped.
|
|
174
|
+
export const CALL_COST_SOURCES = ["hook", "gather", "command"];
|
|
175
|
+
export function callCostPath(path = configPath()) {
|
|
176
|
+
const dir = dirname(path);
|
|
177
|
+
return join(basename(dir) === "agents" ? dirname(dir) : dir, "call-cost.json");
|
|
178
|
+
}
|
|
179
|
+
let callSource = "command";
|
|
180
|
+
/** What the calls of this process count as, from its argv. */
|
|
181
|
+
export function callSourceFor(argv = []) {
|
|
182
|
+
if (argv[0] === "hook") return "hook";
|
|
183
|
+
if (argv[0] === "gather" || (argv[0] === "lane" && argv[1] === "gather")) return "gather";
|
|
184
|
+
return "command";
|
|
185
|
+
}
|
|
186
|
+
export function setCallSource(source) {
|
|
187
|
+
callSource = CALL_COST_SOURCES.includes(source) ? source : "command";
|
|
188
|
+
}
|
|
189
|
+
const emptyCallCost = (since) => ({ since, calls: Object.fromEntries(CALL_COST_SOURCES.map((k) => [k, { n: 0, ms: 0 }])) });
|
|
190
|
+
/** The counter file, or null when there is none or it does not parse. */
|
|
191
|
+
export async function readCallCost(path = callCostPath()) {
|
|
192
|
+
try {
|
|
193
|
+
const saved = JSON.parse(await readFile(path, "utf8"));
|
|
194
|
+
if (typeof saved?.since !== "string" || !saved.calls || typeof saved.calls !== "object") return null;
|
|
195
|
+
const out = emptyCallCost(saved.since);
|
|
196
|
+
for (const k of CALL_COST_SOURCES) {
|
|
197
|
+
const n = Number(saved.calls[k]?.n), ms = Number(saved.calls[k]?.ms);
|
|
198
|
+
if (Number.isSafeInteger(n) && n >= 0 && Number.isFinite(ms) && ms >= 0) out.calls[k] = { n, ms };
|
|
199
|
+
}
|
|
200
|
+
return out;
|
|
201
|
+
} catch {
|
|
202
|
+
return null;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
// The counts are best effort: two processes that read the file at once each
|
|
206
|
+
// write their own +1, and one of them is lost. A weekly number tolerates that;
|
|
207
|
+
// a lock on every Dev request would cost more than the count is worth.
|
|
208
|
+
export async function recordCallCost(ms, { source = callSource, path = callCostPath(), now = () => new Date() } = {}) {
|
|
209
|
+
try {
|
|
210
|
+
const cost = (await readCallCost(path)) ?? emptyCallCost(now().toISOString());
|
|
211
|
+
const bucket = cost.calls[CALL_COST_SOURCES.includes(source) ? source : "command"];
|
|
212
|
+
bucket.n += 1;
|
|
213
|
+
bucket.ms = Math.round((bucket.ms + Math.max(0, ms)) * 10) / 10;
|
|
214
|
+
const temporary = `${path}.${process.pid}.${randomBytes(4).toString("hex")}`;
|
|
215
|
+
await writeFile(temporary, JSON.stringify(cost), { mode: 0o600 });
|
|
216
|
+
await rename(temporary, path);
|
|
217
|
+
} catch { /* best effort: never fails a request */ }
|
|
218
|
+
}
|
|
219
|
+
|
|
169
220
|
async function devFetchOnce(method, path, bodyText, contentType, accept, extra = {}, signal) {
|
|
170
221
|
const first = await devFetchSend(method, path, bodyText, contentType, accept, extra, signal);
|
|
171
222
|
if (first.response.status !== 429) return first;
|
|
@@ -203,10 +254,13 @@ async function devFetchSend(method, path, bodyText, contentType, accept, extra =
|
|
|
203
254
|
let refreshed = false;
|
|
204
255
|
let adopted = false;
|
|
205
256
|
for (;;) {
|
|
206
|
-
|
|
257
|
+
// The CLI's version rides every Dev request (O3 item 7). Not x-nodii-*: the
|
|
258
|
+
// edge strips those and the hub reads them as gateway claims.
|
|
259
|
+
const headers = { accept, "x-dev-cli-version": VERSION, ...extra };
|
|
207
260
|
if (bodyText !== undefined) headers["content-type"] = contentType;
|
|
208
261
|
Object.assign(headers, await wait(auth.headers({ method, path, body: bodyText ?? "" })));
|
|
209
262
|
let response;
|
|
263
|
+
const started = performance.now();
|
|
210
264
|
try {
|
|
211
265
|
response = await wait(fetch(url, { method, headers, body: bodyText, signal }));
|
|
212
266
|
} catch (error) {
|
|
@@ -215,6 +269,7 @@ async function devFetchSend(method, path, bodyText, contentType, accept, extra =
|
|
|
215
269
|
throw new CliError("DEV_UNREACHABLE", `Cannot reach Dev at ${new URL(url).origin}: ${error.message}`);
|
|
216
270
|
}
|
|
217
271
|
const raw = await wait(response.text());
|
|
272
|
+
await recordCallCost(performance.now() - started);
|
|
218
273
|
if (response.status !== 401 || typeof auth.refreshStale !== "function" || !staleCode(raw)) return { response, raw };
|
|
219
274
|
if (refreshed) return { response, raw };
|
|
220
275
|
// A cached token that is stale too is not adopted twice: the next one is refreshed.
|
|
@@ -525,16 +580,24 @@ export async function devExchange(method, path, bodyText, { contentType = "appli
|
|
|
525
580
|
if (!response.ok || payload.error === true) {
|
|
526
581
|
const waitMs = response.status === 429 ? retryAfterMs(response.headers?.get?.("retry-after")) : null;
|
|
527
582
|
const after = waitMs === null ? "" : ` Dev asks to wait ${Math.ceil(waitMs / 1000)} s before trying again.`;
|
|
528
|
-
throw
|
|
529
|
-
payload.code ?? `HTTP_${response.status}`,
|
|
530
|
-
`${payload.message ?? `Dev returned HTTP ${response.status}`}${after}`,
|
|
531
|
-
1,
|
|
532
|
-
payload.details,
|
|
533
|
-
);
|
|
583
|
+
throw devError(payload, response.status, after);
|
|
534
584
|
}
|
|
535
585
|
return { status: response.status, payload };
|
|
536
586
|
}
|
|
537
587
|
|
|
588
|
+
/**
|
|
589
|
+
* Dev's refusal as a CliError. VERSION_BELOW_FLOOR (426, O3 item 7, DEC-0569,
|
|
590
|
+
* MW5-8.1): this CLI is below Dev's floor, so the write was refused; Dev's
|
|
591
|
+
* message names the floor and the version, and the fix is printed under it
|
|
592
|
+
* (exit 2: the caller must act).
|
|
593
|
+
*/
|
|
594
|
+
export function devError(payload, status, after = "") {
|
|
595
|
+
const code = payload?.code ?? `HTTP_${status}`;
|
|
596
|
+
const message = `${payload?.message ?? `Dev returned HTTP ${status}`}${after}`;
|
|
597
|
+
if (code === "VERSION_BELOW_FLOOR") return new CliError(code, `${message}\nFix: nodii-dev harness update`, 2, payload.details);
|
|
598
|
+
return new CliError(code, message, 1, payload?.details);
|
|
599
|
+
}
|
|
600
|
+
|
|
538
601
|
export async function devRawRequest(method, path, bodyText, contentType = "application/json", options = {}) {
|
|
539
602
|
return (await devExchange(method, path, bodyText, { ...options, contentType })).payload;
|
|
540
603
|
}
|
|
@@ -545,7 +608,7 @@ export async function devTextRequest(method, path) {
|
|
|
545
608
|
if (response.ok) return raw;
|
|
546
609
|
let payload = {};
|
|
547
610
|
try { payload = JSON.parse(raw); } catch { payload = { message: raw }; }
|
|
548
|
-
throw
|
|
611
|
+
throw devError(payload, response.status);
|
|
549
612
|
}
|
|
550
613
|
|
|
551
614
|
export const devRequest = (method, path, body, options) =>
|
package/dist/figma-scope.js
CHANGED
|
@@ -250,7 +250,14 @@ export function assertKnownSets(surfaces, scopes) {
|
|
|
250
250
|
export function laneFigmaScope(lane) {
|
|
251
251
|
const stored = lane?.freeze?.boundaries?.figma;
|
|
252
252
|
if (Array.isArray(stored))
|
|
253
|
-
return stored.map((file) => ({
|
|
253
|
+
return stored.map((file) => ({
|
|
254
|
+
fileKey: file.fileKey,
|
|
255
|
+
componentSets: file.componentSetKeys ?? [],
|
|
256
|
+
...(file.creates?.length ? { creates: file.creates } : {}),
|
|
257
|
+
// hub-643: sections and pages the Freeze grants by node id.
|
|
258
|
+
...(file.sectionIds?.length ? { sections: grantedNodeIds(lane, "sectionIds", file.sectionIds) } : {}),
|
|
259
|
+
...(file.pageIds?.length ? { pages: grantedNodeIds(lane, "pageIds", file.pageIds) } : {}),
|
|
260
|
+
}));
|
|
254
261
|
const launch = lane?.launch?.figmaScopes;
|
|
255
262
|
if (!Array.isArray(launch) || !launch.length) return null;
|
|
256
263
|
try {
|
|
@@ -263,6 +270,18 @@ export function laneFigmaScope(lane) {
|
|
|
263
270
|
}
|
|
264
271
|
}
|
|
265
272
|
|
|
273
|
+
/**
|
|
274
|
+
* A Freeze's granted section or page ids (hub-643): plain top-level
|
|
275
|
+
* node ids, as `--scope section:ID` takes them. Anything else is refused, never
|
|
276
|
+
* read as a wider grant.
|
|
277
|
+
*/
|
|
278
|
+
function grantedNodeIds(lane, field, ids) {
|
|
279
|
+
const bad = ids.filter((id) => typeof id !== "string" || !/^\d+:\d+$/.test(id));
|
|
280
|
+
if (bad.length)
|
|
281
|
+
throw Object.assign(new CliError("FIGMA_SCOPE_INVALID", `Lane ${lane?.key ?? ""}'s Freeze grants ${field} that are not plain node ids (${bad.map((id) => JSON.stringify(id)).join(", ")}). Fix them with ${SWAP_BOUNDARIES(lane?.key)}.`, 1), { reason: `${field}: ${bad.join(", ")}` });
|
|
282
|
+
return [...ids];
|
|
283
|
+
}
|
|
284
|
+
|
|
266
285
|
/** The DS components (guideline keys) and Surfaces a scope covers. */
|
|
267
286
|
export function componentsForScope(surfaces, scope) {
|
|
268
287
|
const keys = new Set(scope.flatMap((file) => file.componentSets));
|
|
@@ -286,7 +305,7 @@ export function guidelineLookup(components) {
|
|
|
286
305
|
};
|
|
287
306
|
}
|
|
288
307
|
|
|
289
|
-
export const SWAP_BOUNDARIES = (key = "<key>") => `\`nodii-dev lane freeze swap ${key} --section boundaries --file BOUNDARIES.json --reason TEXT\` (the whole section: repos plus figma: [{fileKey, componentSetKeys, creates: [{pageId, name}]}]; start from \`nodii-dev lane freeze show ${key}\`)`;
|
|
308
|
+
export const SWAP_BOUNDARIES = (key = "<key>") => `\`nodii-dev lane freeze swap ${key} --section boundaries --file BOUNDARIES.json --reason TEXT\` (the whole section: repos plus figma: [{fileKey, componentSetKeys, creates: [{pageId, name}], sectionIds, pageIds}]; start from \`nodii-dev lane freeze show ${key}\`)`;
|
|
290
309
|
|
|
291
310
|
/** A create's name as Dev compares it (sameCreateName in the hub's scopes.ts). */
|
|
292
311
|
export const createName = (name) =>
|
|
@@ -365,16 +384,22 @@ export async function assertWithinLaneScope(scope, fileKey, lockScopes, { catalo
|
|
|
365
384
|
if (!file)
|
|
366
385
|
throw outside(`${fileKey} is outside this lane's Figma scope (${scope.length ? scope.map((item) => item.fileKey).join(", ") : "no Figma files"}).`, { fileKey, scope });
|
|
367
386
|
const creates = file.creates ?? [];
|
|
368
|
-
|
|
387
|
+
const sections = file.sections ?? [];
|
|
388
|
+
const pages = file.pages ?? [];
|
|
389
|
+
if (lockScopes === null || (!file.componentSets.length && !creates.length && !sections.length && !pages.length)) return { checked: true, fileKey };
|
|
369
390
|
// DS-254: a create the Freeze grants, on its page and under its name.
|
|
370
391
|
// A name with no letters or digits names nothing, so it matches nothing.
|
|
371
392
|
const granted = (item) => Boolean(item.pageId && createName(item.name ?? "")) && creates.some((create) => create.pageId === item.pageId && createName(create.name ?? "") === createName(item.name));
|
|
372
393
|
const ungranted = lockScopes.filter((item) => item.kind === "create" && !granted(item));
|
|
373
394
|
if (ungranted.length)
|
|
374
395
|
throw outside(`${ungranted.map((item) => `create "${item.name}" on page ${item.pageId}`).join(", ")} in ${fileKey} is not a create this lane's Freeze grants (${creates.length ? creates.map((create) => `"${create.name}" on page ${create.pageId}`).join(", ") : "none"}).`, { fileKey, scope: file });
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
396
|
+
// hub-643: a section or page the Freeze grants by id, exactly.
|
|
397
|
+
const grantedNode = (item) => (item.kind === "section" && sections.includes(item.nodeId)) || (item.kind === "page" && pages.includes(item.nodeId));
|
|
398
|
+
const wide = lockScopes.length ? lockScopes.filter((item) => item.kind !== "component" && item.kind !== "create" && !grantedNode(item)) : [{ kind: "file" }];
|
|
399
|
+
if (wide.length) {
|
|
400
|
+
const grants = [creates.length && "granted creates", sections.length && `granted sections (${sections.join(", ")})`, pages.length && `granted pages (${pages.join(", ")})`].filter(Boolean);
|
|
401
|
+
throw outside(`This lane may lock only its component sets${grants.length ? ` and ${grants.join(" and ")}` : ""} in ${fileKey}, not ${wide.map((item) => (item.nodeId ? `${item.kind} ${item.nodeId}` : item.kind)).join(", ")}.`, { fileKey, scope: file });
|
|
402
|
+
}
|
|
378
403
|
lockScopes = lockScopes.filter((item) => item.kind === "component");
|
|
379
404
|
if (!lockScopes.length) return { checked: true, fileKey };
|
|
380
405
|
// Surfaces first; a DS set's key is looked up only when a node is still unaccounted for.
|
package/dist/flags.js
CHANGED
|
@@ -16,9 +16,6 @@ export const COMMAND_FLAGS = {
|
|
|
16
16
|
"figma transfer": ["to", "reason"],
|
|
17
17
|
"coordinator start": ["machine", "account", "heartbeat-seconds"],
|
|
18
18
|
"coordinator items": ["machine"],
|
|
19
|
-
"lane ask": ["question", "options"],
|
|
20
|
-
"lane asks": ["machine", "state", "lane", "cursor", "limit"],
|
|
21
|
-
"lane answer": ["text"],
|
|
22
19
|
// NODII-DEV-CLI-191: lane-to-lane messaging.
|
|
23
20
|
"lane message": [...BODY, "issue"],
|
|
24
21
|
"lane inbox": ["all"],
|
|
@@ -51,7 +48,10 @@ export const COMMAND_FLAGS = {
|
|
|
51
48
|
"lane ready": ["withdraw", "reason"],
|
|
52
49
|
"lane cap": ["confirm-raise", "reason"],
|
|
53
50
|
"lane heartbeat": ["note", "waiting-on"],
|
|
54
|
-
"lane waits": ["machine"],
|
|
51
|
+
"lane waits": ["machine", "person"],
|
|
52
|
+
// O3 items 9 and 12 (DEC-0569, MW1-115): --text and --scratch are the new flags.
|
|
53
|
+
"ruling file": ["text"],
|
|
54
|
+
"steward register": ["focus", "repos", "side", "key", "scratch"],
|
|
55
55
|
"lane resume": ["override", "reason", "host-lost", "min-free-gb", "stagger-seconds", "profile", "class", "if-changed", "ungated"],
|
|
56
56
|
"lane transfer": ["reason", "to-agent"],
|
|
57
57
|
"inbox ack": ["note"],
|
|
@@ -69,6 +69,8 @@ export const COMMAND_FLAGS = {
|
|
|
69
69
|
"operator step-up": ["revoke"],
|
|
70
70
|
"lane land": [],
|
|
71
71
|
"lane verify": ["dev-check", "checks"],
|
|
72
|
+
// O3 item 4: the weekly page takes only --json.
|
|
73
|
+
"harness week": [],
|
|
72
74
|
"repo policy": ["root"],
|
|
73
75
|
"test affected": ["base", "max-light", "run"],
|
|
74
76
|
"repo lint": ["root"],
|
package/dist/harness.js
CHANGED
|
@@ -573,10 +573,113 @@ export async function harnessCommand(action, flags, { request = devRequest, cont
|
|
|
573
573
|
// current dispatcher (its lane-free nudges included), with no sudo.
|
|
574
574
|
const refreshed = claudeBundle ? [] : await refreshManaged(managedHome ? { home: managedHome } : {}).catch(() => []);
|
|
575
575
|
const refreshText = refreshed.length ? `\nRefreshed the managed hook dispatcher in ${refreshed.join(", ")}.` : "";
|
|
576
|
-
const managedCliText = !managedCli ? ""
|
|
576
|
+
const managedCliText = (!managedCli ? ""
|
|
577
577
|
: managedCli.error ? `\nwarning: the managed nodii-dev was not updated: ${managedCli.error}`
|
|
578
578
|
: managedCli.current ? `\nThe managed nodii-dev is at the latest release, ${managedCli.version}.`
|
|
579
|
-
: `\nInstalled the managed nodii-dev ${managedCli.version}${managedCli.previous ? ` over ${managedCli.previous}` : ""} at ${managedCli.cliPath}
|
|
579
|
+
: `\nInstalled the managed nodii-dev ${managedCli.version}${managedCli.previous ? ` over ${managedCli.previous}` : ""} at ${managedCli.cliPath}.`)
|
|
580
|
+
+ (managedCli?.movedFrom ? `\nMoved the managed nodii-dev from ${managedCli.movedFrom}, a prefix this user cannot write, to ${managedCli.cliPath}; no root was used. Put ${managedCli.cliPath.replace(/\/lib\/node_modules\/@nodii\/dev\/bin\/nodii-dev$/, "/bin")} first on PATH so \`command -v nodii-dev\` names it.` : "");
|
|
580
581
|
const claudeData = claudePlan ? { claudeManagedDir: claudeBundle.dir, claudeManaged: { state: claudePlan.state, target: claudePlan.target, systemCommands: claudePlan.commands } } : {};
|
|
581
582
|
return { payload: { data: { ...summary, applied: true, ...(systemCommands.length ? { systemCommands: [...systemCommands, ...(claudePlan?.commands ?? [])], managedDir: managedBundle.dir } : {}), ...claudeData, ...(refreshed.length ? { managedDispatchRefreshed: refreshed } : {}), ...(managedCli ? { managedCli } : {}) } }, human: `${lines.join("\n")}\n${machineOnly ? "No harness in this directory: refreshed this machine's managed hooks only, and wrote no repository files." : plan.changes.length ? `${action === "install" ? "Installed" : "Updated"}: ${plan.changes.length} change${plan.changes.length === 1 ? "" : "s"}.` : "Harness already current."}${systemText}${refreshText}${managedCliText}` };
|
|
582
583
|
}
|
|
584
|
+
|
|
585
|
+
// ─── harness week (O3 item 4, MW5-8.1, DEC-0569) ────────────────────────────
|
|
586
|
+
// The weekly page for someone who does not build: Dev computes every number
|
|
587
|
+
// (GET /harness/week) and this prints them as plain text, in a fixed order, so
|
|
588
|
+
// the same answer always reads the same. --json prints Dev's payload.
|
|
589
|
+
|
|
590
|
+
export const WEEK_USAGE = "harness week [--json]";
|
|
591
|
+
|
|
592
|
+
/** 3d 4h, 2h 5m, 4m 10s, 9s. */
|
|
593
|
+
export function weekDuration(seconds) {
|
|
594
|
+
const s = Math.max(0, Math.round(Number(seconds) || 0));
|
|
595
|
+
const d = Math.floor(s / 86_400), h = Math.floor((s % 86_400) / 3600), m = Math.floor((s % 3600) / 60);
|
|
596
|
+
if (d) return `${d}d ${h}h`;
|
|
597
|
+
if (h) return `${h}h ${m}m`;
|
|
598
|
+
if (m) return `${m}m ${s % 60}s`;
|
|
599
|
+
return `${s}s`;
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
const dash = (value) => (value === null || value === undefined || value === "" ? "-" : String(value));
|
|
603
|
+
const count = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
|
|
604
|
+
const tokensText = (n) => (typeof n === "number" ? `${n} tokens` : "tokens not recorded");
|
|
605
|
+
|
|
606
|
+
/** Rows as columns padded to their widest cell; the last column is not padded. */
|
|
607
|
+
function columns(rows, indent = " ") {
|
|
608
|
+
const widths = rows[0]?.map((_, i) => Math.max(...rows.map((r) => String(r[i]).length))) ?? [];
|
|
609
|
+
return rows.map((r) => indent + r.map((cell, i) => (i === r.length - 1 ? String(cell) : String(cell).padEnd(widths[i]))).join(" ").trimEnd());
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
const meanText = (c) => (c?.n ? `${Math.round(((c.meanMs ?? c.ms / c.n) || 0) * 10) / 10} ms` : "-");
|
|
613
|
+
const costCell = (c) => `${c?.n ?? 0} calls, ${Math.round((c?.ms ?? 0) * 10) / 10} ms, mean ${meanText(c)}`;
|
|
614
|
+
|
|
615
|
+
export function renderWeek(week) {
|
|
616
|
+
const w = week ?? {};
|
|
617
|
+
const machineNames = new Map((w.versions?.machines ?? []).map((m) => [m.machineId, m.name]));
|
|
618
|
+
for (const m of w.runs?.perMachine ?? []) if (m.machineId && m.name) machineNames.set(m.machineId, m.name);
|
|
619
|
+
const machineName = (id) => (id ? machineNames.get(id) ?? id : "no machine");
|
|
620
|
+
const out = [`The week from ${dash(w.window?.since)} to ${dash(w.window?.until)}`];
|
|
621
|
+
const section = (title, lines) => out.push("", title, ...(lines.length ? lines : [" none"]));
|
|
622
|
+
|
|
623
|
+
section("Run-hours that pushed nothing, by how the run ended", columns((w.classes ?? []).map((c) =>
|
|
624
|
+
[c.class, count(c.runs, "run"), `${c.runHours} h`, tokensText(c.tokens)])));
|
|
625
|
+
|
|
626
|
+
const waits = w.waits;
|
|
627
|
+
section("Waits, as of now", waits ? [
|
|
628
|
+
` unknown: ${count(waits.unknown.lanes, "lane")} waiting on ${count(waits.unknown.targets, "PR or release", "PRs or releases")} Dev traced to no lane`,
|
|
629
|
+
` claimed: ${count(waits.claimed.lanes, "lane")} (on lanes ${waits.claimed.onLanes}, operator questions ${waits.claimed.operatorQuestions}, decisions ${waits.claimed.decisions}, launch day ${waits.claimed.launchDay}, roles ${waits.claimed.persons})`,
|
|
630
|
+
] : []);
|
|
631
|
+
|
|
632
|
+
const r = w.refusals;
|
|
633
|
+
const top = (label, list, name = dash) => ` by ${label}: ${(list ?? []).length ? list.map((x) => `${name(x.key)} ${x.count}`).join(", ") : "none"}`;
|
|
634
|
+
section(`Refusals: ${r?.total ?? 0}`, r && r.total ? [top("code", r.byCode), top("route", r.byRoute), top("caller", r.byCaller), top("machine", r.byMachine, machineName)] : []);
|
|
635
|
+
|
|
636
|
+
section("Hours main was red, per repository", [
|
|
637
|
+
...columns((w.red?.repos ?? []).map((x) => [x.repo, `${x.hoursRed} h`, x.redNow ? "red now" : ""])),
|
|
638
|
+
...(w.red?.source ? [` (${w.red.source})`] : []),
|
|
639
|
+
]);
|
|
640
|
+
|
|
641
|
+
section("Lanes by state, as of now", columns((w.states ?? []).map((s) => [s.state, s.count, `oldest ${weekDuration(s.oldestAgeSeconds)}`])));
|
|
642
|
+
|
|
643
|
+
const b = w.baselines;
|
|
644
|
+
const baselineRows = (list) => columns((list ?? []).map((x) => [x.repo, String(x.mergeBase).slice(0, 12), x.measuredAt,
|
|
645
|
+
`${count(x.counts?.files ?? 0, "file")}, ${x.counts?.red ?? 0} red${x.red?.length ? `: ${x.red.join(", ")}` : ""}`]));
|
|
646
|
+
section("Test baselines at main's merge base", !b ? [` ${w.baselinesReason ?? "not reported"}`] : [
|
|
647
|
+
...baselineRows(b.repos),
|
|
648
|
+
...(b.scratch?.length ? [" scratch (a local path, in no total):", ...baselineRows(b.scratch).map((l) => ` ${l}`)] : []),
|
|
649
|
+
...(b.totals ? [` total: ${count(b.totals.baselines, "baseline")}, ${b.totals.withRed} with red, ${count(b.totals.redFiles, "red file")}`] : []),
|
|
650
|
+
]);
|
|
651
|
+
|
|
652
|
+
const cost = w.callCost;
|
|
653
|
+
section("Dev calls per machine", !cost ? [` ${w.callCostReason ?? "not reported"}`] : [
|
|
654
|
+
...columns([["machine", "since", "hook", "gather", "command"], ...(cost.machines ?? []).map((m) => [m.name, m.since, costCell(m.hook), costCell(m.gather), costCell(m.command)])]),
|
|
655
|
+
...(cost.basis ? [` (${cost.basis})`] : []),
|
|
656
|
+
]);
|
|
657
|
+
|
|
658
|
+
const v = w.versions ?? {};
|
|
659
|
+
section("CLI versions", [
|
|
660
|
+
` target ${dash(v.target)}, floor ${dash(v.floor)}`,
|
|
661
|
+
...columns((v.machines ?? []).map((m) => [m.name, m.cliVersion ?? "no version", m.needsRoot === true ? "needs root" : ""])),
|
|
662
|
+
` needs root: ${(v.needRoot ?? []).length ? v.needRoot.join(", ") : "none"}`,
|
|
663
|
+
]);
|
|
664
|
+
|
|
665
|
+
section("Runs per machine", columns((w.runs?.perMachine ?? []).map((m) => [m.name ?? machineName(m.machineId), count(m.runs, "run"), `${m.scratchRuns} scratch`])));
|
|
666
|
+
|
|
667
|
+
if (w.rulings) section("Rulings", [` filed: ${w.rulings.filed}`]);
|
|
668
|
+
|
|
669
|
+
const list = w.runs?.list ?? [];
|
|
670
|
+
section(`Runs (${list.length}${w.runs?.truncated ? ", more not shown" : ""})`, list.length ? columns([
|
|
671
|
+
["lane", "step", "started because", "tokens", "duration", "ended", "machine"],
|
|
672
|
+
...list.map((x) => [
|
|
673
|
+
`${x.laneKey ?? `(${x.kind})`}${x.scratch ? " [scratch]" : ""}`,
|
|
674
|
+
dash(x.facts?.step), dash(x.facts?.startReason), dash(x.facts?.tokens), weekDuration(x.durationSeconds),
|
|
675
|
+
`${x.endingClass ?? "running"}${x.pushed ? ", pushed" : ""}`, x.machineName ?? machineName(x.machineId),
|
|
676
|
+
]),
|
|
677
|
+
]) : []);
|
|
678
|
+
return out.join("\n");
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
export async function harnessWeekCommand(rest, flags, { request = devRequest } = {}) {
|
|
682
|
+
if (rest.length) throw new CliError("USAGE", `harness week takes no arguments, got: ${rest.join(" ")}. ${WEEK_USAGE}`, 2);
|
|
683
|
+
const payload = await request("GET", "/api/v1/harness/week");
|
|
684
|
+
return { payload, human: () => renderWeek(payload?.data) };
|
|
685
|
+
}
|