@nodii/dev 0.6.77 → 0.6.78

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/dist/cli.js CHANGED
@@ -320,6 +320,10 @@ Usage: nodii-dev <command> [options] [--json]
320
320
  lane heartbeat <key> --note "BLOCKED: ..."|"WAITING: ..."
321
321
  # a note starting BLOCKED or WAITING: (capitals) marks the lane blocked:
322
322
  # an exit then ends its run blocked and never counts as a death
323
+ lane heartbeat <key> --waiting-on LANE|owner/repo#n|Q-nnn|DEC-nnnn|release:PKG|launch-day [...]
324
+ # repeatable; replaces the lane's waits (a WAITING note's lane keys and
325
+ # repo#n count too; a note that is no wait clears them). A wait on another
326
+ # lane raises its priority by one and notifies the machine coordinator
323
327
  lane resume <key> --override --reason TEXT
324
328
  # coordinator: resume past the two-identical-deaths stop; Dev refuses
325
329
  # it (RESUME_OVERRIDE_NEEDS_CHANGE) unless the lane was amended since
@@ -358,7 +362,16 @@ Usage: nodii-dev <command> [options] [--json]
358
362
  lane freeze drop <key> --section SECTION --item ID --reason TEXT
359
363
  lane freeze swap <key> --section SECTION [--item ID] --file VALUE.json --reason TEXT
360
364
  lane freeze show|history <key> # durable compact-safe contract and all versions
361
- lane close <key> [--delivered-by <PR URL|lane key|issue key>] --reason TEXT
365
+ lane stop <key> --reason TEXT [--sweeper LANE] [--no-closeout]
366
+ # hub-244: Dev ends the lane and releases its holds in one step
367
+ # (issue claims; editing and all-rejected change sets with their scopes;
368
+ # sets holding operator decisions move to --sweeper or are listed on the
369
+ # issue and to the coordinator). Then, on this machine, each repository's
370
+ # unlanded commits are pushed, a PR is opened or reused and CLOSED with the
371
+ # Stopped label, the lane's test stacks go down and the worktree is removed
372
+ # (only after the push, clean, and with no process in it). Recorded on the issue
373
+ lane closeout <key> --reason TEXT # re-run that machine half for an ended lane (a worktree kept earlier)
374
+ lane close <key> [--delivered-by <PR URL|lane key|issue key>] --reason TEXT [--sweeper LANE] [--no-closeout]
362
375
  # hub-232. The machine's coordinator closes a lane that marked itself
363
376
  # finished with a reason and evidence (MW1-28.2); LANE_NOT_FINISHED
364
377
  # otherwise. --delivered-by adds proof on dev (a merged PR verified on
@@ -379,7 +392,10 @@ Usage: nodii-dev <command> [options] [--json]
379
392
  lane non-issue <key> --reason TEXT --evidence TEXT --reroute KEY[,KEY]|none
380
393
  --branch carried:KEY|dropped[:REASON] [--commits SHA[,SHA]]
381
394
  # DEC-0011: terminal non_issue; issue -> wont_do; slot frees
382
- lane list [--kind KIND] [--status STATUS] [--mine] [--cursor CURSOR]
395
+ lane list [--kind KIND] [--status STATUS] [--mine] [--sort created|priority] [--cursor CURSOR]
396
+ # --sort priority: live lanes by effective priority (own + lanes waiting)
397
+ lane waits [--machine ID] # the wait graph: lanes others wait on, chains through stuck or orphaned
398
+ # lanes, and lanes held per operator question, decision and launch day
383
399
  lane show <key> | next <key> [--paths A,B] [--components K,L] [--role R]
384
400
  # next step, plus the rules Dev serves for it (DEC-0020)
385
401
  lane gather [key] [--delta] [--paths A,B] [--components K,L]
@@ -0,0 +1,232 @@
1
+ // hub-244: the machine half of a lane's end. Dev releases what it
2
+ // holds (change sets, scopes, claims) in the stop itself; Dev cannot reach this
3
+ // machine, so `lane stop`, `lane close`, `lane closeout` and the watchdog's
4
+ // final Orphan run this here, for each of the lane's repositories:
5
+ //
6
+ // 1. Commits not on the base are pushed, and read back from the remote.
7
+ // 2. A PR for the branch is opened if none is open ("Stopped: <reason>",
8
+ // lane key, issues), labelled Stopped, commented and CLOSED, so the work
9
+ // is recorded as stopped and recoverable from the branch. An open PR is
10
+ // closed the same way.
11
+ // 3. The lane's Docker test stacks (compose projects started from inside the
12
+ // worktree) are taken down: the lane created them, nobody else (MW2-49).
13
+ // 4. The worktree is removed, only after the push was read back, only when
14
+ // it is clean, and never while a process has it as its directory (MW1-49).
15
+ //
16
+ // Each step's outcome is reported; a step that cannot run says why, and later
17
+ // steps that depend on it are skipped, never forced.
18
+ import { execFile } from "node:child_process";
19
+ import { existsSync } from "node:fs";
20
+ import { dirname, resolve, sep } from "node:path";
21
+ import { promisify } from "node:util";
22
+ import { encode } from "./core.js";
23
+
24
+ const execFileAsync = promisify(execFile);
25
+ export const STOPPED_LABEL = "Stopped";
26
+ const MAX_BUFFER = 16 * 1024 * 1024;
27
+
28
+ const defaultExec = async (command, args, options = {}) => {
29
+ const { stdout } = await execFileAsync(command, args, { encoding: "utf8", maxBuffer: MAX_BUFFER, ...options });
30
+ return stdout;
31
+ };
32
+
33
+ /** The repositories a lane worked in, with branch and worktree. */
34
+ export function laneRepositories(lane) {
35
+ if (!lane) return [];
36
+ if (lane.repositories?.length) return lane.repositories;
37
+ if (lane.worktree && lane.branch) return [{ repo: lane.repos?.[0], branch: lane.branch, worktree: lane.worktree, baseRef: "origin/main" }];
38
+ return [];
39
+ }
40
+
41
+ const inside = (path, root) => {
42
+ const a = resolve(path);
43
+ const b = resolve(root);
44
+ return a === b || a.startsWith(b + sep);
45
+ };
46
+
47
+ /** PIDs whose current directory is inside the worktree (MW1-49). */
48
+ async function processesIn(worktree, exec, selfCwd) {
49
+ const found = [];
50
+ if (inside(selfCwd, worktree)) found.push({ pid: process.pid, cwd: selfCwd });
51
+ let out = "";
52
+ try { out = await exec("lsof", ["-a", "-d", "cwd", "-F", "pn"]); }
53
+ catch (error) { out = error?.stdout ?? ""; }
54
+ let pid = null;
55
+ for (const line of out.split("\n")) {
56
+ if (line.startsWith("p")) pid = Number(line.slice(1));
57
+ else if (line.startsWith("n") && pid && pid !== process.pid && inside(line.slice(1), worktree)) found.push({ pid, cwd: line.slice(1) });
58
+ }
59
+ return found;
60
+ }
61
+
62
+ /** Compose projects whose working directory is inside the worktree. */
63
+ async function laneStacks(worktree, exec) {
64
+ let out = "";
65
+ try {
66
+ out = await exec("docker", ["ps", "-a", "--filter", "label=com.docker.compose.project", "--format", '{{.Label "com.docker.compose.project"}}\t{{.Label "com.docker.compose.project.working_dir"}}']);
67
+ } catch (error) {
68
+ return { error: error?.code === "ENOENT" ? "docker not installed" : "docker not reachable", projects: [] };
69
+ }
70
+ const projects = new Set();
71
+ for (const line of out.split("\n")) {
72
+ const [project, dir] = line.split("\t");
73
+ if (project && dir && inside(dir, worktree)) projects.add(project);
74
+ }
75
+ return { projects: [...projects].sort() };
76
+ }
77
+
78
+ function prBody(lane, reason, issueKeys) {
79
+ return [
80
+ `Stopped: ${reason}`,
81
+ "",
82
+ `Lane: ${lane.key}`,
83
+ `Issue: ${issueKeys.length ? issueKeys.join(", ") : "none linked"}`,
84
+ "",
85
+ "This lane was stopped before its work landed. The branch keeps its commits, so the work can be picked up again from it.",
86
+ ].join("\n");
87
+ }
88
+
89
+ async function closeStoppedPr({ lane, repository, reason, issueKeys, gh }) {
90
+ const branch = repository.branch;
91
+ const open = JSON.parse((await gh("pr", "list", "--head", branch, "--state", "open", "--json", "number,url")) || "[]");
92
+ let pr = open[0] ?? null;
93
+ let opened = false;
94
+ if (!pr) {
95
+ const title = `Stopped: ${lane.title ?? lane.key}`.slice(0, 250);
96
+ const url = (await gh("pr", "create", "--head", branch, "--base", (repository.baseRef ?? "origin/main").replace(/^origin\//, ""), "--title", title, "--body", prBody(lane, reason, issueKeys))).trim().split("\n").pop();
97
+ const number = Number(url.match(/\/pull\/(\d+)/)?.[1]);
98
+ if (!number) throw Object.assign(new Error(`gh pr create returned no PR URL: ${url}`), { code: "PR_CREATE_FAILED" });
99
+ pr = { number, url };
100
+ opened = true;
101
+ }
102
+ // The label may not exist yet in this repository; --force leaves it as it is if it does.
103
+ try { await gh("label", "create", STOPPED_LABEL, "--color", "B60205", "--description", "Lane stopped before its work landed", "--force"); }
104
+ catch { /* labelling still runs; a missing label shows in the read-back */ }
105
+ await gh("pr", "edit", String(pr.number), "--add-label", STOPPED_LABEL);
106
+ await gh("pr", "close", String(pr.number), "--comment", `Stopped: ${reason}\n\nLane ${lane.key} was stopped; its branch ${branch} keeps the work.`);
107
+ // K03-16: read the PR back.
108
+ const after = JSON.parse(await gh("pr", "view", String(pr.number), "--json", "state,labels,url"));
109
+ const labelled = (after.labels ?? []).some((label) => label.name === STOPPED_LABEL);
110
+ return { number: pr.number, url: after.url ?? pr.url, opened, state: after.state, labelled };
111
+ }
112
+
113
+ /**
114
+ * Close out one repository of a stopped lane. Returns what happened at each
115
+ * step; never throws for a step's failure.
116
+ */
117
+ export async function closeoutRepository(lane, repository, { reason, issueKeys = [], exec = defaultExec, cwd = process.cwd() } = {}) {
118
+ const { worktree, branch } = repository;
119
+ const out = { repo: repository.repo, branch, worktree, pushed: null, pr: null, stacks: [], worktreeRemoved: false, notes: [] };
120
+ if (!worktree || !existsSync(worktree)) {
121
+ out.notes.push("worktree is not on this machine; nothing to close out here");
122
+ return out;
123
+ }
124
+ const git = (...args) => exec("git", ["-C", worktree, ...args]);
125
+ const gh = (...args) => exec("gh", args, { cwd: worktree });
126
+ const base = repository.baseRef ?? "origin/main";
127
+ let pushedOk = false;
128
+ try {
129
+ try { await git("fetch", "--quiet", "origin"); } catch { out.notes.push("git fetch failed; compared against the last fetched base"); }
130
+ const head = (await git("rev-parse", "HEAD")).trim();
131
+ const ahead = Number((await git("rev-list", "--count", `${base}..HEAD`)).trim());
132
+ // MW1-30.1: content already on the base has landed; no PR to record.
133
+ const landed = ahead === 0 || (await git("diff", "--name-only", base, "HEAD")).trim() === "";
134
+ if (landed) {
135
+ out.pushed = { ahead, head, needed: false };
136
+ pushedOk = true;
137
+ } else {
138
+ await git("push", "--quiet", "-u", "origin", `HEAD:refs/heads/${branch}`);
139
+ const remote = (await git("ls-remote", "origin", `refs/heads/${branch}`)).trim().split(/\s+/)[0] ?? "";
140
+ pushedOk = remote === head;
141
+ out.pushed = { ahead, head, remote, needed: true, readBack: pushedOk };
142
+ if (!pushedOk) out.notes.push(`push read-back failed: remote ${branch} is ${remote || "missing"}, HEAD is ${head}`);
143
+ }
144
+ } catch (error) {
145
+ out.notes.push(`push failed: ${String(error?.stderr || error?.message || error).trim().slice(0, 300)}`);
146
+ }
147
+ // An open PR is closed as Stopped even when nothing new needed a push.
148
+ if (pushedOk) {
149
+ try {
150
+ if (out.pushed.needed) out.pr = await closeStoppedPr({ lane, repository, reason, issueKeys, gh });
151
+ else {
152
+ const open = JSON.parse((await gh("pr", "list", "--head", branch, "--state", "open", "--json", "number,url")) || "[]");
153
+ if (open.length) out.pr = await closeStoppedPr({ lane, repository, reason, issueKeys, gh });
154
+ }
155
+ } catch (error) {
156
+ out.notes.push(`PR close-out failed: ${String(error?.stderr || error?.message || error).trim().slice(0, 300)}`);
157
+ }
158
+ }
159
+ const stacks = await laneStacks(worktree, exec);
160
+ if (stacks.error) out.notes.push(`test stacks not checked: ${stacks.error}`);
161
+ for (const project of stacks.projects) {
162
+ try {
163
+ await exec("docker", ["compose", "-p", project, "down", "--volumes", "--remove-orphans"]);
164
+ out.stacks.push({ project, down: true });
165
+ } catch (error) {
166
+ out.stacks.push({ project, down: false, error: String(error?.stderr || error?.message || error).trim().slice(0, 200) });
167
+ }
168
+ }
169
+ if (!pushedOk) {
170
+ out.notes.push("worktree kept: the push did not succeed");
171
+ return out;
172
+ }
173
+ const dirty = (await git("status", "--porcelain")).trim();
174
+ if (dirty) {
175
+ out.notes.push("worktree kept: it has uncommitted changes, which removal would lose");
176
+ return out;
177
+ }
178
+ const busy = await processesIn(worktree, exec, cwd);
179
+ if (busy.length) {
180
+ out.notes.push(`worktree kept: a process is in it (PID ${busy.map((x) => x.pid).join(", ")}); run nodii-dev lane closeout ${lane.key} once it ends (MW1-49)`);
181
+ return out;
182
+ }
183
+ try {
184
+ const common = resolve(worktree, (await git("rev-parse", "--git-common-dir")).trim());
185
+ await exec("git", ["-C", dirname(common), "worktree", "remove", worktree]);
186
+ out.worktreeRemoved = !existsSync(worktree);
187
+ if (!out.worktreeRemoved) out.notes.push("git worktree remove returned but the directory is still there");
188
+ } catch (error) {
189
+ out.notes.push(`worktree removal failed: ${String(error?.stderr || error?.message || error).trim().slice(0, 300)}`);
190
+ }
191
+ return out;
192
+ }
193
+
194
+ /** One line per repository, as a person reads it on the issue. */
195
+ export function describeCloseout(lane, repositories) {
196
+ const lines = [`Lane ${lane.key} close-out on this machine:`];
197
+ for (const r of repositories) {
198
+ const parts = [];
199
+ if (r.pushed?.needed) parts.push(r.pushed.readBack ? `pushed ${r.pushed.ahead} commit(s) to ${r.branch}` : "push not confirmed");
200
+ else if (r.pushed) parts.push("nothing unlanded to push");
201
+ if (r.pr) parts.push(`PR ${r.pr.url} ${r.pr.opened ? "opened and " : ""}closed${r.pr.labelled ? ` with the ${STOPPED_LABEL} label` : ` (the ${STOPPED_LABEL} label did not stick)`}`);
202
+ for (const s of r.stacks) parts.push(s.down ? `test stack ${s.project} taken down` : `test stack ${s.project} NOT taken down (${s.error})`);
203
+ parts.push(r.worktreeRemoved ? "worktree removed" : "worktree kept");
204
+ lines.push(`- ${r.repo ?? r.worktree}: ${parts.join("; ")}.${r.notes.length ? ` ${r.notes.join("; ")}.` : ""}`);
205
+ }
206
+ return lines.join("\n");
207
+ }
208
+
209
+ /**
210
+ * Close out every repository of the lane on this machine and record the result
211
+ * on its issues. The lane must already have ended in Dev (or be a final
212
+ * Orphan): Dev's refusal of the stop comes first, so nothing local runs for a
213
+ * stop Dev did not allow.
214
+ */
215
+ export async function closeoutLane(lane, { reason, request, onBehalfOf, exec = defaultExec, cwd = process.cwd() } = {}) {
216
+ const issueKeys = (lane?.issues ?? []).map((issue) => issue.key).filter(Boolean);
217
+ const repositories = [];
218
+ for (const repository of laneRepositories(lane))
219
+ repositories.push(await closeoutRepository(lane, repository, { reason, issueKeys, exec, cwd }));
220
+ const text = describeCloseout(lane, repositories);
221
+ const recorded = [];
222
+ if (request && repositories.length)
223
+ for (const key of issueKeys) {
224
+ try {
225
+ await request("POST", `/api/v1/issues/${encode(key)}/comment`, { body: text.slice(0, 10_000), ...(onBehalfOf ? { onBehalfOf } : {}) });
226
+ recorded.push(key);
227
+ } catch (error) {
228
+ recorded.push(`${key} (not recorded: ${error?.code ?? "error"})`);
229
+ }
230
+ }
231
+ return { repositories, recorded, text };
232
+ }
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.77";
7
+ export const VERSION = "0.6.78";
8
8
  export const configPath = () =>
9
9
  process.env.NODII_DEV_CONFIG_PATH ??
10
10
  join(homedir(), ".config/nodii-dev/config.json");