@nodii/dev 0.6.132 → 0.6.134
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 +22 -0
- package/dist/cdp.js +138 -0
- package/dist/chrome.js +359 -0
- package/dist/cli.js +51 -4
- package/dist/coordinator-board.js +490 -0
- package/dist/coordinator-watch.js +564 -0
- package/dist/core.js +1 -1
- package/dist/figma-publish.js +207 -0
- package/dist/figma.js +7 -4
- package/dist/flags.js +1 -0
- package/dist/governor.js +3 -1
- package/package.json +1 -1
|
@@ -0,0 +1,490 @@
|
|
|
1
|
+
// nodii-dev coordinator board: the "What's running" section of the operator's
|
|
2
|
+
// sheet (MW4-31: nodii-infra docs/open/<coordinator>.md) and the lanes at the
|
|
3
|
+
// top of "What needs you", built from Dev's real state.
|
|
4
|
+
//
|
|
5
|
+
// "Waiting on" never reads the lane's note text. It comes from: the lane's
|
|
6
|
+
// status (on_dev/non_issue are done), the change sets the lane holds (their
|
|
7
|
+
// state and pending items), Dev's wait records, the heavy-slot queue, and the
|
|
8
|
+
// coordinator's answered.md. The note is shown in its own column, as written.
|
|
9
|
+
//
|
|
10
|
+
// --write merges the section from a worktree of nodii-infra, after harvesting
|
|
11
|
+
// any answers the operator typed in their checkout (verbatim into answered.md),
|
|
12
|
+
// then fast-forwards the operator's checkout. An empty or collapsed board is
|
|
13
|
+
// never written.
|
|
14
|
+
import { execFile as execFileCallback } from "node:child_process";
|
|
15
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
16
|
+
import { homedir } from "node:os";
|
|
17
|
+
import { basename, dirname, join } from "node:path";
|
|
18
|
+
import { promisify } from "node:util";
|
|
19
|
+
import { fileURLToPath } from "node:url";
|
|
20
|
+
import { CliError, devRequest, encode, query, readConfig } from "./core.js";
|
|
21
|
+
import { governorMachineId } from "./governor.js";
|
|
22
|
+
|
|
23
|
+
const execFile = promisify(execFileCallback);
|
|
24
|
+
export const coordinatorHome = (home = homedir()) => join(home, ".config", "nodii-dev", "coordinator");
|
|
25
|
+
const settingsPath = (home) => join(coordinatorHome(home), "settings.json");
|
|
26
|
+
|
|
27
|
+
export const RUNNING_START = "<!-- RUNNING:START -->";
|
|
28
|
+
export const RUNNING_END = "<!-- RUNNING:END -->";
|
|
29
|
+
export const NEEDS_START = "<!-- NEEDS-YOU:START -->";
|
|
30
|
+
export const NEEDS_END = "<!-- NEEDS-YOU:END -->";
|
|
31
|
+
const DONE_STATUSES = new Set(["on_dev", "non_issue"]);
|
|
32
|
+
const SHOWN_STATUSES = new Set(["queued", "building", "built", "review", "on_main"]);
|
|
33
|
+
// Finished lanes stay on the board, as done, for a day.
|
|
34
|
+
export const DONE_SHOWN_MS = 24 * 60 * 60_000;
|
|
35
|
+
|
|
36
|
+
// The coordinator's priority domains, in the operator's order (hub-405).
|
|
37
|
+
// Dev has no domain field, so this is coordinator configuration: settings.json
|
|
38
|
+
// may replace it with its own { "domains": [{ "name", "prefixes" }] }.
|
|
39
|
+
export const DEFAULT_DOMAINS = [
|
|
40
|
+
{ name: "Generator", prefixes: ["gen-", "ds-gen-", "surf-", "kyc-gen", "tm-surfaces"] },
|
|
41
|
+
{ name: "Frontend adoption", prefixes: ["fe-adopt"] },
|
|
42
|
+
{ name: "Procedure", prefixes: ["hub-methodology", "hub-controls", "cli-gather", "cli-coordinator", "hub-dev-friction"] },
|
|
43
|
+
{ name: "Build promotion", prefixes: ["gen-hub-", "hub-prod", "crit-edge-42", "cli-heavy", "hub-ci", "fe-release"] },
|
|
44
|
+
{ name: "RBAC", prefixes: ["rbac-", "ds-rbac-", "crit-"] },
|
|
45
|
+
];
|
|
46
|
+
|
|
47
|
+
export async function readCoordinatorSettings(home = homedir()) {
|
|
48
|
+
try { return JSON.parse(await readFile(settingsPath(home), "utf8")); }
|
|
49
|
+
catch (error) { if (error?.code === "ENOENT") return {}; throw error; }
|
|
50
|
+
}
|
|
51
|
+
export async function saveCoordinatorSettings(value, home = homedir()) {
|
|
52
|
+
await mkdir(coordinatorHome(home), { recursive: true, mode: 0o700 });
|
|
53
|
+
await writeFile(settingsPath(home), `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The lane's domain. The most specific prefix wins, so gen-hub-* is Build promotion, not Generator. */
|
|
57
|
+
export function laneDomain(key, domains = DEFAULT_DOMAINS) {
|
|
58
|
+
let best = null;
|
|
59
|
+
for (const domain of domains)
|
|
60
|
+
for (const prefix of domain.prefixes)
|
|
61
|
+
if (key.startsWith(prefix) && (!best || prefix.length > best.prefix.length)) best = { name: domain.name, prefix };
|
|
62
|
+
return best?.name ?? null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Every lane on the machine, all pages. */
|
|
66
|
+
export async function machineLanes(machineId, { request = devRequest } = {}) {
|
|
67
|
+
const lanes = [];
|
|
68
|
+
let cursor;
|
|
69
|
+
do {
|
|
70
|
+
const page = await request("GET", `/api/v1/lanes${query({ machine: machineId, cursor, limit: 200 })}`);
|
|
71
|
+
lanes.push(...(page.data ?? []));
|
|
72
|
+
cursor = page.nextCursor ?? page.next ?? undefined;
|
|
73
|
+
} while (cursor);
|
|
74
|
+
return lanes;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Open change sets, and those published in the last day, with their holder lane. */
|
|
78
|
+
export async function liveChangeSets({ request = devRequest, now = Date.now } = {}) {
|
|
79
|
+
const params = new URLSearchParams({ limit: "200" });
|
|
80
|
+
for (const state of ["editing", "in_review", "applying", "awaiting_publish"]) params.append("state", state);
|
|
81
|
+
const open = (await request("GET", `/api/v1/design/change-sets?${params}`)).data ?? [];
|
|
82
|
+
const recent = new URLSearchParams({ limit: "200", state: "published" });
|
|
83
|
+
const published = ((await request("GET", `/api/v1/design/change-sets?${recent}`).catch(() => ({ data: [] }))).data ?? [])
|
|
84
|
+
.filter((set) => now() - Date.parse(set.updatedAt ?? set.closedAt ?? 0) < DONE_SHOWN_MS);
|
|
85
|
+
return [...open, ...published].map((set) => ({
|
|
86
|
+
id: set.id, state: set.state, title: set.title, fileKey: set.fileKey, actionable: set.actionable, blockedBy: set.blockedBy,
|
|
87
|
+
pending: set.itemCounts?.pending ?? null, updatedAt: set.updatedAt,
|
|
88
|
+
holderLane: String(set.holder?.agent?.displayName ?? set.holder ?? "").replace(/^lane-/, "") || null,
|
|
89
|
+
}));
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** The heavy-slot queue as lane keys: who holds a slot and who waits for one. */
|
|
93
|
+
export function parseHeavyStatus(text, cwdOf = () => null) {
|
|
94
|
+
const holding = new Map();
|
|
95
|
+
const queued = new Map();
|
|
96
|
+
for (const line of String(text).split("\n")) {
|
|
97
|
+
// v26 names the lane itself (" lane KEY"); older copies only the worktree.
|
|
98
|
+
const slot = line.match(/^\s+slot \d+ pid (\d+) for (\d+)s(?: lane (\S+))?: (\S+)/);
|
|
99
|
+
if (slot) {
|
|
100
|
+
const key = slot[3] ?? slot[4].match(/\/worktrees\/([^/ ]+)/)?.[1];
|
|
101
|
+
if (key) holding.set(key, { pid: Number(slot[1]), seconds: Number(slot[2]) });
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
const wait = line.match(/^\s+queued \d+: pid (\d+) waiting (\d+)s/);
|
|
105
|
+
if (wait) {
|
|
106
|
+
const key = String(cwdOf(Number(wait[1])) ?? "").match(/\/worktrees\/([^/ ]+)/)?.[1];
|
|
107
|
+
if (key) queued.set(key, { pid: Number(wait[1]), seconds: Number(wait[2]) });
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return { holding, queued };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export async function heavyQueue({ execute = execFile } = {}) {
|
|
114
|
+
const slot = join(dirname(fileURLToPath(import.meta.url)), "heavy-slot.sh");
|
|
115
|
+
let text = "";
|
|
116
|
+
try { text = (await execute("/bin/bash", [slot, "--status"], { timeout: 20_000 })).stdout; } catch { return { holding: new Map(), queued: new Map() }; }
|
|
117
|
+
const cwds = new Map();
|
|
118
|
+
for (const pid of [...text.matchAll(/queued \d+: pid (\d+)/g)].map((m) => Number(m[1]))) {
|
|
119
|
+
try { cwds.set(pid, (await execute("lsof", ["-a", "-p", String(pid), "-d", "cwd", "-Fn"])).stdout.split("\n").find((l) => l.startsWith("n"))?.slice(1)); } catch {}
|
|
120
|
+
}
|
|
121
|
+
return parseHeavyStatus(text, (pid) => cwds.get(pid));
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** This machine's lane processes, from the watchdog's run records: lane key -> alive. */
|
|
125
|
+
export async function laneProcesses({ readRuns, isAlive } = {}) {
|
|
126
|
+
const watchdog = await import("./watchdog.js");
|
|
127
|
+
const read = await (readRuns ?? watchdog.readWatchedRuns)();
|
|
128
|
+
const records = Array.isArray(read) ? read : read?.records ?? [];
|
|
129
|
+
const newest = new Map();
|
|
130
|
+
for (const record of records) {
|
|
131
|
+
const key = record.worktree?.match(/\/worktrees\/([^/]+)$/)?.[1];
|
|
132
|
+
if (!key) continue;
|
|
133
|
+
const prior = newest.get(key);
|
|
134
|
+
if (!prior || String(record.recordedAt) > String(prior.recordedAt)) newest.set(key, record);
|
|
135
|
+
}
|
|
136
|
+
const alive = new Map();
|
|
137
|
+
for (const [key, record] of newest) alive.set(key, await (isAlive ?? watchdog.isProcessAlive)(record.pid, record.processStartedAt).catch(() => false));
|
|
138
|
+
return alive;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** The item ids of the sheet's open asks: its "## ID: title" headings. */
|
|
142
|
+
export function sheetItemIds(sheet) {
|
|
143
|
+
return new Set([...String(sheet ?? "").matchAll(/^## ([A-Z][A-Za-z]*-?\d+)\b/gm)].map((m) => m[1]));
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Question and item ids the operator has answered, from answered.md. */
|
|
147
|
+
export function answeredIds(text) {
|
|
148
|
+
return new Set([...String(text ?? "").matchAll(/\b(Q-\d+|[A-Z]{1,2}\d{1,3})\b/g)].map((m) => m[1]));
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const short = (value, n) => {
|
|
152
|
+
const text = String(value ?? "").replace(/\s+/g, " ").replaceAll("|", "/").trim();
|
|
153
|
+
return text.length > n ? `${text.slice(0, n - 1)}…` : text;
|
|
154
|
+
};
|
|
155
|
+
const hhmm = (iso) => (iso ? `${String(iso).slice(11, 16)}Z` : "");
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* What the lane is waiting on, from real state only. `you` marks a lane that
|
|
159
|
+
* genuinely needs the operator now.
|
|
160
|
+
*/
|
|
161
|
+
export function waitingOn(lane, { sets = [], heavy = { holding: new Map(), queued: new Map() }, answered = new Set(), sheetItems = new Set(), lanesByKey = new Map(), alive } = {}) {
|
|
162
|
+
if (DONE_STATUSES.has(lane.status)) return { text: lane.status === "on_dev" ? "✅ done (on Dev)" : "✅ done (not an issue)", done: true };
|
|
163
|
+
const held = sets.filter((set) => set.holderLane === lane.key);
|
|
164
|
+
const review = held.find((set) => set.state === "in_review" && (set.pending ?? 1) > 0);
|
|
165
|
+
if (review) {
|
|
166
|
+
if (review.actionable === false && review.blockedBy) return { text: `queued: ${review.id} waits behind ${review.blockedBy} (MW8-4.1)` };
|
|
167
|
+
return { text: `**you**: review ${review.id} (${review.pending ?? "?"} pending)`, you: true, set: review.id };
|
|
168
|
+
}
|
|
169
|
+
const applying = held.find((set) => set.state === "applying");
|
|
170
|
+
if (applying) return { text: `you: done ✓ (${applying.id} decided; lane applies it)` };
|
|
171
|
+
const awaiting = held.find((set) => set.state === "awaiting_publish");
|
|
172
|
+
if (awaiting) return { text: `you: done ✓ (${awaiting.id} applied; coordinator publishes)` };
|
|
173
|
+
const published = held.find((set) => set.state === "published");
|
|
174
|
+
if (lane.status === "building" && published && !held.some((set) => ["editing", "in_review"].includes(set.state)))
|
|
175
|
+
return { text: `you: done ✓ (${published.id} published; lane catching up)` };
|
|
176
|
+
if (lane.status === "on_main") return { text: "release and deploy (steward)" };
|
|
177
|
+
if (lane.status === "built") return { text: "dev check (lane)" };
|
|
178
|
+
for (const wait of lane.waits ?? []) {
|
|
179
|
+
const ref = wait.targetRef ?? "";
|
|
180
|
+
if (wait.targetKind === "question" || /^Q-\d+$/.test(ref)) {
|
|
181
|
+
// An ask is the operator's only when it is an open item on the sheet (MW4-31).
|
|
182
|
+
if (answered.has(ref)) return { text: `you: done ✓ (${ref} answered)` };
|
|
183
|
+
if (sheetItems.has(ref)) return { text: `**you**: ${ref} on the sheet`, you: true };
|
|
184
|
+
return { text: `question ${ref} (not on the sheet; coordinator checks it)` };
|
|
185
|
+
}
|
|
186
|
+
if (wait.targetKind === "lane" && wait.blockerLaneKey) {
|
|
187
|
+
const blocker = lanesByKey.get(wait.blockerLaneKey);
|
|
188
|
+
if (!blocker || !DONE_STATUSES.has(blocker.status)) return { text: `lane ${wait.blockerLaneKey}` };
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
if (wait.targetKind === "pr") return { text: `PR ${ref.replace(/^cognion-nucleus\//, "")}` };
|
|
192
|
+
if (wait.targetKind === "launch_day") return { text: "launch day" };
|
|
193
|
+
if (ref) return { text: ref };
|
|
194
|
+
}
|
|
195
|
+
const slot = heavy.holding.get(lane.key);
|
|
196
|
+
if (slot) return { text: `tests (heavy slot, ${Math.round(slot.seconds / 60)} min)` };
|
|
197
|
+
const queued = heavy.queued.get(lane.key);
|
|
198
|
+
if (queued) return { text: `tests (queued ${Math.round(queued.seconds / 60)} min)` };
|
|
199
|
+
if (lane.status === "building" && alive && alive.get(lane.key) === false) return { text: "coordinator: resume (process down)" };
|
|
200
|
+
return { text: "—" };
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** The lane's newest note, as written, and the coordinator's newest amendment. */
|
|
204
|
+
export function laneNotes(detail) {
|
|
205
|
+
const notes = (detail?.events ?? []).filter((e) => typeof e?.metadata?.note === "string" && e.metadata.note.trim() && !/Freeze over cap/.test(e.metadata.note));
|
|
206
|
+
const note = notes.at(-1);
|
|
207
|
+
const amendment = (detail?.amendments ?? []).at(-1);
|
|
208
|
+
return {
|
|
209
|
+
note: note ? `${hhmm(note.createdAt)} ${note.metadata.note}` : "",
|
|
210
|
+
action: amendment ? `${hhmm(amendment.createdAt)} ${amendment.reason ?? ""}`.trim() : "",
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
async function mapLimit(items, limit, fn) {
|
|
215
|
+
const out = new Array(items.length);
|
|
216
|
+
let next = 0;
|
|
217
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
|
|
218
|
+
while (next < items.length) { const i = next++; out[i] = await fn(items[i]); }
|
|
219
|
+
}));
|
|
220
|
+
return out;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Everything the board shows, from Dev and this machine. */
|
|
224
|
+
export async function collectBoard({
|
|
225
|
+
request = devRequest, config = readConfig, now = Date.now, domains, answeredText = "", sheetText = "", heavy, processes, sets, machineId,
|
|
226
|
+
} = {}) {
|
|
227
|
+
const machine = machineId ?? (await governorMachineId({}, { request, config }));
|
|
228
|
+
const all = await machineLanes(machine, { request });
|
|
229
|
+
const lanesByKey = new Map(all.map((lane) => [lane.key, lane]));
|
|
230
|
+
const shown = all.filter((lane) =>
|
|
231
|
+
!lane.key.startsWith("steward-") &&
|
|
232
|
+
(SHOWN_STATUSES.has(lane.status) || (DONE_STATUSES.has(lane.status) && now() - Date.parse(lane.updatedAt ?? 0) < DONE_SHOWN_MS)));
|
|
233
|
+
const changeSets = sets ?? (await liveChangeSets({ request, now }));
|
|
234
|
+
const heavyState = heavy ?? (await heavyQueue());
|
|
235
|
+
const alive = processes ?? (await laneProcesses());
|
|
236
|
+
const answered = answeredIds(answeredText);
|
|
237
|
+
const sheetItems = sheetItemIds(sheetText);
|
|
238
|
+
const domainList = domains ?? DEFAULT_DOMAINS;
|
|
239
|
+
const rows = await mapLimit(shown, 6, async (lane) => {
|
|
240
|
+
const detail = (await request("GET", `/api/v1/lanes/${encode(lane.key)}`).catch(() => ({ data: null }))).data;
|
|
241
|
+
const { note, action } = laneNotes(detail);
|
|
242
|
+
const step = lane.side === "frontend" ? lane.currentFrontendStep : lane.currentBackendStep ?? lane.currentFrontendStep;
|
|
243
|
+
const process = DONE_STATUSES.has(lane.status) ? "ended" : alive.has(lane.key) ? (alive.get(lane.key) ? "running" : "**down**") : lane.liveness === "active" ? "running" : `**${lane.liveness ?? "down"}**`;
|
|
244
|
+
const wait = waitingOn(lane, { sets: changeSets, heavy: heavyState, answered, sheetItems, lanesByKey, alive });
|
|
245
|
+
return {
|
|
246
|
+
key: lane.key, domain: laneDomain(lane.key, domainList), title: lane.title ?? "", status: lane.status,
|
|
247
|
+
step: `${lane.side ?? ""}/${step ?? lane.status}`, process, waiting: wait, action: `${action}${lane.status === "on_dev" ? " · on Dev" : ""}`.trim(), note,
|
|
248
|
+
};
|
|
249
|
+
});
|
|
250
|
+
return { at: new Date(now()).toISOString(), machineId: machine, rows, domains: domainList.map((d) => d.name) };
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** The RUNNING block and the NEEDS-YOU block, as markdown. */
|
|
254
|
+
export function renderBoard(board, { coordinator = "coordinator" } = {}) {
|
|
255
|
+
const at = hhmm(board.at);
|
|
256
|
+
const lines = [RUNNING_START, `## 1. What's running (nodii-dev coordinator board, every 15 min; last ${at})`, ""];
|
|
257
|
+
const groups = [...board.domains, null];
|
|
258
|
+
for (const domain of groups) {
|
|
259
|
+
const rows = board.rows.filter((row) => row.domain === domain).sort((a, b) => a.key.localeCompare(b.key));
|
|
260
|
+
if (!rows.length) continue;
|
|
261
|
+
if (domain === null) {
|
|
262
|
+
lines.push("", `**Other lanes on this machine:** ${rows.map((row) => `${row.key} (${short(row.waiting.text, 40)})`).join(", ")}`, "");
|
|
263
|
+
continue;
|
|
264
|
+
}
|
|
265
|
+
lines.push("", `**${domain}**`, "", `| Lane | Doing | Step | Process | Waiting on | ${coordinator}'s last action | Lane's last note |`, "|---|---|---|---|---|---|---|");
|
|
266
|
+
for (const row of rows)
|
|
267
|
+
lines.push(`| ${row.key} | ${short(row.title, 70)} | ${short(row.step, 30)} | ${row.process} | ${short(row.waiting.text, 70)} | ${short(row.action, 50)} | ${short(row.note, 110)} |`);
|
|
268
|
+
}
|
|
269
|
+
lines.push("", RUNNING_END);
|
|
270
|
+
const you = board.rows.filter((row) => row.waiting.you).sort((a, b) => a.key.localeCompare(b.key));
|
|
271
|
+
const needs = [NEEDS_START, ...(you.length
|
|
272
|
+
? [`**Lanes waiting on you now** (from Dev, ${at}):`, "", ...you.map((row) => `- **${row.key}**: ${row.waiting.text.replace(/^\*\*you\*\*: /, "")}. ${short(row.title, 90)}`)]
|
|
273
|
+
: [`No lane is waiting on you (from Dev, ${at}).`]), NEEDS_END];
|
|
274
|
+
return { running: lines.join("\n"), needs: needs.join("\n") };
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
const replaceBlock = (text, start, end, block) => {
|
|
278
|
+
const i = text.indexOf(start);
|
|
279
|
+
const j = text.indexOf(end);
|
|
280
|
+
if (i < 0 || j < i) return null;
|
|
281
|
+
return text.slice(0, i) + block + text.slice(j + end.length);
|
|
282
|
+
};
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* What's running goes on the coordinator's status page, never the sheet
|
|
286
|
+
* (MW4-31). Replaces the block, or puts it first, under the page's title.
|
|
287
|
+
*/
|
|
288
|
+
export function placeRunning(status, running) {
|
|
289
|
+
const replaced = replaceBlock(status, RUNNING_START, RUNNING_END, running);
|
|
290
|
+
if (replaced !== null) return replaced;
|
|
291
|
+
const first = status.indexOf("\n## ");
|
|
292
|
+
return first < 0 ? `${status.replace(/\s*$/, "")}\n\n${running}\n` : `${status.slice(0, first)}\n\n${running}\n${status.slice(first)}`;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* The sheet carries only asks (MW4-31): the lanes that genuinely wait on the
|
|
297
|
+
* operator, under its "What needs you" heading. A board an earlier tool left
|
|
298
|
+
* on the sheet is taken off it.
|
|
299
|
+
*/
|
|
300
|
+
export function placeNeeds(sheet, needs) {
|
|
301
|
+
let text = replaceBlock(sheet, RUNNING_START, RUNNING_END, "") ?? sheet;
|
|
302
|
+
text = text.replace(/\n{3,}/g, "\n\n");
|
|
303
|
+
const replaced = replaceBlock(text, NEEDS_START, NEEDS_END, needs);
|
|
304
|
+
if (replaced !== null) return replaced;
|
|
305
|
+
const heading = text.match(/\n## [^\n]*What needs you[^\n]*\n/);
|
|
306
|
+
if (heading) {
|
|
307
|
+
const at = heading.index + heading[0].length;
|
|
308
|
+
return `${text.slice(0, at)}\n${needs}\n${text.slice(at)}`;
|
|
309
|
+
}
|
|
310
|
+
const first = text.indexOf("\n## ");
|
|
311
|
+
return first < 0 ? `${text.replace(/\s*$/, "")}\n\n${needs}\n` : `${text.slice(0, first)}\n\n${needs}\n${text.slice(first)}`;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
export const statusPageHeader = (sheet) =>
|
|
315
|
+
`# ${sheet} status\n\nKept by the coordinator. What is running, reports and status live here; the asks are on [${sheet}.md](${sheet}.md) (MW4-31).\n`;
|
|
316
|
+
|
|
317
|
+
/** Rows in the sheet's current board: the last published count, for the collapse check. */
|
|
318
|
+
export const boardRowCount = (sheet) => {
|
|
319
|
+
const i = sheet.indexOf(RUNNING_START);
|
|
320
|
+
const j = sheet.indexOf(RUNNING_END);
|
|
321
|
+
if (i < 0 || j < i) return 0;
|
|
322
|
+
return sheet.slice(i, j).split("\n").filter((line) => /^\| (?!Lane \||---)/.test(line)).length;
|
|
323
|
+
};
|
|
324
|
+
|
|
325
|
+
/** Refuses an empty board, or one that collapsed against the last one (Dev answered short). */
|
|
326
|
+
export function assertBoardSane(board, previousRows, { force = false } = {}) {
|
|
327
|
+
const shown = board.rows.filter((row) => row.domain).length;
|
|
328
|
+
if (!board.rows.length) throw new CliError("BOARD_EMPTY", "Dev returned no lanes for this machine; the board was not written (never publish an empty board).", 1);
|
|
329
|
+
if (!force && previousRows >= 6 && shown < previousRows * 0.5)
|
|
330
|
+
throw new CliError("BOARD_SHRANK", `The board would drop from ${previousRows} rows to ${shown}; not written. Check Dev, then pass --force if it is real.`, 1);
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// ---- Answers the operator typed in their checkout ---------------------------
|
|
334
|
+
|
|
335
|
+
/** "## ID: title" sections and the text after their "Answer:" lines. */
|
|
336
|
+
export function answersBySection(sheet) {
|
|
337
|
+
const out = new Map();
|
|
338
|
+
let id = null;
|
|
339
|
+
for (const line of String(sheet).split("\n")) {
|
|
340
|
+
const heading = line.match(/^## ([A-Z][A-Za-z0-9-]*\d[A-Za-z0-9-]*)\b[: ]/);
|
|
341
|
+
if (heading) { id = heading[1]; continue; }
|
|
342
|
+
if (/^## /.test(line)) { id = null; continue; }
|
|
343
|
+
const answer = line.match(/^\s*(?:[-*]\s*)?(?:\*\*)?Answer:?(?:\*\*)?:?\s*(.*)$/);
|
|
344
|
+
if (id && answer) out.set(`${id}\u0000${line.replace(/Answer:?(?:\*\*)?:?\s*.*$/, "")}`, { id, line, text: answer[1].trim() });
|
|
345
|
+
}
|
|
346
|
+
return out;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** Answers present in the operator's copy and not in main: typed by the operator. */
|
|
350
|
+
export function typedAnswers(operatorSheet, mainSheet) {
|
|
351
|
+
const mine = answersBySection(operatorSheet);
|
|
352
|
+
const main = answersBySection(mainSheet);
|
|
353
|
+
const typed = [];
|
|
354
|
+
for (const [slot, answer] of mine) {
|
|
355
|
+
if (!answer.text) continue;
|
|
356
|
+
if (main.get(slot)?.text === answer.text) continue;
|
|
357
|
+
typed.push({ ...answer, mainLine: main.get(slot)?.line ?? null });
|
|
358
|
+
}
|
|
359
|
+
return typed;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/** Writes each typed answer into main's sheet in place, and verbatim into answered.md. */
|
|
363
|
+
export function applyAnswers(mainSheet, answeredMd, typed, at) {
|
|
364
|
+
let sheet = mainSheet;
|
|
365
|
+
for (const answer of typed) if (answer.mainLine !== null) sheet = sheet.replace(answer.mainLine, answer.line);
|
|
366
|
+
if (!typed.length) return { sheet, answered: answeredMd };
|
|
367
|
+
const block = [
|
|
368
|
+
"",
|
|
369
|
+
`## ${at.slice(0, 10)} ${at.slice(11, 16)}Z: typed on the sheet (harvested verbatim by nodii-dev coordinator board)`,
|
|
370
|
+
...typed.map((answer) => `- **${answer.id}**, verbatim: "${answer.text}"`),
|
|
371
|
+
"",
|
|
372
|
+
].join("\n");
|
|
373
|
+
return { sheet, answered: `${answeredMd.replace(/\s*$/, "")}\n${block}` };
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** The sheet with the board blocks taken out, to compare two copies. */
|
|
377
|
+
export const withoutBoard = (sheet) =>
|
|
378
|
+
[[RUNNING_START, RUNNING_END], [NEEDS_START, NEEDS_END]].reduce((text, [start, end]) => {
|
|
379
|
+
const i = text.indexOf(start);
|
|
380
|
+
const j = text.indexOf(end);
|
|
381
|
+
return i < 0 || j < i ? text : text.slice(0, i) + text.slice(j + end.length);
|
|
382
|
+
}, sheet);
|
|
383
|
+
|
|
384
|
+
/** Whether two copies of the sheet match once the board blocks, and the blank lines around them, are set aside. */
|
|
385
|
+
export const sameApartFromBoard = (a, b) => {
|
|
386
|
+
const norm = (text) => withoutBoard(text).replace(/[ \t]+$/gm, "").replace(/\n{3,}/g, "\n\n").trim();
|
|
387
|
+
return norm(a) === norm(b);
|
|
388
|
+
};
|
|
389
|
+
|
|
390
|
+
// ---- Writing the sheet -------------------------------------------------------
|
|
391
|
+
|
|
392
|
+
const git = (execute, cwd, args, options = {}) => execute("git", ["-C", cwd, ...args], { maxBuffer: 16 * 1024 * 1024, ...options }).then((r) => r.stdout);
|
|
393
|
+
|
|
394
|
+
export async function writeBoard(board, {
|
|
395
|
+
infra, sheet, coordinator = sheet, execute = execFile, home = homedir(), sleep = (ms) => new Promise((r) => setTimeout(r, ms)), force = false, now = Date.now,
|
|
396
|
+
} = {}) {
|
|
397
|
+
const sheetPath = `docs/open/${sheet}.md`;
|
|
398
|
+
const statusPath = `docs/open/${sheet}-status.md`;
|
|
399
|
+
const answeredPath = "docs/open/answered.md";
|
|
400
|
+
const worktree = join(infra, ".claude", "worktrees", `${sheet}-board`);
|
|
401
|
+
const branch = `docs/open-${sheet}-board`;
|
|
402
|
+
await git(execute, infra, ["fetch", "-q", "origin", "main"]);
|
|
403
|
+
try { await git(execute, worktree, ["rev-parse", "--git-dir"]); }
|
|
404
|
+
catch { await git(execute, infra, ["worktree", "add", "-q", "--detach", worktree, "origin/main"]); }
|
|
405
|
+
await git(execute, worktree, ["fetch", "-q", "origin", "main"]);
|
|
406
|
+
await git(execute, worktree, ["checkout", "-q", "-B", branch, "origin/main"]);
|
|
407
|
+
const mainSheet = await readFile(join(worktree, sheetPath), "utf8");
|
|
408
|
+
const mainStatus = await readFile(join(worktree, statusPath), "utf8").catch(() => statusPageHeader(sheet));
|
|
409
|
+
const mainAnswered = await readFile(join(worktree, answeredPath), "utf8").catch(() => "");
|
|
410
|
+
const operatorSheet = await readFile(join(infra, sheetPath), "utf8").catch(() => mainSheet);
|
|
411
|
+
assertBoardSane(board, Math.max(boardRowCount(mainStatus), boardRowCount(mainSheet)), { force });
|
|
412
|
+
const typed = typedAnswers(operatorSheet, mainSheet);
|
|
413
|
+
const at = new Date(now()).toISOString();
|
|
414
|
+
const answered = applyAnswers(mainSheet, mainAnswered, typed, at);
|
|
415
|
+
const blocks = renderBoard(board, { coordinator });
|
|
416
|
+
const nextSheet = placeNeeds(answered.sheet, blocks.needs);
|
|
417
|
+
const nextStatus = placeRunning(mainStatus, blocks.running);
|
|
418
|
+
// Only the timestamp moved: nothing to merge.
|
|
419
|
+
const stamp = (text) => text.replace(/; last \d\d:\d\dZ\)/, "").replace(/\(from Dev, \d\d:\d\dZ\)/g, "");
|
|
420
|
+
let merged = false;
|
|
421
|
+
let pr = null;
|
|
422
|
+
if (stamp(nextSheet) !== stamp(mainSheet) || stamp(nextStatus) !== stamp(mainStatus) || typed.length) {
|
|
423
|
+
await writeFile(join(worktree, sheetPath), nextSheet);
|
|
424
|
+
await writeFile(join(worktree, statusPath), nextStatus);
|
|
425
|
+
if (typed.length) await writeFile(join(worktree, answeredPath), answered.answered);
|
|
426
|
+
// A name carries no time or count (S01-46); those go in the body.
|
|
427
|
+
const message = `docs(open): ${sheet} board from Dev${typed.length ? " with harvested answers" : ""}`;
|
|
428
|
+
await git(execute, worktree, ["add", "--", sheetPath, statusPath, ...(typed.length ? [answeredPath] : [])]);
|
|
429
|
+
await git(execute, worktree, ["commit", "-q", "-m", message]);
|
|
430
|
+
await git(execute, worktree, ["push", "-q", "-f", "-u", "origin", branch]);
|
|
431
|
+
const body = `Built at ${at}. Auto-update from Dev's real state (nodii-dev coordinator board): what is running on ${sheet}-status.md, the lanes waiting on the operator on ${sheet}.md (MW4-31).${typed.length ? `\n\nHarvested verbatim into answered.md: ${typed.map((t) => t.id).join(", ")}.` : ""}`;
|
|
432
|
+
pr = (await execute("gh", ["pr", "create", "-B", "main", "-H", branch, "-t", message, "-b", body], { cwd: worktree }).catch((e) => ({ stdout: String(e?.stdout ?? "") }))).stdout.trim() || branch;
|
|
433
|
+
for (let attempt = 0; attempt < 6 && !merged; attempt++) {
|
|
434
|
+
await sleep(attempt ? 10_000 : 5000);
|
|
435
|
+
try { await execute("gh", ["pr", "merge", branch, "--squash", "--delete-branch"], { cwd: worktree }); merged = true; } catch {}
|
|
436
|
+
}
|
|
437
|
+
if (!merged) throw new CliError("BOARD_MERGE_FAILED", `The board PR (${pr}) did not merge; the sheet is unchanged on main.`, 1);
|
|
438
|
+
}
|
|
439
|
+
await git(execute, worktree, ["fetch", "-q", "origin", "main"]);
|
|
440
|
+
await git(execute, worktree, ["checkout", "-q", "--detach", "origin/main"]);
|
|
441
|
+
const operator = await fastForwardOperator(infra, sheetPath, { execute });
|
|
442
|
+
return { merged, pr, harvested: typed.map((t) => ({ id: t.id, text: t.text })), operator, rows: board.rows.length };
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/**
|
|
446
|
+
* Fast-forwards the operator's checkout. Their copy of the sheet is reset only
|
|
447
|
+
* when, apart from the board, it already matches main: every answer they typed
|
|
448
|
+
* is in main verbatim. Anything else they changed is left alone and reported.
|
|
449
|
+
*/
|
|
450
|
+
export async function fastForwardOperator(infra, sheetPath, { execute = execFile } = {}) {
|
|
451
|
+
const branchName = (await git(execute, infra, ["branch", "--show-current"])).trim();
|
|
452
|
+
if (branchName !== "main") return { forwarded: false, reason: `the checkout is on ${branchName || "a detached HEAD"}, not main` };
|
|
453
|
+
await git(execute, infra, ["fetch", "-q", "origin", "main"]);
|
|
454
|
+
const dirty = (await git(execute, infra, ["status", "--porcelain", "--untracked-files=no"])).split("\n").filter(Boolean).map((l) => l.slice(3));
|
|
455
|
+
if (dirty.length) {
|
|
456
|
+
if (dirty.some((path) => path !== sheetPath)) return { forwarded: false, reason: `local changes outside the sheet: ${dirty.filter((p) => p !== sheetPath).join(", ")}` };
|
|
457
|
+
const mine = await readFile(join(infra, sheetPath), "utf8");
|
|
458
|
+
const main = await git(execute, infra, ["show", `origin/main:${sheetPath}`]);
|
|
459
|
+
if (sameApartFromBoard(mine, main) === false)
|
|
460
|
+
return { forwarded: false, reason: "the sheet has edits that are not in main yet (not an answer the board could harvest)" };
|
|
461
|
+
await git(execute, infra, ["checkout", "-q", "--", sheetPath]);
|
|
462
|
+
}
|
|
463
|
+
try { await git(execute, infra, ["merge", "-q", "--ff-only", "origin/main"]); }
|
|
464
|
+
catch (error) { return { forwarded: false, reason: `fast-forward refused: ${String(error?.stderr ?? error?.message ?? error).trim().slice(0, 160)}` }; }
|
|
465
|
+
return { forwarded: true };
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
export async function boardCommand(flags = {}, { home = homedir(), collect = collectBoard, write = writeBoard, execute = execFile } = {}) {
|
|
469
|
+
const settings = await readCoordinatorSettings(home);
|
|
470
|
+
const infra = flags.infra ?? settings.infra ?? join(home, "Projects", "nodii-infra");
|
|
471
|
+
const sheet = flags.sheet ?? settings.sheet;
|
|
472
|
+
const answeredText = await readFile(join(infra, "docs", "open", "answered.md"), "utf8").catch(() => "");
|
|
473
|
+
const sheetText = sheet ? await readFile(join(infra, "docs", "open", `${sheet}.md`), "utf8").catch(() => "") : "";
|
|
474
|
+
const board = await collect({ answeredText, sheetText, domains: settings.domains });
|
|
475
|
+
if (!flags.write) {
|
|
476
|
+
const rendered = renderBoard(board, { coordinator: sheet ?? "coordinator" });
|
|
477
|
+
return { payload: { data: board }, human: `${rendered.needs}\n\n${rendered.running}` };
|
|
478
|
+
}
|
|
479
|
+
if (!sheet) throw new CliError("USAGE", "coordinator board --write needs --sheet NAME once (the coordinator's sheet, docs/open/NAME.md); it is remembered.", 2);
|
|
480
|
+
if (flags.sheet || flags.infra) await saveCoordinatorSettings({ ...settings, sheet, infra }, home);
|
|
481
|
+
const result = await write(board, { infra, sheet, coordinator: sheet, execute, home, force: Boolean(flags.force) });
|
|
482
|
+
return {
|
|
483
|
+
payload: { data: { ...result, at: board.at } },
|
|
484
|
+
human: [
|
|
485
|
+
result.merged ? `Board merged into ${sheet}.md (${result.rows} lanes).` : `Board unchanged on ${sheet}.md (${result.rows} lanes).`,
|
|
486
|
+
...(result.harvested.length ? [`Harvested into answered.md: ${result.harvested.map((h) => h.id).join(", ")}`] : []),
|
|
487
|
+
result.operator.forwarded ? "Operator's checkout fast-forwarded." : `Operator's checkout NOT fast-forwarded: ${result.operator.reason}.`,
|
|
488
|
+
].join("\n"),
|
|
489
|
+
};
|
|
490
|
+
}
|