@nodii/dev 0.6.175 → 0.6.176
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 +169 -19
- 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/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 +69 -6
- 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
|
@@ -442,7 +442,7 @@ export async function repoReviewState(dir) {
|
|
|
442
442
|
return {
|
|
443
443
|
root,
|
|
444
444
|
head: await git(root, "rev-parse", "HEAD"),
|
|
445
|
-
base: await
|
|
445
|
+
base: await reviewBase(root).catch(() => null),
|
|
446
446
|
receipt: receiptText ? JSON.parse(receiptText) : null,
|
|
447
447
|
};
|
|
448
448
|
}
|
|
@@ -671,16 +671,69 @@ export function commandViolations(raw, context) {
|
|
|
671
671
|
return violations;
|
|
672
672
|
}
|
|
673
673
|
|
|
674
|
+
/**
|
|
675
|
+
* A path with its nearest existing ancestor resolved through symlinks, so a
|
|
676
|
+
* new file in a new directory compares against real worktree roots (macOS
|
|
677
|
+
* /var is /private/var) the same way an existing file does.
|
|
678
|
+
*/
|
|
679
|
+
async function realAncestorPath(path) {
|
|
680
|
+
const rest = [];
|
|
681
|
+
let current = path;
|
|
682
|
+
for (;;) {
|
|
683
|
+
try {
|
|
684
|
+
return join(await realpath(current), ...rest.reverse());
|
|
685
|
+
} catch {
|
|
686
|
+
const parent = dirname(current);
|
|
687
|
+
if (parent === current) return path;
|
|
688
|
+
rest.push(basename(current));
|
|
689
|
+
current = parent;
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
|
|
674
694
|
/** Edit-tool ownership and generated-file blocks. */
|
|
675
695
|
export async function editViolations(paths, context) {
|
|
676
696
|
const violations = [];
|
|
677
697
|
const root = await realpath(context.root).catch(() => resolve(context.root));
|
|
678
698
|
for (const path of paths) {
|
|
679
699
|
const unresolved = isAbsolute(path) ? resolve(path) : resolve(context.cwd, path);
|
|
680
|
-
const absolute = await
|
|
700
|
+
const absolute = await realAncestorPath(unresolved);
|
|
681
701
|
const rel = cleanPath(relative(root, absolute));
|
|
682
702
|
if (rel === ".." || rel.startsWith("../") || isAbsolute(rel)) {
|
|
683
|
-
|
|
703
|
+
// NODII-DEV-CLI-191: a lane that holds several repositories edits in
|
|
704
|
+
// every worktree it holds; only a path outside all of them is refused.
|
|
705
|
+
// `safetyContext` sets `context.loadLaneRoots` for a proven lane (its
|
|
706
|
+
// worktrees from Dev's lane record and Freeze boundaries, `laneWorktrees`);
|
|
707
|
+
// a session with no lane has none, so its fence stays its repository.
|
|
708
|
+
// Each worktree's own owned paths and generated files apply there.
|
|
709
|
+
const laneRoots = typeof context.loadLaneRoots === "function" ? await context.loadLaneRoots().catch(() => []) : [];
|
|
710
|
+
let home = null;
|
|
711
|
+
for (const laneRoot of laneRoots ?? []) {
|
|
712
|
+
const real = await realpath(laneRoot).catch(() => resolve(laneRoot));
|
|
713
|
+
const other = cleanPath(relative(real, absolute));
|
|
714
|
+
if (real !== root && !(other === ".." || other.startsWith("../") || isAbsolute(other))) home = { root: real, rel: other };
|
|
715
|
+
}
|
|
716
|
+
if (!home) {
|
|
717
|
+
violations.push({ code: "SAFETY_EDIT_OUTSIDE_REPO", message: `Edit blocked outside the lane's repositories: ${path}.` });
|
|
718
|
+
continue;
|
|
719
|
+
}
|
|
720
|
+
// That repository's own owned paths and generated files apply (P-8).
|
|
721
|
+
// Its record is the lane's repository row, else its Freeze boundary; a
|
|
722
|
+
// worktree neither describes fails closed, since its owned paths can't be read.
|
|
723
|
+
let repository = null;
|
|
724
|
+
for (const item of [...(context.lane?.repositories ?? []), ...(context.lane?.freeze?.boundaries?.repos ?? [])])
|
|
725
|
+
if (!repository && item?.worktree && (await realpath(item.worktree).catch(() => resolve(item.worktree))) === home.root) repository = item;
|
|
726
|
+
if (!repository) {
|
|
727
|
+
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.` });
|
|
728
|
+
continue;
|
|
729
|
+
}
|
|
730
|
+
const owned = (repository.ownedPaths ?? []).map((item) => (isAbsolute(item) ? cleanPath(relative(home.root, item)) : cleanPath(item)));
|
|
731
|
+
if (owned.length && !owned.some((x) => globPattern(x).test(home.rel))) {
|
|
732
|
+
violations.push({ code: "SAFETY_EDIT_OUTSIDE_SCOPE", message: `Edit blocked outside the lane's owned paths in ${home.root}: ${home.rel}.` });
|
|
733
|
+
continue;
|
|
734
|
+
}
|
|
735
|
+
if (await generatedFile(home.rel, { ...context, root: home.root, generatedPaths: await harnessGenerated(home.root) }))
|
|
736
|
+
violations.push({ code: "SAFETY_EDIT_GENERATED", message: `Edit blocked for generated file ${home.rel} in ${home.root}; change its source and regenerate it.` });
|
|
684
737
|
continue;
|
|
685
738
|
}
|
|
686
739
|
if (context.ownedPaths.length && !context.ownedPaths.some((x) => globPattern(x).test(rel))) {
|
|
@@ -783,7 +836,7 @@ export async function safetyContext(cwd = process.cwd(), { request = devRequest,
|
|
|
783
836
|
const root = await realpath(await git(cwd, "rev-parse", "--show-toplevel"));
|
|
784
837
|
const branch = await git(cwd, "branch", "--show-current");
|
|
785
838
|
const head = await git(cwd, "rev-parse", "HEAD");
|
|
786
|
-
const base = await
|
|
839
|
+
const base = await reviewBase(cwd);
|
|
787
840
|
let config = null;
|
|
788
841
|
try { config = await configReader(false); } catch {}
|
|
789
842
|
const configuredPath = env.NODII_DEV_CONFIG_PATH ?? configPath();
|
|
@@ -940,11 +993,21 @@ export async function safetyPostHook(payload) {
|
|
|
940
993
|
return { recorded: false };
|
|
941
994
|
}
|
|
942
995
|
|
|
943
|
-
/**
|
|
996
|
+
/**
|
|
997
|
+
* NODII-DEV-CLI-191: the base a review covers is the branch's merge base with
|
|
998
|
+
* origin/main, the diff a PR shows. origin/main's tip moved with every merge by
|
|
999
|
+
* anyone, so a check longer than the gap between merges went REVIEW_FILE_STALE
|
|
1000
|
+
* on a busy repository. Without a merge base, the tip, as before.
|
|
1001
|
+
*/
|
|
1002
|
+
export async function reviewBase(cwd = process.cwd()) {
|
|
1003
|
+
return git(cwd, "merge-base", "origin/main", "HEAD").catch(() => git(cwd, "rev-parse", "origin/main"));
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
/** The exact commit and origin/main merge base a review and its local receipt cover. */
|
|
944
1007
|
export async function reviewCommitContext(cwd = process.cwd()) {
|
|
945
1008
|
return {
|
|
946
1009
|
commit: await git(cwd, "rev-parse", "HEAD"),
|
|
947
|
-
base: await
|
|
1010
|
+
base: await reviewBase(cwd),
|
|
948
1011
|
};
|
|
949
1012
|
}
|
|
950
1013
|
|
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,
|
package/dist/starting.js
CHANGED
|
@@ -14,6 +14,7 @@ import { hostBootedAt } from "./host.js";
|
|
|
14
14
|
import { cachedGet, laneReadCache } from "./read-cache.js";
|
|
15
15
|
import { clearCoordinatorMarker, coordinatorMarkerPath } from "./coordinator-items.js";
|
|
16
16
|
import { accountFlags, listAccounts, profilePath, registerAccount, reportUsage, usageLine } from "./accounts.js";
|
|
17
|
+
import { subagentBudgetLine } from "./lane-supervisor.js";
|
|
17
18
|
|
|
18
19
|
const execFile = promisify(execFileCallback);
|
|
19
20
|
const via = { via: "nodii-dev" };
|
|
@@ -693,7 +694,8 @@ export async function launchLaneCommand(key, flags, {
|
|
|
693
694
|
profileHome: body.profile,
|
|
694
695
|
cwd: repositories[0].worktree,
|
|
695
696
|
addDirs: repositories.slice(1).map(({ worktree }) => worktree),
|
|
696
|
-
|
|
697
|
+
// NODII-DEV-CLI-191: the brief names the subagent budget.
|
|
698
|
+
prompt: [payload.data.brief, subagentBudgetLine(payload.data.lane?.subagentQuota ?? body.subagentQuota)].filter(Boolean).join("\n\n"),
|
|
697
699
|
runId: payload.data.run.id,
|
|
698
700
|
});
|
|
699
701
|
} catch (error) {
|
|
@@ -978,8 +980,8 @@ export async function currentMarker(run = execFile, load = loadJson, env = proce
|
|
|
978
980
|
return { ...marker, runId };
|
|
979
981
|
}
|
|
980
982
|
|
|
981
|
-
// An amendment, a leeway, a question and its answer or deferral change no brief by themselves.
|
|
982
|
-
const GUARD_EXEMPT_LANE_ACTIONS = new Set(["amend", "leeway", "ask", "asks", "answer", "defer"]);
|
|
983
|
+
// An amendment, a leeway, a question and its answer or deferral, and a lane message change no brief by themselves.
|
|
984
|
+
const GUARD_EXEMPT_LANE_ACTIONS = new Set(["amend", "leeway", "ask", "asks", "answer", "defer", "message", "inbox"]);
|
|
983
985
|
|
|
984
986
|
/**
|
|
985
987
|
* MW1-12.9: what a lane hook tells a long-running session about an amendment
|