@nodii/dev 0.6.175 → 0.6.177
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 +177 -20
- package/dist/accounts.js +62 -1
- package/dist/cli.js +98 -92
- package/dist/core.js +2 -2
- package/dist/flags.js +5 -1
- package/dist/freeze.js +35 -2
- package/dist/gather.js +14 -3
- package/dist/handrolled.js +85 -0
- package/dist/hook-handlers.js +127 -0
- package/dist/hooks.js +22 -6
- package/dist/issue-group.js +63 -0
- package/dist/lane-messages.js +313 -0
- package/dist/lane-runtime.js +7 -1
- package/dist/lane-supervisor.js +284 -19
- package/dist/lane-switches.js +32 -0
- package/dist/lanes.js +63 -15
- package/dist/managed-hooks.js +21 -2
- package/dist/nudges.js +54 -20
- package/dist/resume-gate.js +150 -0
- package/dist/runtime-launcher.js +64 -4
- package/dist/safety.js +185 -9
- package/dist/setup.js +3 -1
- package/dist/starting.js +5 -3
- package/package.json +1 -1
package/dist/nudges.js
CHANGED
|
@@ -12,7 +12,8 @@ import { promisify } from "node:util";
|
|
|
12
12
|
import { devRequest, hookLanePath } from "./core.js";
|
|
13
13
|
import { indexed, laneFigmaScope, loadDsFigmaIndex, squashName } from "./figma-scope.js";
|
|
14
14
|
import { extractFileKey, extractNodeIds, isFigmaTool, isReadTool } from "./hooks.js";
|
|
15
|
-
import { continueTaskMessage, doneCheckRecorded,
|
|
15
|
+
import { HUMAN_GATE_COMMAND, blockedIsNotExit, continueTaskMessage, doneCheckRecorded, laneRunEnds } from "./lane-supervisor.js";
|
|
16
|
+
import { inboxStopGate } from "./lane-messages.js";
|
|
16
17
|
import { patchPaths } from "./safety.js";
|
|
17
18
|
|
|
18
19
|
const execFileAsync = promisify(execFile);
|
|
@@ -639,6 +640,7 @@ const SHOUTED_DONE = /\bDONE\b/;
|
|
|
639
640
|
const NOT_DONE = /\b(?:not|isn't|aren't|wasn't|never|until|nothing is|n't)\s+(?:yet\s+)?(?:done|complete[d]?|finished)\b|\b(?:unfinished|incomplete)\b/i;
|
|
640
641
|
const claimsDone = (text) => String(text).split(/(?<=[.!?\n])\s+/).some((sentence) => (DONE_CLAIM.test(sentence) || SHOUTED_DONE.test(sentence)) && !NOT_DONE.test(sentence));
|
|
641
642
|
const COULDNT = /\b(?:I|we)\s+(?:couldn't|could not|can't|cannot|was unable to|were unable to|wasn't able to|am unable to)\b/i;
|
|
643
|
+
const ISSUE_KEY = /\b[A-Z][A-Z0-9]+(?:-[A-Z0-9]+)*-\d+\b|\bissue\s+#?\d+/;
|
|
642
644
|
const FILED = /\b[A-Z][A-Z0-9]+(?:-[A-Z0-9]+)*-\d+\b|\bfiled\b|\bissue\s+#?\d+|\bopen\.md\b/;
|
|
643
645
|
|
|
644
646
|
/** The last assistant message: the Stop payload's own, else the transcript's final one. */
|
|
@@ -661,49 +663,72 @@ export async function lastAssistantText(payload) {
|
|
|
661
663
|
const openUnconfirmed = (lane) => [lane.freeze?.unconfirmed, lane.unconfirmed].flat().filter(Boolean).filter((item) =>
|
|
662
664
|
typeof item === "string" || !(item?.resolvedAt || item?.confirmedAt || ["resolved", "confirmed", "dropped"].includes(item?.status)));
|
|
663
665
|
|
|
664
|
-
const
|
|
665
|
-
const
|
|
666
|
-
return Number.isInteger(
|
|
666
|
+
const envCount = (value, fallback) => {
|
|
667
|
+
const number = Number(value ?? fallback);
|
|
668
|
+
return Number.isInteger(number) && number >= 0 ? number : fallback;
|
|
667
669
|
};
|
|
670
|
+
// NODII-DEV-CLI-191: a cost backstop well above any real run's stops; the
|
|
671
|
+
// no-progress guard is what ends a loop.
|
|
672
|
+
const stopBlockLimit = (env) => envCount(env.NODII_DEV_STOP_BLOCK_LIMIT, 40);
|
|
673
|
+
const stopStallLimit = (env) => envCount(env.NODII_DEV_STOP_STALL_LIMIT, 2);
|
|
674
|
+
|
|
675
|
+
/** The session's tool calls so far, from its transcript; null when unreadable. */
|
|
676
|
+
export async function transcriptToolUses(path) {
|
|
677
|
+
if (!path) return null;
|
|
678
|
+
const text = await optional(path).catch(() => null);
|
|
679
|
+
if (text == null) return null;
|
|
680
|
+
return (String(text).match(/"type"\s*:\s*"tool_use"/g) ?? []).length;
|
|
681
|
+
}
|
|
668
682
|
|
|
669
683
|
/**
|
|
670
684
|
* NODII-DEV-CLI-8 (hub-58, gate for AGENT-HARNESS-13): a lane session may not
|
|
671
|
-
* stop before its done check is recorded
|
|
672
|
-
*
|
|
673
|
-
* (`
|
|
674
|
-
*
|
|
675
|
-
*
|
|
676
|
-
*
|
|
685
|
+
* stop before its done check is recorded. NODII-DEV-CLI-191: BLOCKED is not an
|
|
686
|
+
* exit. A blocker the lane can claim and fix holds the stop; only a typed
|
|
687
|
+
* human gate (`laneHumanGate`: operator TOTP, a steward-only step, spend, an
|
|
688
|
+
* operator question or decision) lets it through. The lane is read fresh: the
|
|
689
|
+
* lane this hook call just read from Dev by key (`context.laneDetail`), else
|
|
690
|
+
* one slim read here (hub-528). An unreadable lane lets the stop through.
|
|
691
|
+
* The no-progress guard: a stop held NODII_DEV_STOP_STALL_LIMIT (2) times in a
|
|
692
|
+
* row with no new tool call in between is let through, and the count starts
|
|
693
|
+
* over. NODII_DEV_STOP_BLOCK_LIMIT (40) caps the holds a session gets in a row.
|
|
677
694
|
*/
|
|
678
|
-
export async function doneCheckStopGate(payload, context, { request = devRequest, env = process.env, state = (update) => writePrivateJson(context.root, STOP_GATE, update) } = {}) {
|
|
695
|
+
export async function doneCheckStopGate(payload, context, { request = devRequest, env = process.env, state = (update) => writePrivateJson(context.root, STOP_GATE, update), toolUses = transcriptToolUses } = {}) {
|
|
679
696
|
if (context?.role !== "lane" || !context.lane?.key) return null;
|
|
680
697
|
let lane;
|
|
681
698
|
if (context.laneDetail === true) lane = context.lane;
|
|
682
699
|
else try { lane = (await request("GET", hookLanePath(context.lane.key))).data; } catch { return null; }
|
|
683
700
|
const session = String(payload.session_id ?? "");
|
|
684
701
|
const forget = (before) => { const sessions = { ...before.sessions }; delete sessions[session]; return { sessions }; };
|
|
685
|
-
if (!lane || doneCheckRecorded(lane) ||
|
|
702
|
+
if (!lane || doneCheckRecorded(lane) || laneRunEnds(lane, env)) {
|
|
686
703
|
await state(forget).catch(() => {});
|
|
687
704
|
return null;
|
|
688
705
|
}
|
|
689
|
-
|
|
706
|
+
const tools = await toolUses(payload.transcript_path).catch(() => null);
|
|
707
|
+
let release = false;
|
|
690
708
|
try {
|
|
691
709
|
await state((before) => {
|
|
692
|
-
|
|
693
|
-
|
|
710
|
+
const last = before.sessions?.[session];
|
|
711
|
+
const previous = typeof last === "number" ? { held: last } : (last ?? {});
|
|
712
|
+
const held = (previous.held ?? 0) + 1;
|
|
713
|
+
const stalls = tools != null && previous.tools != null && tools <= previous.tools ? (previous.stalls ?? 0) + 1 : 0;
|
|
714
|
+
release = held > stopBlockLimit(env) || stalls >= stopStallLimit(env);
|
|
715
|
+
return release ? forget(before) : { sessions: { ...before.sessions, [session]: { held, tools, stalls } } };
|
|
694
716
|
});
|
|
695
717
|
} catch {
|
|
696
718
|
// No count to hold against: block once, as the other Stop nudges do.
|
|
697
|
-
|
|
719
|
+
release = Boolean(payload.stop_hook_active);
|
|
698
720
|
}
|
|
699
|
-
if (
|
|
700
|
-
return continueTaskMessage(context.lane.key, lane);
|
|
721
|
+
if (release) return null;
|
|
722
|
+
return continueTaskMessage(context.lane.key, lane, env);
|
|
701
723
|
}
|
|
702
724
|
|
|
703
725
|
/** Stop nudges. A lane that has just been nudged once is left to stop (stop_hook_active). */
|
|
704
|
-
export async function nudgeStop(payload, context, { lastText = lastAssistantText, status = (root) => git(root, "status", "--porcelain"), gate = doneCheckStopGate } = {}) {
|
|
726
|
+
export async function nudgeStop(payload, context, { lastText = lastAssistantText, status = (root) => git(root, "status", "--porcelain"), gate = doneCheckStopGate, inbox = inboxStopGate } = {}) {
|
|
705
727
|
const lane = context?.lane;
|
|
706
728
|
if (!lane) return [];
|
|
729
|
+
// NODII-DEV-CLI-191: unread lane messages hold the stop first, even after an earlier block; each is delivered once.
|
|
730
|
+
const mail = await inbox(payload, context).catch(() => null);
|
|
731
|
+
if (mail) return [mail];
|
|
707
732
|
// The done-check gate holds the stop even after an earlier block (stop_hook_active).
|
|
708
733
|
const held = await gate(payload, context).catch(() => null);
|
|
709
734
|
if (held) return [held];
|
|
@@ -712,7 +737,16 @@ export async function nudgeStop(payload, context, { lastText = lastAssistantText
|
|
|
712
737
|
const text = await lastText(payload);
|
|
713
738
|
if (claimsDone(text) && lane.status !== "on_dev")
|
|
714
739
|
notes.push(`${lane.key} reads ${lane.status}, not on_dev: done means merged, deployed and verified live on dev (MW3). Run \`nodii-dev lane show ${lane.key}\`, and say what is left instead of "done"`);
|
|
715
|
-
|
|
740
|
+
// NODII-DEV-CLI-191: a blocker is the lane's to fix, not to file and stop on.
|
|
741
|
+
// NODII-DEV-CLI-191: with NODII_DEV_BLOCKED_NOT_EXIT=1 a blocker is the lane's to
|
|
742
|
+
// fix, not to file and stop on; off, the ratified text (MW1-12.6, DEC-0486).
|
|
743
|
+
if (COULDNT.test(text) && blockedIsNotExit()) {
|
|
744
|
+
const cited = text.match(ISSUE_KEY)?.[0];
|
|
745
|
+
const gateLine = `. Stop only on a typed human gate (\`${HUMAN_GATE_COMMAND(lane.key)}\`)`;
|
|
746
|
+
notes.push(cited
|
|
747
|
+
? `you said you couldn't do something and cited ${cited}: claim it and fix it with your subagents (\`nodii-dev lane leeway\` when another lane's work blocks you), and keep working what is not blocked${gateLine}`
|
|
748
|
+
: `you said you couldn't do something: fix it, or claim it and fix it with your subagents (\`nodii-dev issues create\` then \`nodii-dev lane leeway\` when no issue covers it yet). File and leave only what this lane must not do${gateLine}`);
|
|
749
|
+
} else if (COULDNT.test(text) && !FILED.test(text))
|
|
716
750
|
notes.push('you said you couldn\'t do something and cited no filed issue; file it (`nodii-dev issues create`, or a request or drift entry) so it is not lost. If it blocks this lane and is an open issue that no live lane holds, do not stop there: ask for leeway with `nodii-dev lane leeway` (MW1-12.6, DEC-0486)');
|
|
717
751
|
const unconfirmed = openUnconfirmed(lane);
|
|
718
752
|
if (unconfirmed.length)
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { execFile as execFileCallback } from "node:child_process";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
4
|
+
import { dirname } from "node:path";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
import { devRequest, encode } from "./core.js";
|
|
7
|
+
|
|
8
|
+
const execFile = promisify(execFileCallback);
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* NODII-DEV-CLI-191: a lane is resumed only when what blocks it changed.
|
|
12
|
+
* Watchers resumed lanes on a timer and on process presence, so 1,600 of
|
|
13
|
+
* 2,067 runs in 12-17 Nov added nothing; seven "still blocked" re-checks
|
|
14
|
+
* missed a fix that had merged twelve hours earlier because they read issue
|
|
15
|
+
* status alone. The fingerprint reads each blocker's real state: a PR's state,
|
|
16
|
+
* head and merge commit; an issue's status; a blocking lane's status; plus the
|
|
17
|
+
* lane's own leeways and amendments. Heartbeat notes are narration and are
|
|
18
|
+
* never part of it.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
const TERMINAL_ISSUE = new Set(["done", "wont_do", "closed", "cancelled", "canceled", "superseded", "duplicate"]);
|
|
22
|
+
// Before deploy a lane still has building to do; from deploy on, merged work is expected.
|
|
23
|
+
const BUILDING_STEPS = new Set(["gather", "identify", "build_test", "build", "adopt_test", "local_test", "draft"]);
|
|
24
|
+
|
|
25
|
+
const prKey = (ref) => {
|
|
26
|
+
const url = /github\.com\/([^/]+\/[^/]+)\/pull\/(\d+)/.exec(ref ?? "");
|
|
27
|
+
if (url) return `${url[1]}#${url[2]}`;
|
|
28
|
+
return /^[\w.-]+\/[\w.-]+#\d+$/.test(ref ?? "") ? ref : null;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
async function ghPrState(ref) {
|
|
32
|
+
const [repo, number] = ref.split("#");
|
|
33
|
+
const { stdout } = await execFile("gh", ["pr", "view", number, "--repo", repo, "--json", "state,headRefOid,mergeCommit"], { timeout: 20_000 });
|
|
34
|
+
const data = JSON.parse(stdout);
|
|
35
|
+
return { state: data.state, headRefOid: data.headRefOid, mergeCommit: data.mergeCommit?.oid ?? null };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The default readers: GitHub through `gh`, Dev for issues and lanes, git for branches. */
|
|
39
|
+
export function defaultReaders({ request = devRequest } = {}) {
|
|
40
|
+
return {
|
|
41
|
+
prState: ghPrState,
|
|
42
|
+
issueStatus: async (key) => (await request("GET", `/api/v1/issues/${encode(key)}`)).data?.status ?? null,
|
|
43
|
+
laneStatus: async (key) => (await request("GET", `/api/v1/lanes/${encode(key)}?view=hook`)).data?.status ?? null,
|
|
44
|
+
// MW1-30.1: landed when the branch's changed paths show no difference
|
|
45
|
+
// from origin/main (a commit count says nothing after a squash merge).
|
|
46
|
+
landed: async ({ worktree, branch }) => {
|
|
47
|
+
if (!worktree || !branch) return false;
|
|
48
|
+
await execFile("git", ["-C", worktree, "fetch", "--quiet", "origin", "main"], { timeout: 60_000 }).catch(() => {});
|
|
49
|
+
const { stdout: base } = await execFile("git", ["-C", worktree, "merge-base", "origin/main", branch], { timeout: 20_000 });
|
|
50
|
+
const { stdout: names } = await execFile("git", ["-C", worktree, "diff", "--name-only", base.trim(), branch], { timeout: 20_000 });
|
|
51
|
+
const paths = names.split("\n").filter(Boolean);
|
|
52
|
+
if (!paths.length) return false;
|
|
53
|
+
const { stdout: left } = await execFile("git", ["-C", worktree, "diff", "origin/main", branch, "--", ...paths], { timeout: 20_000, maxBuffer: 64 * 1024 * 1024 });
|
|
54
|
+
return !left.trim();
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const safely = async (label, read) => {
|
|
60
|
+
try {
|
|
61
|
+
return JSON.stringify(await read());
|
|
62
|
+
} catch (error) {
|
|
63
|
+
return `unreadable (${String(error?.code ?? error?.message ?? error).slice(0, 80)})`;
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
/** Each blocker's real state as a sorted list of parts, and their hash. */
|
|
68
|
+
export async function blockerFingerprint(lane, readers) {
|
|
69
|
+
const parts = [];
|
|
70
|
+
for (const wait of lane?.waits ?? []) {
|
|
71
|
+
const ref = wait?.targetRef;
|
|
72
|
+
if (!ref) continue;
|
|
73
|
+
const pr = wait.targetKind === "pr" || prKey(ref) ? prKey(ref) : null;
|
|
74
|
+
if (pr) parts.push(`pr ${pr}: ${await safely(pr, () => readers.prState(pr))}`);
|
|
75
|
+
else if (wait.targetKind === "issue") parts.push(`issue ${ref}: ${await safely(ref, () => readers.issueStatus(ref))}`);
|
|
76
|
+
else if (wait.targetKind === "lane" || (!wait.targetKind && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(ref)))
|
|
77
|
+
parts.push(`lane ${ref}: ${await safely(ref, () => readers.laneStatus(ref))}`);
|
|
78
|
+
else parts.push(`${wait.targetKind ?? "wait"} ${ref}`);
|
|
79
|
+
}
|
|
80
|
+
for (const leeway of lane?.leeways ?? []) parts.push(`leeway ${leeway.id} ${leeway.blockerIssueKey}: ${leeway.state}`);
|
|
81
|
+
const amendments = (lane?.amendments ?? []).map((amendment) => Number(amendment.version) || 0);
|
|
82
|
+
parts.push(`amendments: ${amendments.length ? Math.max(...amendments) : 0}`);
|
|
83
|
+
parts.sort();
|
|
84
|
+
return { fingerprint: createHash("sha256").update(parts.join("\n")).digest("hex"), parts };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Why a lane is not resumed for building, with the evidence, or null.
|
|
89
|
+
* Superseded: every issue the lane holds is closed (a dead lane). Landed: the
|
|
90
|
+
* lane has not reached deploy and every repository's branch work is on
|
|
91
|
+
* origin/main by MW1-30.1. Landed is not done (MW1-28): such a lane goes on to
|
|
92
|
+
* deploy and its dev check, and is never stopped for it.
|
|
93
|
+
*/
|
|
94
|
+
export async function deadLaneEvidence(lane, readers) {
|
|
95
|
+
const issues = (lane?.issues ?? []).map((issue) => issue?.key).filter(Boolean);
|
|
96
|
+
if (issues.length) {
|
|
97
|
+
const statuses = [];
|
|
98
|
+
for (const key of issues) statuses.push([key, await readers.issueStatus(key).catch(() => null)]);
|
|
99
|
+
if (statuses.every(([, status]) => TERMINAL_ISSUE.has(String(status))))
|
|
100
|
+
return { kind: "superseded", evidence: statuses.map(([key, status]) => `${key} is ${status}`) };
|
|
101
|
+
}
|
|
102
|
+
const step = lane?.currentBackendStep ?? lane?.currentFrontendStep;
|
|
103
|
+
const repos = (lane?.repositories ?? []).filter((repo) => repo?.worktree && repo?.branch);
|
|
104
|
+
if (repos.length && (!step || BUILDING_STEPS.has(step))) {
|
|
105
|
+
const evidence = [];
|
|
106
|
+
for (const repo of repos) {
|
|
107
|
+
if (!(await readers.landed(repo).catch(() => false))) return null;
|
|
108
|
+
evidence.push(`${repo.repo}: branch ${repo.branch} is landed (MW1-30.1): its changed paths match origin/main`);
|
|
109
|
+
}
|
|
110
|
+
return { kind: "landed", evidence };
|
|
111
|
+
}
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** The last fingerprint each lane was resumed on, in one private JSON file. */
|
|
116
|
+
export function fingerprintStore(path) {
|
|
117
|
+
const read = async () => {
|
|
118
|
+
try { return JSON.parse(await readFile(path, "utf8")); } catch { return {}; }
|
|
119
|
+
};
|
|
120
|
+
return {
|
|
121
|
+
get: async (key) => (await read())[key] ?? null,
|
|
122
|
+
set: async (key, value) => {
|
|
123
|
+
const all = await read();
|
|
124
|
+
all[key] = value;
|
|
125
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
126
|
+
const temp = `${path}.${process.pid}.tmp`;
|
|
127
|
+
await writeFile(temp, `${JSON.stringify(all, null, 2)}\n`, { mode: 0o600 });
|
|
128
|
+
await rename(temp, path);
|
|
129
|
+
},
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Whether to resume a lane now. `record()` stores the fingerprint once the
|
|
135
|
+
* resume went through, so the next look compares against what it resumed on.
|
|
136
|
+
*/
|
|
137
|
+
export async function resumeGate(lane, { store, ...readers }) {
|
|
138
|
+
const dead = await deadLaneEvidence(lane, readers);
|
|
139
|
+
if (dead?.kind === "superseded") return { resume: false, code: "LANE_DEAD", dead, reason: `${lane.key} is superseded: ${dead.evidence.join("; ")}` };
|
|
140
|
+
if (dead?.kind === "landed")
|
|
141
|
+
return { resume: false, code: "LANDED_NOT_DONE", dead, reason: `${lane.key}'s work is on main (${dead.evidence.join("; ")}), and landed is not done (MW1-28): move it to deploy and the dev check (\`nodii-dev lane step ${lane.key} --side SIDE --done build_test\`), then resume it for those steps` };
|
|
142
|
+
const now = await blockerFingerprint(lane, readers);
|
|
143
|
+
const before = await store.get(lane.key);
|
|
144
|
+
const record = () => store.set(lane.key, { fingerprint: now.fingerprint, parts: now.parts, at: new Date().toISOString() });
|
|
145
|
+
if (!before) return { resume: true, reason: "no fingerprint recorded yet", parts: now.parts, record };
|
|
146
|
+
if (before.fingerprint === now.fingerprint)
|
|
147
|
+
return { resume: false, code: "BLOCKERS_UNCHANGED", reason: `nothing that blocks ${lane.key} changed since its resume at ${before.at}`, parts: now.parts };
|
|
148
|
+
const changed = now.parts.filter((part) => !(before.parts ?? []).includes(part));
|
|
149
|
+
return { resume: true, reason: `changed: ${changed.join("; ") || "a blocker was removed"}`, parts: now.parts, record };
|
|
150
|
+
}
|
package/dist/runtime-launcher.js
CHANGED
|
@@ -6,6 +6,8 @@ import { fileURLToPath } from "node:url";
|
|
|
6
6
|
import { configPath } from "./core.js";
|
|
7
7
|
import { laneConfigName } from "./lane-env.js";
|
|
8
8
|
import { recordWatchedRun } from "./watchdog.js";
|
|
9
|
+
import { laneSwitchOn } from "./lane-switches.js";
|
|
10
|
+
import { continuationInvocation, continueTaskMessage, sessionIdFromLog, subagentBudgetLine } from "./lane-supervisor.js";
|
|
9
11
|
|
|
10
12
|
const RUNTIMES = new Set(["codex", "claude"]);
|
|
11
13
|
|
|
@@ -109,6 +111,53 @@ function amendmentsSinceFreeze(lane, freeze) {
|
|
|
109
111
|
];
|
|
110
112
|
}
|
|
111
113
|
|
|
114
|
+
/**
|
|
115
|
+
* The dead run's last conclusion: the final result or assistant text in its
|
|
116
|
+
* stream-json log tail (Claude `result`/`assistant`, Codex `agent_message`).
|
|
117
|
+
*/
|
|
118
|
+
export function lastConclusion(logTail, limit = 1500) {
|
|
119
|
+
let found = null;
|
|
120
|
+
for (const line of String(logTail ?? "").split("\n")) {
|
|
121
|
+
let entry;
|
|
122
|
+
try { entry = JSON.parse(line); } catch { continue; }
|
|
123
|
+
const content = entry?.message?.content;
|
|
124
|
+
const text = typeof entry?.result === "string" ? entry.result
|
|
125
|
+
: entry?.item?.type === "agent_message" && typeof entry.item.text === "string" ? entry.item.text
|
|
126
|
+
: entry?.type === "assistant" && Array.isArray(content) ? content.filter((part) => part?.type === "text").map((part) => part.text).join("\n")
|
|
127
|
+
: null;
|
|
128
|
+
if (text?.trim()) found = text.trim();
|
|
129
|
+
}
|
|
130
|
+
return found ? (found.length > limit ? `${found.slice(0, limit - 1)}…` : found) : null;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* NODII-DEV-CLI-191: the prompt for a resume in the dead run's own session.
|
|
135
|
+
* The session already holds the Freeze and everything it read, so this says
|
|
136
|
+
* only what it concluded, what changed, and to fix the blocker.
|
|
137
|
+
*/
|
|
138
|
+
export function buildResumePrompt(data, sessionId, env = process.env) {
|
|
139
|
+
const { runId, laneKey } = validateData(data);
|
|
140
|
+
const lane = data.lane ?? {};
|
|
141
|
+
const waits = (lane.waits ?? []).map((wait) => `- waits on ${wait.targetRef}${wait.targetKind ? ` (${wait.targetKind})` : ""}`);
|
|
142
|
+
const leeways = (lane.leeways ?? []).map((leeway) => `- leeway ${leeway.id} for ${leeway.blockerIssueKey}: ${leeway.state}`);
|
|
143
|
+
const amendments = amendmentsSinceFreeze(lane, data.recovery?.freeze);
|
|
144
|
+
return [
|
|
145
|
+
`You are lane ${laneKey}, resumed in your own session ${sessionId} as run ${runId}. You already hold your Freeze and what you read; don't re-read it, act on what changed.`,
|
|
146
|
+
"",
|
|
147
|
+
`Your last conclusion:\n${lastConclusion(data.recovery?.logTail) ?? "(none recorded)"}`,
|
|
148
|
+
"",
|
|
149
|
+
"What changed since:",
|
|
150
|
+
`- last pushed commit: ${printable(data.recovery?.lastPushedCommit)}`,
|
|
151
|
+
...waits,
|
|
152
|
+
...leeways,
|
|
153
|
+
...(amendments.length ? amendments.slice(0, -1) : ["- no amendment since your Freeze"]),
|
|
154
|
+
"",
|
|
155
|
+
continueTaskMessage(laneKey, lane),
|
|
156
|
+
...[subagentBudgetLine(lane.subagentQuota, env)].filter(Boolean),
|
|
157
|
+
"",
|
|
158
|
+
].join("\n");
|
|
159
|
+
}
|
|
160
|
+
|
|
112
161
|
/** Build the complete recovery message passed to the fresh runtime over stdin. */
|
|
113
162
|
export function buildRecoveryPrompt(data) {
|
|
114
163
|
const { runId, laneKey } = validateData(data);
|
|
@@ -317,6 +366,7 @@ export async function launchRuntime(options, {
|
|
|
317
366
|
* opened append-only and both files are private to the current user.
|
|
318
367
|
*/
|
|
319
368
|
export async function launchRecovery(payload, {
|
|
369
|
+
session = sessionIdFromLog,
|
|
320
370
|
spawnImpl = spawn,
|
|
321
371
|
fs = fsPromises,
|
|
322
372
|
stateRoot,
|
|
@@ -327,14 +377,24 @@ export async function launchRecovery(payload, {
|
|
|
327
377
|
supervisorEntry,
|
|
328
378
|
} = {}) {
|
|
329
379
|
const data = dataFrom(payload);
|
|
330
|
-
const { runId, laneKey, addDirs } = validateData(data);
|
|
380
|
+
const { runId, laneKey, addDirs, runtime } = validateData(data);
|
|
331
381
|
const devConfigPath = laneConfig(data?.launch?.devConfigPath, laneKey, "launch.devConfigPath");
|
|
332
|
-
const
|
|
333
|
-
const
|
|
382
|
+
const root = stateRoot ?? recoveryStateRoot(devConfigPath);
|
|
383
|
+
const fresh = buildRecoveryInvocation(data, { env, home });
|
|
384
|
+
// NODII-DEV-CLI-191: continue the dead run's own session when its log
|
|
385
|
+
// names one and the lane stays on the same account (a session lives in its
|
|
386
|
+
// profile); otherwise start fresh with the Freeze. Off unless
|
|
387
|
+
// NODII_DEV_SAME_SESSION_RESUME=1 until its clause is in force.
|
|
388
|
+
const sourceRunId = data.recovery?.sourceRunId;
|
|
389
|
+
const sessionId = sourceRunId && !data.accountMove && laneSwitchOn("sameSessionResume", env)
|
|
390
|
+
? await session(join(root, sourceRunId, "process.log"), runtime).catch(() => null)
|
|
391
|
+
: null;
|
|
392
|
+
const invocation = sessionId ? continuationInvocation(fresh, sessionId) : fresh;
|
|
393
|
+
const prompt = sessionId ? buildResumePrompt(data, sessionId, env) : buildRecoveryPrompt(data);
|
|
334
394
|
return launchDetached({ invocation, prompt, runId, laneKey, devConfigPath, addDirs }, {
|
|
335
395
|
spawnImpl,
|
|
336
396
|
fs,
|
|
337
|
-
stateRoot:
|
|
397
|
+
stateRoot: root,
|
|
338
398
|
watch,
|
|
339
399
|
terminate,
|
|
340
400
|
...(supervisorEntry ? { supervisorEntry } : {}),
|
package/dist/safety.js
CHANGED
|
@@ -7,6 +7,7 @@ import { promisify } from "node:util";
|
|
|
7
7
|
import { CliError, LANE_CAP_RAISE_PROMPT, LIVE_LANE_STATUSES, configPath, devRequest, encode, hookLanePath, query, readConfig } from "./core.js";
|
|
8
8
|
import { laneCapReminder } from "./watchdog.js";
|
|
9
9
|
import { heavyViolation } from "./heavy.js";
|
|
10
|
+
import { compareHandrolled } from "./handrolled.js";
|
|
10
11
|
|
|
11
12
|
const execFileAsync = promisify(execFile);
|
|
12
13
|
const ACTIVE = new Set(LIVE_LANE_STATUSES);
|
|
@@ -442,7 +443,7 @@ export async function repoReviewState(dir) {
|
|
|
442
443
|
return {
|
|
443
444
|
root,
|
|
444
445
|
head: await git(root, "rev-parse", "HEAD"),
|
|
445
|
-
base: await
|
|
446
|
+
base: await reviewBase(root).catch(() => null),
|
|
446
447
|
receipt: receiptText ? JSON.parse(receiptText) : null,
|
|
447
448
|
};
|
|
448
449
|
}
|
|
@@ -671,23 +672,188 @@ export function commandViolations(raw, context) {
|
|
|
671
672
|
return violations;
|
|
672
673
|
}
|
|
673
674
|
|
|
675
|
+
/**
|
|
676
|
+
* A path with its nearest existing ancestor resolved through symlinks, so a
|
|
677
|
+
* new file in a new directory compares against real worktree roots (macOS
|
|
678
|
+
* /var is /private/var) the same way an existing file does.
|
|
679
|
+
*/
|
|
680
|
+
async function realAncestorPath(path) {
|
|
681
|
+
const rest = [];
|
|
682
|
+
let current = path;
|
|
683
|
+
for (;;) {
|
|
684
|
+
try {
|
|
685
|
+
return join(await realpath(current), ...rest.reverse());
|
|
686
|
+
} catch {
|
|
687
|
+
const parent = dirname(current);
|
|
688
|
+
if (parent === current) return path;
|
|
689
|
+
rest.push(basename(current));
|
|
690
|
+
current = parent;
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
// hub-548: a generated Surface that DEC-0488, DEC-0494 and MW8-17.11
|
|
696
|
+
// let a lane patch inside keyed @handrolled marks.
|
|
697
|
+
const SURFACE_GENERATED = /(?:^|\/)[^/]+\.surface\.generated\.tsx$/;
|
|
698
|
+
|
|
699
|
+
/**
|
|
700
|
+
* hub-548: whether an edit to a generated Surface only adds or changes
|
|
701
|
+
* keyed `@handrolled <KEY>: ...` ... `@end-handrolled` regions. The file's text
|
|
702
|
+
* after the edit must parse (every region keyed, none nested or unclosed) and
|
|
703
|
+
* pass the surface-gen check's own test against the text before it: every byte
|
|
704
|
+
* outside the regions unchanged and in order. So the guard is no looser than
|
|
705
|
+
* the check CI runs ("Generated pages match their Surfaces"). Any other
|
|
706
|
+
* generated file, a delete or move, an after-text that can't be computed, or a
|
|
707
|
+
* call with no tool input, is not a mark edit.
|
|
708
|
+
*/
|
|
709
|
+
async function markEditAllowed(absolute, path, payload) {
|
|
710
|
+
if (!payload || !SURFACE_GENERATED.test(cleanPath(absolute))) return false;
|
|
711
|
+
const before = await optional(absolute);
|
|
712
|
+
if (before === null) return false;
|
|
713
|
+
const after = textAfterEdit(payload, path, before);
|
|
714
|
+
if (after === null) return false;
|
|
715
|
+
try {
|
|
716
|
+
const { equal, regions } = compareHandrolled(after, before);
|
|
717
|
+
return equal && regions.length > 0;
|
|
718
|
+
} catch {
|
|
719
|
+
return false;
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
function replaceOnce(text, edit) {
|
|
724
|
+
const from = typeof edit?.old_string === "string" ? edit.old_string : null;
|
|
725
|
+
if (!from || typeof edit.new_string !== "string") return null;
|
|
726
|
+
const count = text.split(from).length - 1;
|
|
727
|
+
if (!count || (count > 1 && edit.replace_all !== true)) return null;
|
|
728
|
+
return edit.replace_all === true ? text.split(from).join(edit.new_string) : text.replace(from, () => edit.new_string);
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
/** The file's text after this tool call, or null when it can't be known. */
|
|
732
|
+
export function textAfterEdit(payload, path, before) {
|
|
733
|
+
const input = payload?.tool_input ?? {};
|
|
734
|
+
switch (payload?.tool_name) {
|
|
735
|
+
case "Write":
|
|
736
|
+
return typeof input.content === "string" ? input.content : null;
|
|
737
|
+
case "Edit":
|
|
738
|
+
return replaceOnce(before, input);
|
|
739
|
+
case "MultiEdit": {
|
|
740
|
+
if (!Array.isArray(input.edits) || !input.edits.length) return null;
|
|
741
|
+
let text = before;
|
|
742
|
+
for (const edit of input.edits) if ((text = replaceOnce(text, edit)) === null) return null;
|
|
743
|
+
return text;
|
|
744
|
+
}
|
|
745
|
+
case "apply_patch":
|
|
746
|
+
return patchedText(String(input.command ?? ""), path, before);
|
|
747
|
+
default:
|
|
748
|
+
return null;
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
/**
|
|
753
|
+
* Apply a Codex patch's `*** Update File:` hunks for one path. A path the patch
|
|
754
|
+
* adds, deletes or moves, or a hunk whose old lines are not found, gives null.
|
|
755
|
+
*/
|
|
756
|
+
function patchedText(command, path, before) {
|
|
757
|
+
let section = null;
|
|
758
|
+
let found = false;
|
|
759
|
+
const hunks = [];
|
|
760
|
+
for (const line of command.split(/\r?\n/)) {
|
|
761
|
+
const header = /^\*\*\* (Add|Update|Delete) File: (.+)$/.exec(line);
|
|
762
|
+
if (header) {
|
|
763
|
+
section = header[2].trim() === path ? header[1] : null;
|
|
764
|
+
if (section && section !== "Update") return null;
|
|
765
|
+
if (section) found = true;
|
|
766
|
+
continue;
|
|
767
|
+
}
|
|
768
|
+
if (section !== "Update") continue;
|
|
769
|
+
if (/^\*\*\* Move to: /.test(line)) return null;
|
|
770
|
+
if (/^\*\*\* (?:End Patch|End of File)/.test(line)) continue;
|
|
771
|
+
if (line.startsWith("@@")) {
|
|
772
|
+
hunks.push({ anchor: line.slice(2).trim(), old: [], next: [] });
|
|
773
|
+
continue;
|
|
774
|
+
}
|
|
775
|
+
if (!hunks.length) hunks.push({ anchor: "", old: [], next: [] });
|
|
776
|
+
const hunk = hunks.at(-1);
|
|
777
|
+
const body = line.slice(1);
|
|
778
|
+
if (line === "" || line[0] === " ") { hunk.old.push(body); hunk.next.push(body); }
|
|
779
|
+
else if (line[0] === "-") hunk.old.push(body);
|
|
780
|
+
else if (line[0] === "+") hunk.next.push(body);
|
|
781
|
+
else return null;
|
|
782
|
+
}
|
|
783
|
+
if (!found || !hunks.length) return null;
|
|
784
|
+
const text = before.split("\n");
|
|
785
|
+
let at = 0;
|
|
786
|
+
for (const hunk of hunks) {
|
|
787
|
+
if (!hunk.old.length) return null;
|
|
788
|
+
if (hunk.anchor) {
|
|
789
|
+
const anchor = text.findIndex((line, index) => index >= at && line.trim() === hunk.anchor);
|
|
790
|
+
if (anchor < 0) return null;
|
|
791
|
+
at = anchor + 1;
|
|
792
|
+
}
|
|
793
|
+
const match = (same) => {
|
|
794
|
+
for (let index = at; index + hunk.old.length <= text.length; index++)
|
|
795
|
+
if (hunk.old.every((line, offset) => same(text[index + offset], line))) return index;
|
|
796
|
+
return -1;
|
|
797
|
+
};
|
|
798
|
+
let index = match((a, b) => a === b);
|
|
799
|
+
if (index < 0) index = match((a, b) => a.trimEnd() === b.trimEnd());
|
|
800
|
+
if (index < 0) return null;
|
|
801
|
+
text.splice(index, hunk.old.length, ...hunk.next);
|
|
802
|
+
at = index + hunk.next.length;
|
|
803
|
+
}
|
|
804
|
+
return text.join("\n");
|
|
805
|
+
}
|
|
806
|
+
|
|
674
807
|
/** Edit-tool ownership and generated-file blocks. */
|
|
675
|
-
export async function editViolations(paths, context) {
|
|
808
|
+
export async function editViolations(paths, context, payload = null) {
|
|
676
809
|
const violations = [];
|
|
677
810
|
const root = await realpath(context.root).catch(() => resolve(context.root));
|
|
678
811
|
for (const path of paths) {
|
|
679
812
|
const unresolved = isAbsolute(path) ? resolve(path) : resolve(context.cwd, path);
|
|
680
|
-
const absolute = await
|
|
813
|
+
const absolute = await realAncestorPath(unresolved);
|
|
681
814
|
const rel = cleanPath(relative(root, absolute));
|
|
682
815
|
if (rel === ".." || rel.startsWith("../") || isAbsolute(rel)) {
|
|
683
|
-
|
|
816
|
+
// NODII-DEV-CLI-191: a lane that holds several repositories edits in
|
|
817
|
+
// every worktree it holds; only a path outside all of them is refused.
|
|
818
|
+
// `safetyContext` sets `context.loadLaneRoots` for a proven lane (its
|
|
819
|
+
// worktrees from Dev's lane record and Freeze boundaries, `laneWorktrees`);
|
|
820
|
+
// a session with no lane has none, so its fence stays its repository.
|
|
821
|
+
// Each worktree's own owned paths and generated files apply there.
|
|
822
|
+
const laneRoots = typeof context.loadLaneRoots === "function" ? await context.loadLaneRoots().catch(() => []) : [];
|
|
823
|
+
let home = null;
|
|
824
|
+
for (const laneRoot of laneRoots ?? []) {
|
|
825
|
+
const real = await realpath(laneRoot).catch(() => resolve(laneRoot));
|
|
826
|
+
const other = cleanPath(relative(real, absolute));
|
|
827
|
+
if (real !== root && !(other === ".." || other.startsWith("../") || isAbsolute(other))) home = { root: real, rel: other };
|
|
828
|
+
}
|
|
829
|
+
if (!home) {
|
|
830
|
+
violations.push({ code: "SAFETY_EDIT_OUTSIDE_REPO", message: `Edit blocked outside the lane's repositories: ${path}.` });
|
|
831
|
+
continue;
|
|
832
|
+
}
|
|
833
|
+
// That repository's own owned paths and generated files apply (P-8).
|
|
834
|
+
// Its record is the lane's repository row, else its Freeze boundary; a
|
|
835
|
+
// worktree neither describes fails closed, since its owned paths can't be read.
|
|
836
|
+
let repository = null;
|
|
837
|
+
for (const item of [...(context.lane?.repositories ?? []), ...(context.lane?.freeze?.boundaries?.repos ?? [])])
|
|
838
|
+
if (!repository && item?.worktree && (await realpath(item.worktree).catch(() => resolve(item.worktree))) === home.root) repository = item;
|
|
839
|
+
if (!repository) {
|
|
840
|
+
violations.push({ code: "SAFETY_EDIT_OUTSIDE_SCOPE", message: `Edit blocked: no repository record of the lane describes ${home.root}, so its owned paths can't be checked.` });
|
|
841
|
+
continue;
|
|
842
|
+
}
|
|
843
|
+
const owned = (repository.ownedPaths ?? []).map((item) => (isAbsolute(item) ? cleanPath(relative(home.root, item)) : cleanPath(item)));
|
|
844
|
+
if (owned.length && !owned.some((x) => globPattern(x).test(home.rel))) {
|
|
845
|
+
violations.push({ code: "SAFETY_EDIT_OUTSIDE_SCOPE", message: `Edit blocked outside the lane's owned paths in ${home.root}: ${home.rel}.` });
|
|
846
|
+
continue;
|
|
847
|
+
}
|
|
848
|
+
if (await generatedFile(home.rel, { ...context, root: home.root, generatedPaths: await harnessGenerated(home.root) }) && !(await markEditAllowed(absolute, path, payload)))
|
|
849
|
+
violations.push({ code: "SAFETY_EDIT_GENERATED", message: `Edit blocked for generated file ${home.rel} in ${home.root}; change its source and regenerate it.` });
|
|
684
850
|
continue;
|
|
685
851
|
}
|
|
686
852
|
if (context.ownedPaths.length && !context.ownedPaths.some((x) => globPattern(x).test(rel))) {
|
|
687
853
|
violations.push({ code: "SAFETY_EDIT_OUTSIDE_SCOPE", message: `Edit blocked outside the lane's owned paths: ${rel}.` });
|
|
688
854
|
continue;
|
|
689
855
|
}
|
|
690
|
-
if (await generatedFile(rel, context))
|
|
856
|
+
if ((await generatedFile(rel, context)) && !(await markEditAllowed(absolute, path, payload)))
|
|
691
857
|
violations.push({ code: "SAFETY_EDIT_GENERATED", message: `Edit blocked for generated file ${rel}; change its source and regenerate it.` });
|
|
692
858
|
}
|
|
693
859
|
return violations;
|
|
@@ -783,7 +949,7 @@ export async function safetyContext(cwd = process.cwd(), { request = devRequest,
|
|
|
783
949
|
const root = await realpath(await git(cwd, "rev-parse", "--show-toplevel"));
|
|
784
950
|
const branch = await git(cwd, "branch", "--show-current");
|
|
785
951
|
const head = await git(cwd, "rev-parse", "HEAD");
|
|
786
|
-
const base = await
|
|
952
|
+
const base = await reviewBase(cwd);
|
|
787
953
|
let config = null;
|
|
788
954
|
try { config = await configReader(false); } catch {}
|
|
789
955
|
const configuredPath = env.NODII_DEV_CONFIG_PATH ?? configPath();
|
|
@@ -890,7 +1056,7 @@ export async function safetyPreHook(payload, contextOrResolver = safetyContext,
|
|
|
890
1056
|
if (provenLane(context)) blocked(violation);
|
|
891
1057
|
return { allowed: true, nudges: [nudgeViolation(violation)] };
|
|
892
1058
|
}
|
|
893
|
-
const violation = (await editViolations(paths, context))[0];
|
|
1059
|
+
const violation = (await editViolations(paths, context, payload))[0];
|
|
894
1060
|
if (violation && provenLane(context)) blocked(violation);
|
|
895
1061
|
return {
|
|
896
1062
|
allowed: true,
|
|
@@ -940,11 +1106,21 @@ export async function safetyPostHook(payload) {
|
|
|
940
1106
|
return { recorded: false };
|
|
941
1107
|
}
|
|
942
1108
|
|
|
943
|
-
/**
|
|
1109
|
+
/**
|
|
1110
|
+
* NODII-DEV-CLI-191: the base a review covers is the branch's merge base with
|
|
1111
|
+
* origin/main, the diff a PR shows. origin/main's tip moved with every merge by
|
|
1112
|
+
* anyone, so a check longer than the gap between merges went REVIEW_FILE_STALE
|
|
1113
|
+
* on a busy repository. Without a merge base, the tip, as before.
|
|
1114
|
+
*/
|
|
1115
|
+
export async function reviewBase(cwd = process.cwd()) {
|
|
1116
|
+
return git(cwd, "merge-base", "origin/main", "HEAD").catch(() => git(cwd, "rev-parse", "origin/main"));
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
/** The exact commit and origin/main merge base a review and its local receipt cover. */
|
|
944
1120
|
export async function reviewCommitContext(cwd = process.cwd()) {
|
|
945
1121
|
return {
|
|
946
1122
|
commit: await git(cwd, "rev-parse", "HEAD"),
|
|
947
|
-
base: await
|
|
1123
|
+
base: await reviewBase(cwd),
|
|
948
1124
|
};
|
|
949
1125
|
}
|
|
950
1126
|
|
package/dist/setup.js
CHANGED
|
@@ -2,6 +2,7 @@ import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
|
2
2
|
import { dirname, join, resolve } from "node:path";
|
|
3
3
|
import { CliError, checkLogin } from "./core.js";
|
|
4
4
|
import { codexHooksFromClaude } from "./harness.js";
|
|
5
|
+
import { heartbeatSettingsSnippet } from "./hooks.js";
|
|
5
6
|
import { regroundingHooksSnippet, safetySettingsSnippet } from "./safety.js";
|
|
6
7
|
import { EMBED_MODEL, pickerPin, setupOllama } from "./gather.js";
|
|
7
8
|
|
|
@@ -54,7 +55,8 @@ export const workflowHooks = () => {
|
|
|
54
55
|
{ hooks: [{ type: "command", command: "nodii-dev lane list --mine --json" }] },
|
|
55
56
|
...regroundingHooksSnippet().hooks.SessionStart,
|
|
56
57
|
],
|
|
57
|
-
Stop
|
|
58
|
+
// One Stop beat, the harness's own entry, so a repository set up and harnessed has one (NODII-DEV-CLI-191).
|
|
59
|
+
Stop: heartbeatSettingsSnippet().hooks.Stop,
|
|
58
60
|
PreToolUse: safety.PreToolUse,
|
|
59
61
|
PostToolUse: [
|
|
60
62
|
...safety.PostToolUse,
|