@nodii/dev 0.6.70 → 0.6.72
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 +11 -3
- package/dist/cli.js +7 -2
- package/dist/core.js +1 -1
- package/dist/flags.js +2 -0
- package/dist/lanes.js +3 -1
- package/dist/repo-policy.js +315 -0
- package/dist/starting.js +25 -4
- package/dist/watchdog.js +22 -6
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -517,6 +517,8 @@ nodii-dev docs parked [CODE] [--status pending|acknowledged]
|
|
|
517
517
|
nodii-dev harness install [--include-drafts] [--adopt PATH,...] [--dry-run] [--system]
|
|
518
518
|
nodii-dev harness update [--include-drafts] [--adopt PATH,...] [--dry-run] [--system]
|
|
519
519
|
nodii-dev harness check [--json] # 0 current, 1 differs from Dev, 2 no harness
|
|
520
|
+
nodii-dev repo policy [--json] # print this repository's nodii.repo.yaml facts (STD-11)
|
|
521
|
+
nodii-dev repo lint [--json] # 0 clean, 1 findings
|
|
520
522
|
nodii-dev harness update --check # the same check
|
|
521
523
|
nodii-dev watchdog install [--interval SECONDS] # install/update com.nodii.watchdog in ~/Library/LaunchAgents
|
|
522
524
|
nodii-dev watchdog sweep # launchd entrypoint; normally not run by hand
|
|
@@ -530,9 +532,15 @@ gone, and watched worktrees whose HEAD has commits absent from its configured
|
|
|
530
532
|
remote branch. Each observation is posted to the watched run by the machine
|
|
531
533
|
coordinator; `process_dead` transitions it to explicit `orphan` immediately.
|
|
532
534
|
Every watched run whose PID is alive (or whose lane supervisor is, between
|
|
533
|
-
same-session continuations) is reported as `process_alive`.
|
|
534
|
-
|
|
535
|
-
|
|
535
|
+
same-session continuations) is reported as `process_alive`. That is not a
|
|
536
|
+
heartbeat: a lane run with no heartbeat still goes Quiet at 15 minutes (MW1-36),
|
|
537
|
+
and Dev holds it at Quiet, short of Orphan, while its Mac still sees the process.
|
|
538
|
+
Only a coordinator run takes `process_alive` as its heartbeat.
|
|
539
|
+
Each sweep also reads Dev's live runs for the machine. A dead process is reported
|
|
540
|
+
again while Dev still holds its run as running, and a live lane or coordinator
|
|
541
|
+
run with no local record is listed as `unwatchedRuns`.
|
|
542
|
+
`coordinator start` installs this job under the coordinator's own config: the job
|
|
543
|
+
runs as one agent, and a sweep by any other agent is refused.
|
|
536
544
|
A sweep leaves a dead lane runtime alone while its lane supervisor still lives
|
|
537
545
|
(the supervisor reports the exit itself) and skips it once the supervisor has
|
|
538
546
|
reported.
|
package/dist/cli.js
CHANGED
|
@@ -24,6 +24,7 @@ import {
|
|
|
24
24
|
import { FIGMA_HOOK_DENIALS, heartbeatCurrentLane, postHook, postHookFailure, preHook, sessionStartContext, settingsSnippet, workflowSuggestion } from "./hooks.js";
|
|
25
25
|
import { setupCommand } from "./setup.js";
|
|
26
26
|
import { harnessCommand } from "./harness.js";
|
|
27
|
+
import { repoCommand } from "./repo-policy.js";
|
|
27
28
|
import { hookRuntime, recordHookFire, safetyContext, safetyPostHook, safetyPreHook } from "./safety.js";
|
|
28
29
|
import { SUBMIT_CHECK_FLAGS, changedPaths, nudgeCandidate, nudgePre, nudgeStop, recordGathered, recordGuidelineRead, recordSubmitChecks } from "./nudges.js";
|
|
29
30
|
import { doctorCommand } from "./doctor.js";
|
|
@@ -66,7 +67,7 @@ import { docsCommand, rulebookCommand, rulesCommand } from "./upload.js";
|
|
|
66
67
|
import { changeSetCommand, guidelineCommand } from "./guidelines.js";
|
|
67
68
|
import { designCheck, designCheckChangeSet, designCheckText, designRoles, designRolesText, surfacesBehind, surfacesBehindText } from "./design.js";
|
|
68
69
|
import { assertKnownFlags } from "./flags.js";
|
|
69
|
-
import { watchdogCommand } from "./watchdog.js";
|
|
70
|
+
import { installWatchdog, watchdogCommand } from "./watchdog.js";
|
|
70
71
|
import { machineCapacityCommand } from "./accounts.js";
|
|
71
72
|
import {
|
|
72
73
|
ALIASES,
|
|
@@ -189,6 +190,9 @@ Usage: nodii-dev <command> [options] [--json]
|
|
|
189
190
|
# --system stages managed hooks and only prints operator-reviewed sudo commands
|
|
190
191
|
harness check # 0 current, 1 differs from Dev, 2 not installed
|
|
191
192
|
harness update --check # the same check
|
|
193
|
+
repo policy # print this repository's nodii.repo.yaml facts (STD-11)
|
|
194
|
+
repo lint # 0 clean, 1 findings: policy file missing or invalid, stray root
|
|
195
|
+
# files, docs layout, scratch not gitignored, test scripts
|
|
192
196
|
watchdog install [--interval SECONDS] # install/update the per-Mac launchd liveness sweep (default 60s)
|
|
193
197
|
watchdog sweep # launchd entrypoint: report dead runs, stale sockets, unpushed worktrees,
|
|
194
198
|
# and re-report account usage every 5 min
|
|
@@ -745,6 +749,7 @@ export async function main(argv = process.argv.slice(2)) {
|
|
|
745
749
|
if (rest.length) throw new CliError("USAGE", `harness ${action} takes no arguments, got: ${rest.join(" ")}. Write a flag value as --include-drafts=false.`, 2);
|
|
746
750
|
return emitCommand(await harnessCommand(action, f));
|
|
747
751
|
}
|
|
752
|
+
if (command === "repo" && ["policy", "lint"].includes(action)) return emitCommand(await repoCommand(action, rest, f));
|
|
748
753
|
if (command === "watchdog") {
|
|
749
754
|
if (rest.length) throw new CliError("USAGE", `watchdog ${action ?? ""} takes no arguments, got: ${rest.join(" ")}.`, 2);
|
|
750
755
|
return emitCommand(await watchdogCommand(action, f));
|
|
@@ -799,7 +804,7 @@ export async function main(argv = process.argv.slice(2)) {
|
|
|
799
804
|
}
|
|
800
805
|
return;
|
|
801
806
|
}
|
|
802
|
-
if (command === "coordinator") return emitCommand(await coordinatorCommand(action, f));
|
|
807
|
+
if (command === "coordinator") return emitCommand(await coordinatorCommand(action, f, { installWatchdog }));
|
|
803
808
|
if (command === "lane" && action === "launch") return emitCommand(await launchLaneCommand(rest[0], f));
|
|
804
809
|
if (command === "lane" && action === "amend") return emitCommand(await amendLaneCommand(rest[0], f));
|
|
805
810
|
if (command === "lane" && action === "gather") {
|
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.72";
|
|
8
8
|
export const configPath = () =>
|
|
9
9
|
process.env.NODII_DEV_CONFIG_PATH ??
|
|
10
10
|
join(homedir(), ".config/nodii-dev/config.json");
|
package/dist/flags.js
CHANGED
|
@@ -37,6 +37,8 @@ export const COMMAND_FLAGS = {
|
|
|
37
37
|
"lane transfer": ["reason", "to-agent"],
|
|
38
38
|
"lane stop": ["reason"],
|
|
39
39
|
"lane land": [],
|
|
40
|
+
"repo policy": ["root"],
|
|
41
|
+
"repo lint": ["root"],
|
|
40
42
|
"lane review": ["file", "not-required", "decision", "question", "quote", "at"],
|
|
41
43
|
"lane non-issue": ["reason", "reroute", "evidence", "commits", "branch"],
|
|
42
44
|
"drift file": ["service", "severity", "summary", ...BODY, "related-artifact-type", "related-artifact-id"],
|
package/dist/lanes.js
CHANGED
|
@@ -55,7 +55,9 @@ export async function inferGitContext() {
|
|
|
55
55
|
return { repo, branch: need(branch, "Detached HEAD: pass --branch."), worktree };
|
|
56
56
|
}
|
|
57
57
|
|
|
58
|
-
|
|
58
|
+
// `building` is the lane's phase, not a process: say when nothing healthy is running (MW1-36).
|
|
59
|
+
const laneLiveness = (x) => x.liveness && x.liveness !== "active" ? `\t${x.liveness.toUpperCase()}` : "";
|
|
60
|
+
const laneLine = (x) => `${x.key}\t${x.status}\t${x.kind}/${x.side}\t${x.title}${x.stuck ? "\tSTUCK" : ""}${laneLiveness(x)}`;
|
|
59
61
|
// GATHER-NA: a step the coordinator ruled not applicable is never shown as done.
|
|
60
62
|
const stepState = (s) => s.state === "not_applicable" ? `not applicable: ${s.notApplicableReason ?? "(no reason recorded)"}` : s.state;
|
|
61
63
|
const detailText = (x) => [laneLine(x), ...(x.steps ?? []).map((s) => ` ${s.side}\t${stepState(s)}\t${s.stepKey}\t${s.label}`)].join("\n");
|
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
// `nodii-dev repo policy|lint`: the repository policy file (STD-11; MW5-3).
|
|
2
|
+
// The file holds facts about one repository: merge mode, CI cadence, review
|
|
3
|
+
// engine, test tiers and docs layout. It holds no rules; those are in Dev.
|
|
4
|
+
//
|
|
5
|
+
// The CLI has no runtime dependencies, so it reads a strict subset of YAML: block
|
|
6
|
+
// maps, block lists, flow lists of scalars, quoted scalars and comments. Anything
|
|
7
|
+
// else (anchors, block text, several documents) is refused, never guessed at.
|
|
8
|
+
import { execFile } from "node:child_process";
|
|
9
|
+
import { readFile, stat } from "node:fs/promises";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
import { promisify } from "node:util";
|
|
12
|
+
import { CliError } from "./core.js";
|
|
13
|
+
|
|
14
|
+
const execFileAsync = promisify(execFile);
|
|
15
|
+
|
|
16
|
+
export const POLICY_FILE = "nodii.repo.yaml";
|
|
17
|
+
export const SCHEMA_VERSION = 1;
|
|
18
|
+
export const DOCS_LAYOUTS = ["standard", "drive", "existing"];
|
|
19
|
+
export const CI_PR_MODES = ["none", "affected", "full"];
|
|
20
|
+
export const CI_FULL_TRIGGERS = ["weekly", "dispatch", "pr", "push", "release", "label"];
|
|
21
|
+
// MW4-31.1. pre-launch.md is optional, so it is not listed.
|
|
22
|
+
export const STANDARD_DOCS = ["docs/README.md", "docs/open.md", "docs/answered.md", "docs/architecture/", "docs/runbooks/", "docs/reports/", "docs/archive/"];
|
|
23
|
+
|
|
24
|
+
// ─── parser ─────────────────────────────────────────────────────────────────
|
|
25
|
+
const invalid = (message) => new CliError("POLICY_INVALID", `${POLICY_FILE}: ${message}`, 1);
|
|
26
|
+
|
|
27
|
+
/** Text before an unquoted ` #`, trailing space removed. */
|
|
28
|
+
function stripComment(line) {
|
|
29
|
+
let quote = null;
|
|
30
|
+
for (let i = 0; i < line.length; i++) {
|
|
31
|
+
const c = line[i];
|
|
32
|
+
if (quote) { if (c === quote) quote = null; continue; }
|
|
33
|
+
if (c === '"' || c === "'") quote = c;
|
|
34
|
+
else if (c === "#" && (i === 0 || /\s/.test(line[i - 1]))) return line.slice(0, i).trimEnd();
|
|
35
|
+
}
|
|
36
|
+
if (quote) throw invalid(`unterminated quote in: ${line.trim()}`);
|
|
37
|
+
return line.trimEnd();
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function scalar(raw, where) {
|
|
41
|
+
const text = raw.trim();
|
|
42
|
+
if (/^".*"$/.test(text) || /^'.*'$/.test(text)) return text.slice(1, -1);
|
|
43
|
+
if (/^[&*!|>%@`]/.test(text) || text === "---" || text === "...") throw invalid(`${where}: "${text}" uses YAML this reader does not model; write a plain or quoted value`);
|
|
44
|
+
if (/^[{[]/.test(text)) throw invalid(`${where}: nested collections are not allowed in a flow list`);
|
|
45
|
+
if (text === "true") return true;
|
|
46
|
+
if (text === "false") return false;
|
|
47
|
+
if (text === "null" || text === "~") return null;
|
|
48
|
+
if (/^-?\d+$/.test(text)) return Number(text);
|
|
49
|
+
return text;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function flowList(raw, where) {
|
|
53
|
+
if (!raw.endsWith("]")) throw invalid(`${where}: unterminated list`);
|
|
54
|
+
const items = [];
|
|
55
|
+
let current = "";
|
|
56
|
+
let quote = null;
|
|
57
|
+
for (const c of raw.slice(1, -1)) {
|
|
58
|
+
if (quote) { current += c; if (c === quote) quote = null; continue; }
|
|
59
|
+
if (c === '"' || c === "'") quote = c;
|
|
60
|
+
if (c === ",") { items.push(current); current = ""; } else current += c;
|
|
61
|
+
}
|
|
62
|
+
if (current.trim()) items.push(current);
|
|
63
|
+
return items.map((item) => scalar(item, where));
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const value = (raw, where) => (raw.startsWith("[") ? flowList(raw, where) : scalar(raw, where));
|
|
67
|
+
|
|
68
|
+
/** Parse the policy file's YAML subset. Throws POLICY_INVALID on anything outside it. */
|
|
69
|
+
export function parsePolicyYaml(text) {
|
|
70
|
+
const lines = [];
|
|
71
|
+
for (const [index, line] of String(text).split(/\r?\n/).entries()) {
|
|
72
|
+
if (/^\s*\t/.test(line)) throw invalid(`line ${index + 1}: tabs are not allowed in indentation`);
|
|
73
|
+
const clean = stripComment(line);
|
|
74
|
+
if (!clean.trim()) continue;
|
|
75
|
+
if (clean.trim() === "---" || clean.trim() === "...") throw invalid(`line ${index + 1}: write one document, without "---"`);
|
|
76
|
+
lines.push({ number: index + 1, indent: clean.length - clean.trimStart().length, text: clean.trim() });
|
|
77
|
+
}
|
|
78
|
+
let at = 0;
|
|
79
|
+
function block(indent) {
|
|
80
|
+
return lines[at].text.startsWith("- ") || lines[at].text === "-" ? list(indent) : map(indent);
|
|
81
|
+
}
|
|
82
|
+
function list(indent) {
|
|
83
|
+
const out = [];
|
|
84
|
+
while (at < lines.length && lines[at].indent === indent && (lines[at].text.startsWith("- ") || lines[at].text === "-")) {
|
|
85
|
+
const { number, text: item } = lines[at];
|
|
86
|
+
if (item === "-") throw invalid(`line ${number}: a list item needs a value`);
|
|
87
|
+
out.push(value(item.slice(2).trim(), `line ${number}`));
|
|
88
|
+
at++;
|
|
89
|
+
}
|
|
90
|
+
return out;
|
|
91
|
+
}
|
|
92
|
+
function map(indent) {
|
|
93
|
+
const out = {};
|
|
94
|
+
while (at < lines.length && lines[at].indent === indent) {
|
|
95
|
+
const { number, text: entry } = lines[at];
|
|
96
|
+
const match = /^([A-Za-z_][\w-]*):(?:\s+(.*))?$/.exec(entry);
|
|
97
|
+
if (!match) throw invalid(`line ${number}: expected "key: value", got "${entry}"`);
|
|
98
|
+
const [, key, raw] = match;
|
|
99
|
+
if (Object.hasOwn(out, key)) throw invalid(`line ${number}: duplicate key "${key}"`);
|
|
100
|
+
at++;
|
|
101
|
+
if (raw !== undefined && raw !== "") { out[key] = value(raw, `line ${number}`); continue; }
|
|
102
|
+
// A list may sit at its key's own indent, as in common YAML style.
|
|
103
|
+
const next = lines[at];
|
|
104
|
+
const nestedList = next && next.indent === indent && next.text.startsWith("- ");
|
|
105
|
+
if (!next || (next.indent <= indent && !nestedList)) { out[key] = null; continue; }
|
|
106
|
+
out[key] = block(next.indent);
|
|
107
|
+
}
|
|
108
|
+
return out;
|
|
109
|
+
}
|
|
110
|
+
if (!lines.length) throw invalid("the file is empty");
|
|
111
|
+
const root = block(lines[0].indent);
|
|
112
|
+
if (at < lines.length) throw invalid(`line ${lines[at].number}: unexpected indentation`);
|
|
113
|
+
return root;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// ─── schema ─────────────────────────────────────────────────────────────────
|
|
117
|
+
const isObject = (x) => x !== null && typeof x === "object" && !Array.isArray(x);
|
|
118
|
+
const isStringList = (x) => Array.isArray(x) && x.every((item) => typeof item === "string" && item);
|
|
119
|
+
const isText = (x) => typeof x === "string" && x.trim().length > 0;
|
|
120
|
+
const ALLOWED_KEYS = {
|
|
121
|
+
"": ["schema", "service", "merge", "ci", "review", "tests", "docs"],
|
|
122
|
+
merge: ["mode"],
|
|
123
|
+
ci: ["pr", "full", "required", "reporting"],
|
|
124
|
+
review: ["engine", "command", "severities"],
|
|
125
|
+
tests: ["full", "tiers"],
|
|
126
|
+
docs: ["layout", "open", "scratch", "rootAllow"],
|
|
127
|
+
};
|
|
128
|
+
// MW4-31.1 names these as what must not sit at the root; a repo cannot declare them away.
|
|
129
|
+
const STRAY_KIND = /\.(md|mdx|markdown|png|jpe?g|gif|webp|bmp|tiff?|heic|svg|log)$/i;
|
|
130
|
+
const safeRelativePath = (path) => isText(path) && !path.startsWith("/") && !path.split("/").includes("..");
|
|
131
|
+
|
|
132
|
+
/** Every way the parsed file breaks the schema, as sentences. Empty means valid. */
|
|
133
|
+
export function validatePolicy(policy) {
|
|
134
|
+
if (!isObject(policy)) return ["the file must be a map of keys"];
|
|
135
|
+
const errors = [];
|
|
136
|
+
for (const [section, keys] of Object.entries(ALLOWED_KEYS)) {
|
|
137
|
+
const target = section ? policy[section] : policy;
|
|
138
|
+
if (section && !isObject(target)) { errors.push(`${section}: required, and must be a map`); continue; }
|
|
139
|
+
for (const key of Object.keys(target)) if (!keys.includes(key)) errors.push(`${section ? `${section}.` : ""}${key}: unknown key; allowed: ${keys.join(", ")}`);
|
|
140
|
+
}
|
|
141
|
+
if (policy.schema !== SCHEMA_VERSION) errors.push(`schema: must be ${SCHEMA_VERSION}`);
|
|
142
|
+
if (!isText(policy.service)) errors.push("service: required, the repository's service id or name");
|
|
143
|
+
if (isObject(policy.merge) && policy.merge.mode !== "squash") errors.push("merge.mode: must be squash (MW3-9)");
|
|
144
|
+
|
|
145
|
+
if (isObject(policy.ci)) {
|
|
146
|
+
const { pr, full, required, reporting } = policy.ci;
|
|
147
|
+
if (!CI_PR_MODES.includes(pr)) errors.push(`ci.pr: must be one of ${CI_PR_MODES.join(", ")}`);
|
|
148
|
+
const fullOk = isStringList(full) && full.length > 0 && full.every((item) => CI_FULL_TRIGGERS.includes(item));
|
|
149
|
+
if (!fullOk) errors.push(`ci.full: must list when the full suite runs, from ${CI_FULL_TRIGGERS.join(", ")}`);
|
|
150
|
+
for (const [key, list] of [["required", required], ["reporting", reporting]]) if (list !== undefined && !isStringList(list)) errors.push(`ci.${key}: must be a list of check names`);
|
|
151
|
+
const named = [...(required ?? []), ...(reporting ?? [])];
|
|
152
|
+
const perPush = pr !== "none" || (fullOk && (full.includes("pr") || full.includes("push")));
|
|
153
|
+
if (perPush && !named.length) errors.push("ci.required / ci.reporting: a repository that runs PR or push CI must name which checks are required and which only report (MW3-22)");
|
|
154
|
+
if (Array.isArray(required) && Array.isArray(reporting)) for (const name of required) if (reporting.includes(name)) errors.push(`ci: "${name}" is both required and reporting (MW3-22)`);
|
|
155
|
+
if (pr === "none" && fullOk && !perPush && !(full.includes("weekly") && full.includes("dispatch"))) errors.push("ci.full: a weekly repository must run its full suite on weekly and dispatch (MW3-15)");
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
if (isObject(policy.review)) {
|
|
159
|
+
if (!isText(policy.review.engine)) errors.push("review.engine: required");
|
|
160
|
+
if (!isText(policy.review.command)) errors.push("review.command: required");
|
|
161
|
+
if (!isStringList(policy.review.severities) || !policy.review.severities.length) errors.push("review.severities: must list the severities the review reports");
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
if (isObject(policy.tests)) {
|
|
165
|
+
if (!isText(policy.tests.full)) errors.push("tests.full: required, the script that runs the full suite (S06-52)");
|
|
166
|
+
if (!isStringList(policy.tests.tiers)) errors.push("tests.tiers: must be a list of tier names, each with a test:<tier> script (S06-52)");
|
|
167
|
+
else for (const tier of policy.tests.tiers) {
|
|
168
|
+
if (/^(tier[-_]?)?[123][ab]?$/i.test(tier)) errors.push(`tests.tiers: "${tier}" is a cluster tier; the canonical suite owns it, so it is not declared here (S06-52)`);
|
|
169
|
+
else if (!/^[a-z][a-z0-9-]*$/.test(tier)) errors.push(`tests.tiers: "${tier}" must be lowercase letters, digits and hyphens`);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
if (isObject(policy.docs)) {
|
|
174
|
+
const { layout, open, scratch, rootAllow } = policy.docs;
|
|
175
|
+
if (!DOCS_LAYOUTS.includes(layout)) errors.push(`docs.layout: must be one of ${DOCS_LAYOUTS.join(", ")}`);
|
|
176
|
+
if (layout === "standard" && open !== "docs/open.md") errors.push("docs.open: the standard layout keeps it at docs/open.md (MW4-31.1)");
|
|
177
|
+
if (layout === "drive" && !(safeRelativePath(open) && open.endsWith("/open.md"))) errors.push("docs.open: a drive repository names its drive's open.md path (MW4-31)");
|
|
178
|
+
if (open !== undefined && !safeRelativePath(open)) errors.push("docs.open: must be a path inside the repository");
|
|
179
|
+
if (scratch !== undefined && !(isStringList(scratch) && scratch.every(safeRelativePath))) errors.push("docs.scratch: must be a list of paths inside the repository");
|
|
180
|
+
if (rootAllow !== undefined) {
|
|
181
|
+
if (!isStringList(rootAllow)) errors.push("docs.rootAllow: must be a list of root file names");
|
|
182
|
+
else for (const name of rootAllow) if (STRAY_KIND.test(name) || name.includes("/")) errors.push(`docs.rootAllow: "${name}" cannot be allowed; markdown, screenshots and logs never sit at the root (MW4-31.1)`);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return errors;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// ─── reader ─────────────────────────────────────────────────────────────────
|
|
189
|
+
async function gitLines(root, args) {
|
|
190
|
+
const { stdout } = await execFileAsync("git", ["-C", root, ...args], { maxBuffer: 64 * 1024 * 1024 });
|
|
191
|
+
return stdout.split("\n").filter(Boolean);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
async function repoRoot(flags = {}) {
|
|
195
|
+
if (flags.root && flags.root !== true) return String(flags.root);
|
|
196
|
+
try {
|
|
197
|
+
const [root] = await gitLines(process.cwd(), ["rev-parse", "--show-toplevel"]);
|
|
198
|
+
return root;
|
|
199
|
+
} catch { throw new CliError("USAGE", "Run this inside a git repository.", 2); }
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
async function exists(path) {
|
|
203
|
+
try { await stat(path); return true; } catch (error) { if (error.code === "ENOENT") return false; throw error; }
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** The repository's parsed, validated policy. Throws POLICY_MISSING or POLICY_INVALID. */
|
|
207
|
+
export async function readPolicy(root) {
|
|
208
|
+
let text;
|
|
209
|
+
try { text = await readFile(join(root, POLICY_FILE), "utf8"); } catch (error) {
|
|
210
|
+
if (error.code !== "ENOENT") throw error;
|
|
211
|
+
throw new CliError("POLICY_MISSING", `${root} has no ${POLICY_FILE} (STD-11).`, 1);
|
|
212
|
+
}
|
|
213
|
+
const policy = parsePolicyYaml(text);
|
|
214
|
+
const errors = validatePolicy(policy);
|
|
215
|
+
if (errors.length) throw new CliError("POLICY_INVALID", `${POLICY_FILE}: ${errors.join("; ")}`, 1, { errors });
|
|
216
|
+
return policy;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// ─── lint ───────────────────────────────────────────────────────────────────
|
|
220
|
+
// Configuration by name. A root file outside these, and outside docs.rootAllow, is stray.
|
|
221
|
+
const ROOT_NAMES = new Set([POLICY_FILE, "makefile", "justfile", "procfile", "dockerfile", "go.mod", "go.sum", "pipfile", "gemfile"]);
|
|
222
|
+
const ROOT_PATTERNS = [
|
|
223
|
+
/^readme(\.[a-z]+)?$/i,
|
|
224
|
+
/^\.[^/]+$/, // dotfiles
|
|
225
|
+
/\.(json|jsonc|ya?ml|toml|lock|ini|cfg|conf)$/i,
|
|
226
|
+
/\.config\.[cm]?[jt]s$/i,
|
|
227
|
+
/^dockerfile\./i,
|
|
228
|
+
/^requirements[\w.-]*\.txt$/i,
|
|
229
|
+
/^setup\.py$/i,
|
|
230
|
+
];
|
|
231
|
+
const ROOT_MARKDOWN = new Set(["readme.md", "claude.md", "agents.md"]);
|
|
232
|
+
|
|
233
|
+
/** Is this root file allowed? README, CLAUDE.md, the harness's AGENTS.md and config are (MW4-31.1). */
|
|
234
|
+
function allowedAtRoot(name, extras) {
|
|
235
|
+
if (ROOT_MARKDOWN.has(name.toLowerCase())) return true;
|
|
236
|
+
if (STRAY_KIND.test(name)) return false;
|
|
237
|
+
return extras.includes(name) || ROOT_NAMES.has(name.toLowerCase()) || ROOT_PATTERNS.some((pattern) => pattern.test(name));
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** Files at the repository root that git tracks or would track; ignored scratch does not count. */
|
|
241
|
+
async function rootFiles(root) {
|
|
242
|
+
const all = await gitLines(root, ["ls-files", "--cached", "--others", "--exclude-standard", "--deduplicate"]);
|
|
243
|
+
return all.filter((path) => !path.includes("/"));
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
async function isIgnored(root, path) {
|
|
247
|
+
try { await execFileAsync("git", ["-C", root, "check-ignore", "-q", "--no-index", path]); return true; } catch (error) {
|
|
248
|
+
if (error.code === 1) return false;
|
|
249
|
+
throw error;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Check one repository against its policy file. A missing or invalid file fails
|
|
255
|
+
* every repository. `layout: existing` marks a repository that predates MW4-31.1:
|
|
256
|
+
* it is not required to migrate (operator, 2 Nov 2026), so the root and layout
|
|
257
|
+
* checks skip it.
|
|
258
|
+
*/
|
|
259
|
+
export async function lintRepo(root) {
|
|
260
|
+
let policy;
|
|
261
|
+
try { policy = await readPolicy(root); } catch (error) {
|
|
262
|
+
if (error.code !== "POLICY_MISSING" && error.code !== "POLICY_INVALID") throw error;
|
|
263
|
+
return { root, policy: null, findings: [{ code: error.code, path: POLICY_FILE, message: error.message }] };
|
|
264
|
+
}
|
|
265
|
+
const findings = [];
|
|
266
|
+
const add = (code, path, message) => findings.push({ code, path, message });
|
|
267
|
+
const { layout, open, scratch = [], rootAllow = [] } = policy.docs;
|
|
268
|
+
|
|
269
|
+
if (layout !== "existing") {
|
|
270
|
+
for (const name of await rootFiles(root)) {
|
|
271
|
+
if (!allowedAtRoot(name, rootAllow)) add("STRAY_ROOT_FILE", name, `${name} may not sit at the repository root (MW4-31.1): move it under docs/, gitignore it if it is scratch, or list a configuration file in docs.rootAllow.`);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
if (layout === "standard") {
|
|
275
|
+
for (const path of STANDARD_DOCS) if (!(await exists(join(root, path)))) add("DOCS_LAYOUT_MISSING", path, `The standard layout needs ${path} (MW4-31.1).`);
|
|
276
|
+
} else if (open && layout === "drive" && !(await exists(join(root, open)))) {
|
|
277
|
+
add("DOCS_LAYOUT_MISSING", open, `docs.open names ${open}, which does not exist (MW4-31).`);
|
|
278
|
+
}
|
|
279
|
+
for (const path of scratch) if (!(await isIgnored(root, path))) add("SCRATCH_NOT_IGNORED", path, `The scratch path ${path} is not gitignored (MW4-31.1).`);
|
|
280
|
+
|
|
281
|
+
// Tier scripts are checked where the repository declares scripts in package.json.
|
|
282
|
+
let scripts = null;
|
|
283
|
+
try { scripts = JSON.parse(await readFile(join(root, "package.json"), "utf8")).scripts ?? {}; } catch (error) {
|
|
284
|
+
if (error.code !== "ENOENT" && !(error instanceof SyntaxError)) throw error;
|
|
285
|
+
}
|
|
286
|
+
if (scripts) {
|
|
287
|
+
const declared = [policy.tests.full, ...policy.tests.tiers.map((tier) => `test:${tier}`)];
|
|
288
|
+
for (const script of declared) if (!Object.hasOwn(scripts, script)) add("TEST_SCRIPT_MISSING", script, `The policy file declares the script ${script}, which package.json does not have (S06-52).`);
|
|
289
|
+
}
|
|
290
|
+
return { root, policy, findings };
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// ─── command ────────────────────────────────────────────────────────────────
|
|
294
|
+
const humanPolicy = ({ root, policy: p }) => [
|
|
295
|
+
`${root}/${POLICY_FILE} · ${p.service}`,
|
|
296
|
+
`merge: ${p.merge.mode}`,
|
|
297
|
+
`ci: PR runs ${p.ci.pr}; full suite on ${p.ci.full.join(", ")}; required ${p.ci.required?.join(", ") || "none"}; reporting ${p.ci.reporting?.join(", ") || "none"}`,
|
|
298
|
+
`review: ${p.review.engine} · ${p.review.command} · ${p.review.severities.join(", ")}`,
|
|
299
|
+
`tests: ${p.tests.full}${p.tests.tiers.length ? `; tiers ${p.tests.tiers.join(", ")}` : ""}`,
|
|
300
|
+
`docs: ${p.docs.layout}${p.docs.open ? ` · ${p.docs.open}` : ""}`,
|
|
301
|
+
].join("\n");
|
|
302
|
+
|
|
303
|
+
const humanLint = ({ root, findings }) => (findings.length
|
|
304
|
+
? [`${root}: ${findings.length} policy finding(s).`, ...findings.map((f) => ` ${f.code} ${f.path}: ${f.message}`)].join("\n")
|
|
305
|
+
: `${root}: policy file and checks pass.`);
|
|
306
|
+
|
|
307
|
+
export async function repoCommand(action, rest, flags = {}) {
|
|
308
|
+
if (!["policy", "lint"].includes(action)) throw new CliError("USAGE", "repo policy|lint", 2);
|
|
309
|
+
if (rest.length) throw new CliError("USAGE", `repo ${action} takes no arguments, got: ${rest.join(" ")}`, 2);
|
|
310
|
+
const root = await repoRoot(flags);
|
|
311
|
+
if (action === "policy") return { payload: { root, policy: await readPolicy(root) }, human: humanPolicy };
|
|
312
|
+
const result = await lintRepo(root);
|
|
313
|
+
const payload = { root, passed: result.findings.length === 0, findings: result.findings };
|
|
314
|
+
return { payload, human: humanLint, exitCode: result.findings.length ? 1 : 0 };
|
|
315
|
+
}
|
package/dist/starting.js
CHANGED
|
@@ -198,7 +198,7 @@ const coordinatorState = (machine, run, agentId) => ({
|
|
|
198
198
|
* Adopt this session's own running coordinator run again (CLI-16): rewrite the
|
|
199
199
|
* state file and restart the heartbeater. Dev's run is unchanged.
|
|
200
200
|
*/
|
|
201
|
-
async function adoptCoordinatorRun(machine, run, c, { save, heartbeater, existingHeartbeater }) {
|
|
201
|
+
async function adoptCoordinatorRun(machine, run, c, { save, heartbeater, existingHeartbeater, installWatchdog }) {
|
|
202
202
|
await save(stateFile(machine), coordinatorState(machine, run, c.agentId));
|
|
203
203
|
const expected = run.expectedHeartbeatSeconds ?? 60;
|
|
204
204
|
// A heartbeater still beating this run keeps it; a second is never started.
|
|
@@ -208,13 +208,15 @@ async function adoptCoordinatorRun(machine, run, c, { save, heartbeater, existin
|
|
|
208
208
|
try { heartbeaterPid = await heartbeater({ runId: run.id, machine, pid: run.watched.pid, processStartedAt: run.watched.processStartedAt ?? null, intervalSeconds: Math.max(5, Math.floor(expected / 2)) }); }
|
|
209
209
|
catch (error) { heartbeaterError = error?.message ?? String(error); }
|
|
210
210
|
}
|
|
211
|
+
const watchdogTakeover = await takeOverWatchdog(installWatchdog);
|
|
211
212
|
return {
|
|
212
|
-
payload: { data: { adopted: true, run, machine: { id: run.metadata.machineId, name: machine } }, heartbeaterPid },
|
|
213
|
+
payload: { data: { adopted: true, run, machine: { id: run.metadata.machineId, name: machine } }, heartbeaterPid, ...watchdogTakeover },
|
|
213
214
|
human: [
|
|
214
215
|
`Coordinator ${run.id} is this session's run on ${machine}; adopted it again (last heartbeat ${run.lastHeartbeatAt ?? "never"}).`,
|
|
215
216
|
heartbeaterPid
|
|
216
217
|
? `heartbeater ${heartbeaterPid} keeps the run alive while session ${run.watched.pid} lives`
|
|
217
218
|
: `heartbeater not started${heartbeaterError ? ` (${heartbeaterError})` : ""}: the run goes quiet without heartbeats`,
|
|
219
|
+
...watchdogLines(watchdogTakeover),
|
|
218
220
|
].join("\n"),
|
|
219
221
|
};
|
|
220
222
|
}
|
|
@@ -304,6 +306,21 @@ export async function coordinatorHeartbeatLoop({ machine, runId, pid, processSta
|
|
|
304
306
|
}
|
|
305
307
|
|
|
306
308
|
/** Register each --account, then report every account's usage (MW1-38.1). */
|
|
309
|
+
/**
|
|
310
|
+
* The launchd job runs as one agent, so a new coordinator has to take it over
|
|
311
|
+
* or every sweep is refused (WATCHDOG_COORDINATOR_REQUIRED; NODII-DEV-CLI-42).
|
|
312
|
+
*/
|
|
313
|
+
async function takeOverWatchdog(installWatchdog) {
|
|
314
|
+
if (!installWatchdog) return { watchdog: null, watchdogError: null };
|
|
315
|
+
try { return { watchdog: await installWatchdog(), watchdogError: null }; }
|
|
316
|
+
catch (error) { return { watchdog: null, watchdogError: `${error?.code ?? "WATCHDOG_INSTALL_FAILED"}: ${error?.message ?? error}` }; }
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
const watchdogLines = ({ watchdog, watchdogError }) => [
|
|
320
|
+
...(watchdog ? [`watchdog ${watchdog.label} runs under this coordinator${watchdog.changed ? " (updated)" : ""}`] : []),
|
|
321
|
+
...(watchdogError ? [`WATCHDOG NOT RUNNING under this coordinator (${watchdogError}); no sweep reports dead processes until nodii-dev watchdog install succeeds`] : []),
|
|
322
|
+
];
|
|
323
|
+
|
|
307
324
|
async function coordinatorCapacity(machineId, flags, { request, readers }) {
|
|
308
325
|
// The run is already started: a refused registration is reported, not thrown.
|
|
309
326
|
const refused = [];
|
|
@@ -325,6 +342,8 @@ export async function coordinatorCommand(action, flags, {
|
|
|
325
342
|
isAlive = async (pid, startedAt) => (await import("./watchdog.js")).isProcessAlive(pid, startedAt),
|
|
326
343
|
sessionPid = coordinatorRuntimePid,
|
|
327
344
|
existingHeartbeater = runningHeartbeater,
|
|
345
|
+
// Only the CLI passes launchd's installer, so no caller touches launchd by default.
|
|
346
|
+
installWatchdog = null,
|
|
328
347
|
} = {}) {
|
|
329
348
|
if (action === "heartbeat") {
|
|
330
349
|
const result = await heartbeatLoop({
|
|
@@ -361,7 +380,7 @@ export async function coordinatorCommand(action, flags, {
|
|
|
361
380
|
// CLI-16: the run's session is this session (its heartbeater or state file
|
|
362
381
|
// was lost): adopt the run again and restart its heartbeater.
|
|
363
382
|
if (sessionAlive && pid === (await sessionPid().catch(() => null)))
|
|
364
|
-
return adoptCoordinatorRun(machine, live, c, { save, heartbeater, existingHeartbeater });
|
|
383
|
+
return adoptCoordinatorRun(machine, live, c, { save, heartbeater, existingHeartbeater, installWatchdog });
|
|
365
384
|
const interval = live.expectedHeartbeatSeconds ?? 60;
|
|
366
385
|
if (!coordinatorRunStale(live, now()))
|
|
367
386
|
throw new CliError("COORDINATOR_ALREADY_RUNNING", `Coordinator run ${live.id} for ${machine} is live (last heartbeat ${live.lastHeartbeatAt ?? "never"}); it is taken over only after 3x its ${interval}s heartbeat interval with its session gone. Run coordinator start from that run's own session to adopt it again.`, 1);
|
|
@@ -418,8 +437,9 @@ export async function coordinatorCommand(action, flags, {
|
|
|
418
437
|
catch (error) { heartbeaterError = error?.message ?? String(error); }
|
|
419
438
|
}
|
|
420
439
|
const accounts = await coordinatorCapacity(payload.data.machine.id, flags, { request, readers });
|
|
440
|
+
const watchdogTakeover = await takeOverWatchdog(installWatchdog);
|
|
421
441
|
return {
|
|
422
|
-
payload: { ...payload, accounts, heartbeaterPid },
|
|
442
|
+
payload: { ...payload, accounts, heartbeaterPid, ...watchdogTakeover },
|
|
423
443
|
human: (p) => [
|
|
424
444
|
`Coordinator ${p.data.run.id} is watching ${p.data.machine.name}.`,
|
|
425
445
|
`running lanes: ${p.data.runningLanes.length}`,
|
|
@@ -432,6 +452,7 @@ export async function coordinatorCommand(action, flags, {
|
|
|
432
452
|
heartbeaterPid
|
|
433
453
|
? `heartbeater ${heartbeaterPid} keeps the run alive while session ${watched.pid} lives`
|
|
434
454
|
: `heartbeater not started${heartbeaterError ? ` (${heartbeaterError})` : ""}: the run goes quiet without heartbeats`,
|
|
455
|
+
...watchdogLines(watchdogTakeover),
|
|
435
456
|
...(accounts.length
|
|
436
457
|
? accounts.map((result) => `account ${usageLine(result)}`)
|
|
437
458
|
: [`accounts: none registered; add one with --account claude:/path/to/profile (lane launch needs its usage)`]),
|
package/dist/watchdog.js
CHANGED
|
@@ -221,6 +221,21 @@ export async function sweepWatchdog({
|
|
|
221
221
|
const byId = new Map(loaded.records.map((record) => [record.runId, record]));
|
|
222
222
|
const effectiveMachineId = machineId ?? (await coordinatorMachine({ request })).machineId;
|
|
223
223
|
const orphanedRuns = [];
|
|
224
|
+
// Dev's live runs are the authority, not the local flags (NODII-DEV-CLI-42):
|
|
225
|
+
// a run Dev still holds as running gets its dead process reported again, and
|
|
226
|
+
// a run with no local record is one this sweep cannot see. Without Dev's list
|
|
227
|
+
// the local records still get checked.
|
|
228
|
+
let devLiveRuns = null;
|
|
229
|
+
try {
|
|
230
|
+
const state = await request("GET", `/api/v1/run-watchdog?machine=${encode(effectiveMachineId)}`);
|
|
231
|
+
devLiveRuns = Array.isArray(state?.data?.liveRuns) ? state.data.liveRuns : null;
|
|
232
|
+
} catch (error) {
|
|
233
|
+
facts.errors.push({ kind: "live_runs", code: error?.code ?? "RUN_WATCHDOG_STATE_FAILED" });
|
|
234
|
+
}
|
|
235
|
+
const devLiveIds = new Set((devLiveRuns ?? []).map((run) => run.id));
|
|
236
|
+
const unwatchedRuns = (devLiveRuns ?? [])
|
|
237
|
+
.filter((run) => ["lane", "coordinator"].includes(run.kind) && !byId.has(run.id))
|
|
238
|
+
.map((run) => ({ runId: run.id, kind: run.kind, lastHeartbeatAt: run.lastHeartbeatAt }));
|
|
224
239
|
// Record the non-terminal observations first: process_dead transitions the
|
|
225
240
|
// run to Orphan immediately, and must not prevent its stale socket or local
|
|
226
241
|
// commits from reaching Dev in the same sweep.
|
|
@@ -252,8 +267,8 @@ export async function sweepWatchdog({
|
|
|
252
267
|
facts.errors.push({ kind: "run", runId: record.runId, observation: "worktree_unpushed", code: error?.code ?? "RUN_WATCHDOG_REPORT_FAILED" });
|
|
253
268
|
}
|
|
254
269
|
}
|
|
255
|
-
//
|
|
256
|
-
//
|
|
270
|
+
// A PID this Mac sees alive holds a lane run at Quiet, short of Orphan, and is
|
|
271
|
+
// a coordinator run's heartbeat. It is not a lane run's heartbeat (MW1-36).
|
|
257
272
|
for (const live of facts.liveRuns ?? []) {
|
|
258
273
|
const record = byId.get(live.runId);
|
|
259
274
|
if (!record || record.orphanReportedAt || record.terminalSeenAt) continue;
|
|
@@ -268,7 +283,8 @@ export async function sweepWatchdog({
|
|
|
268
283
|
}
|
|
269
284
|
for (const dead of facts.deadRuns) {
|
|
270
285
|
const record = byId.get(dead.runId);
|
|
271
|
-
if (!record
|
|
286
|
+
if (!record) continue;
|
|
287
|
+
if ((record.orphanReportedAt || record.terminalSeenAt) && !devLiveIds.has(record.runId)) continue;
|
|
272
288
|
try {
|
|
273
289
|
const observedAt = now().toISOString();
|
|
274
290
|
const response = await request("POST", `/api/v1/runs/${encode(record.runId)}/watchdog`, observationBody({
|
|
@@ -278,7 +294,7 @@ export async function sweepWatchdog({
|
|
|
278
294
|
if (response?.data?.run?.livenessState === "orphan") {
|
|
279
295
|
record.orphanReportedAt = observedAt;
|
|
280
296
|
orphanedRuns.push({ runId: record.runId, pid: record.pid, reportedAt: record.orphanReportedAt });
|
|
281
|
-
} else if (["done", "handed_off", "failed"].includes(response?.data?.run?.status)) {
|
|
297
|
+
} else if (["done", "handed_off", "failed", "blocked"].includes(response?.data?.run?.status)) {
|
|
282
298
|
record.terminalSeenAt = observedAt;
|
|
283
299
|
} else {
|
|
284
300
|
throw new CliError("RUN_WATCHDOG_RESPONSE_INVALID", "Dev recorded process_dead without returning the run as orphan or terminal.", 1);
|
|
@@ -299,7 +315,7 @@ export async function sweepWatchdog({
|
|
|
299
315
|
} catch (error) {
|
|
300
316
|
facts.errors.push({ kind: "usage", code: error?.code ?? "ACCOUNT_USAGE_REPORT_FAILED" });
|
|
301
317
|
}
|
|
302
|
-
const report = { ...facts, orphanedRuns, accounts };
|
|
318
|
+
const report = { ...facts, orphanedRuns, unwatchedRuns, accounts };
|
|
303
319
|
return report;
|
|
304
320
|
}
|
|
305
321
|
|
|
@@ -360,7 +376,7 @@ export async function watchdogCommand(action, flags, dependencies = {}) {
|
|
|
360
376
|
}
|
|
361
377
|
if (action === "sweep") {
|
|
362
378
|
const data = await sweepWatchdog(dependencies);
|
|
363
|
-
return { payload: { data }, human: `Watchdog sweep: ${data.orphanedRuns.length} orphaned run(s), ${data.staleSockets.length} stale socket(s), ${data.unpushedWorktrees.length} unpushed worktree(s), ${data.errors.length} error(s).` };
|
|
379
|
+
return { payload: { data }, human: `Watchdog sweep: ${data.orphanedRuns.length} orphaned run(s), ${data.unwatchedRuns.length} unwatched run(s), ${data.staleSockets.length} stale socket(s), ${data.unpushedWorktrees.length} unpushed worktree(s), ${data.errors.length} error(s).` };
|
|
364
380
|
}
|
|
365
381
|
throw new CliError("USAGE", "watchdog install [--interval SECONDS] | watchdog sweep", 2);
|
|
366
382
|
}
|