@nodii/dev 0.6.73 → 0.6.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/nudges.js CHANGED
@@ -309,6 +309,100 @@ export async function migrationNudges({ path, rel, existed, after }, knowledge)
309
309
  return notes.map((note) => `nodii-dev nudge: ${note}.`);
310
310
  }
311
311
 
312
+ // ─── Surface generation (MW8-17): every design-system session ─────────────
313
+
314
+ // A product page's source, not its tests, stories, fixtures or catalog data.
315
+ const SURFACE_PAGE = /(?:^|\/)packages\/blocks\/src\/product-pages\/(?:.*\/)?[^/]+\.tsx$/;
316
+ const NOT_SURFACE_SOURCE = /\.(?:test|spec|stories|story|catalog|fixtures?|guidelines)\.tsx$|-(?:fixtures?|catalog|data|mocks?)\.tsx$/;
317
+ export const surfacePageSource = (path) => SURFACE_PAGE.test(cleanPath(path)) && !NOT_SURFACE_SOURCE.test(cleanPath(path));
318
+
319
+ // A JSX opening tag: `<` not glued to an identifier (so `useState<T>` and `Array<T>` are not tags).
320
+ const JSX_TAG = /(?<![\w$.)\]])<([A-Za-z][\w.:-]*)(?=[\s/>])/g;
321
+ const LOOK_ATTRS = new Set(["className", "style"]);
322
+
323
+ /** The end of a `{…}` starting at `at`, by brace depth alone (as jsxOpenTags does). */
324
+ function braceEnd(source, at) {
325
+ let depth = 0;
326
+ for (let i = at; i < source.length; i += 1) {
327
+ if (source[i] === "{") depth += 1;
328
+ else if (source[i] === "}" && --depth === 0) return i + 1;
329
+ }
330
+ return source.length;
331
+ }
332
+
333
+ /**
334
+ * Every JSX element in order, as its tag and its look (className and style
335
+ * values), with the source range of its opening tag. Data props and callbacks
336
+ * are left out on purpose: changing them is not a visual change (DS-BLK-1).
337
+ */
338
+ export function jsxLooks(text) {
339
+ const source = String(text);
340
+ const out = [];
341
+ for (const match of source.matchAll(JSX_TAG)) {
342
+ let at = match.index + match[0].length;
343
+ const look = [];
344
+ while (at < source.length) {
345
+ while (/\s/.test(source[at] ?? "")) at += 1;
346
+ const char = source[at];
347
+ if (char === undefined || char === ">") { at += 1; break; }
348
+ if (char === "/" && source[at + 1] === ">") { at += 2; break; }
349
+ if (char === "{") { at = braceEnd(source, at); continue; }
350
+ const name = /^[\w:-]+/.exec(source.slice(at))?.[0];
351
+ if (!name) { at += 1; continue; }
352
+ at += name.length;
353
+ while (/\s/.test(source[at] ?? "")) at += 1;
354
+ if (source[at] !== "=") continue;
355
+ at += 1;
356
+ while (/\s/.test(source[at] ?? "")) at += 1;
357
+ const start = at;
358
+ if (source[at] === '"' || source[at] === "'") { const close = source.indexOf(source[at], at + 1); at = close === -1 ? source.length : close + 1; }
359
+ else if (source[at] === "{") at = braceEnd(source, at);
360
+ if (LOOK_ATTRS.has(name)) look.push(`${name}=${source.slice(start, at).replace(/\s+/g, " ")}`);
361
+ }
362
+ out.push({ tag: match[1], look: look.join(" "), start: match.index, end: at });
363
+ }
364
+ return out;
365
+ }
366
+
367
+ // Styling code outside an opening tag: a class list or style object built in a variable.
368
+ const STYLE_CODE = /\bclassName\b|\bstyle\s*[:=]|\b(?:cn|clsx|cva|twMerge|classNames)\s*\(/;
369
+ const outsideTags = (text, looks) => looks.reduceRight((out, { start, end }) => out.slice(0, start) + " " + out.slice(end), String(text));
370
+
371
+ /** Whether an edit changes JSX elements, classNames or styles, as opposed to data and wiring alone. */
372
+ export function visualEdit(before, after) {
373
+ const was = jsxLooks(before);
374
+ const now = jsxLooks(after);
375
+ const shape = (looks) => looks.map(({ tag, look }) => `${tag} ${look}`).join("\n");
376
+ if (shape(was) !== shape(now)) return true;
377
+ const a = outsideTags(before, was);
378
+ const b = outsideTags(after, now);
379
+ return [...changedLines(a, b), ...changedLines(b, a)].some((line) => STYLE_CODE.test(line));
380
+ }
381
+
382
+ export const SURFACE_GEN_NUDGE = "nodii-dev nudge: You're editing a Surface's visual code. Product pages are generated from their Surfaces through Code Connect (MW8-17). Editing visuals here by hand probably breaks that rule, and the surface-gen-equal gate will refuse it. Change the Surface in Figma, the component's Code Connect template, or the generator instead. Data props and callbacks (DS-BLK-1) are fine to edit.";
383
+
384
+ /** A product page's visual code edited by hand (MW8-17). Quiet for data-only and prop-wiring edits. */
385
+ export function surfaceGenNudges({ path, rel, before, after }) {
386
+ if (!surfacePageSource(rel ?? path ?? "")) return [];
387
+ return visualEdit(before, after) ? [SURFACE_GEN_NUDGE] : [];
388
+ }
389
+
390
+ /**
391
+ * The lane-free PreToolUse entry point behind the managed dispatcher: it runs
392
+ * in every session, so it reads only the edit itself (no git, no Dev, no lane)
393
+ * and fails open to no nudge.
394
+ */
395
+ export async function surfaceGenPre(payload) {
396
+ try {
397
+ if (!EDIT_TOOLS.has(payload?.tool_name ?? "")) return [];
398
+ if (!editedPaths(payload).some(surfacePageSource)) return [];
399
+ const files = await editedFiles(payload, payload.cwd ?? process.cwd());
400
+ return files.some((file) => surfaceGenNudges(file).length) ? [SURFACE_GEN_NUDGE] : [];
401
+ } catch {
402
+ return [];
403
+ }
404
+ }
405
+
312
406
  const NODE_ID_TOOLS = /(?:get_design_context|get_metadata|get_screenshot|get_variable_defs|get_motion_context)$/;
313
407
 
314
408
  /** A code lane reading Figma by node id (MW8-20). */
@@ -460,13 +554,83 @@ export async function nudgePre(payload, context, { knowledge = laneKnowledge, fi
460
554
  if (!EDIT_TOOLS.has(tool)) return [];
461
555
  const known = await knowledge(cwd);
462
556
  const out = [];
463
- for (const file of await editedFiles(payload, cwd)) {
557
+ const files = await editedFiles(payload, cwd);
558
+ for (const file of files) {
464
559
  const edit = { ...file, rel: cleanPath(relative(root, file.path)) };
465
560
  out.push(...guidelineNudges(edit, known), ...restyleNudges(edit), ...selfPiiNudges(edit), ...(await migrationNudges(edit, known)));
466
561
  }
562
+ // Said once per call, however many pages the call edits.
563
+ if (files.some((file) => surfaceGenNudges(file).length)) out.push(SURFACE_GEN_NUDGE);
467
564
  return out;
468
565
  }
469
566
 
567
+ // ─── Cite before you steer (MW1-95) ─────────────────────────────────────────
568
+
569
+ // What a steward does to steer: an amendment, a message to a lane or the
570
+ // coordinator, a merge or a merge hold, or a new gate in a repository's gate files.
571
+ const STEER_SHELL = [
572
+ [/\b(?:nodii-dev|@nodii\/dev(?:@\S+)?)\s+lane\s+amend\b/, "lane amendment"],
573
+ [/\bgh\s+pr\s+merge\b/, "merge"],
574
+ [/\bgh\s+pr\s+(?:comment|review|edit)\b[^\n]*(?:\bhold\b|\bblock|\bdo(?: not|n't) merge\b|--request-changes\b)/i, "merge hold"],
575
+ ];
576
+ const GATE_FILE = /(?:^|\/)(?:nodii\.repo\.yaml|lefthook\.yml|\.github\/workflows\/[^/]+\.ya?ml)$/;
577
+ const DEC_ID = /\bDEC-\d{3,5}\b/;
578
+ const RULE_ID = /\b([A-Z][A-Z0-9]*(?:-[A-Z][A-Z0-9]*)*)-\d+(?:\.\d+)*\b/g;
579
+ const BODY_FILE = /--(?:body|comment|reason|message)-file[=\s]+("[^"]+"|'[^']+'|\S+)/g;
580
+
581
+ /** Which steering act this call is, or null. Pure, so most calls cost nothing. */
582
+ export function steerAct(payload) {
583
+ const tool = payload?.tool_name ?? "";
584
+ if (tool === "SendMessage") return "message to a lane or the coordinator";
585
+ if (SHELL_TOOLS.has(tool)) {
586
+ const command = String(payload.tool_input?.command ?? "");
587
+ return STEER_SHELL.find(([pattern]) => pattern.test(command))?.[1] ?? null;
588
+ }
589
+ if (EDIT_TOOLS.has(tool)) {
590
+ const path = String(payload.tool_input?.file_path ?? payload.tool_input?.notebook_path ?? "");
591
+ return GATE_FILE.test(path) ? "new gate" : null;
592
+ }
593
+ return null;
594
+ }
595
+
596
+ /** The document codes Dev holds, so an issue key such as UAT-PROD-13 is never taken for a clause. */
597
+ let documentCodes = null;
598
+ export async function ruleDocumentCodes(request = devRequest) {
599
+ if (!documentCodes)
600
+ documentCodes = request("GET", "/api/v1/documents?limit=500").then((page) => new Set((page.data ?? []).map((document) => document.code))).catch(() => { documentCodes = null; return null; });
601
+ return documentCodes;
602
+ }
603
+
604
+ /** Whether the text names a DEC id or a clause of a document Dev holds (any clause shape when Dev cannot say). */
605
+ export function citesRule(text, codes) {
606
+ const value = String(text ?? "");
607
+ if (DEC_ID.test(value)) return true;
608
+ for (const [, code] of value.matchAll(RULE_ID)) if (!codes || codes.has(code)) return true;
609
+ return false;
610
+ }
611
+
612
+ async function steerText(payload, cwd) {
613
+ const input = payload.tool_input ?? {};
614
+ if (payload.tool_name === "SendMessage") return [input.message, input.summary, input.content].filter((part) => typeof part === "string").join("\n");
615
+ if (EDIT_TOOLS.has(payload.tool_name)) return [input.new_string, input.content, ...(input.edits ?? []).map((edit) => edit?.new_string)].filter((part) => typeof part === "string").join("\n");
616
+ const command = String(input.command ?? "");
617
+ const files = await Promise.all([...command.matchAll(BODY_FILE)].map(([, path]) => optional(resolve(cwd, path.replace(/^["']|["']$/g, "")))));
618
+ return [command, ...files.filter(Boolean)].join("\n");
619
+ }
620
+
621
+ /**
622
+ * PreToolUse for a steward session only: a steering act that names no clause
623
+ * or DEC id is nudged before it goes out. It never blocks (AGENT-HARNESS-21).
624
+ */
625
+ export async function stewardSteerNudges(payload, { steward, cwd = payload?.cwd ?? process.cwd(), codes = ruleDocumentCodes } = {}) {
626
+ if (!steward) return [];
627
+ const act = steerAct(payload);
628
+ if (!act) return [];
629
+ const known = await (typeof codes === "function" ? codes() : codes);
630
+ if (citesRule(await steerText(payload, cwd), known)) return [];
631
+ return [`nodii-dev nudge: cite before you steer (MW1-95). This ${act} names no clause id (for example MW8-17) or DEC id. Name the clause or decision it rests on. With none, don't send it: the missing rule is an operator question (MW4-27), added to open.md. Impose no landing condition the rulebook lacks.`];
632
+ }
633
+
470
634
  // ─── Stop ──────────────────────────────────────────────────────────────────
471
635
 
472
636
  // A claim that the work is finished, judged a sentence at a time so "the docs are not done" cannot hide "it is done".
@@ -558,7 +722,7 @@ export async function nudgeStop(payload, context, { lastText = lastAssistantText
558
722
 
559
723
  export const nudgeSettingsSnippet = () => ({
560
724
  hooks: {
561
- PreToolUse: [{ matcher: "^(AskUserQuestion|mcp__(?:figma|claude_ai_Figma|figma-dev-mode)__.*|Bash|Edit|Write|MultiEdit|NotebookEdit)$", hooks: [{ type: "command", command: "nodii-dev hook nudge-pre" }] }],
725
+ PreToolUse: [{ matcher: "^(AskUserQuestion|SendMessage|mcp__(?:figma|claude_ai_Figma|figma-dev-mode)__.*|Bash|Edit|Write|MultiEdit|NotebookEdit)$", hooks: [{ type: "command", command: "nodii-dev hook nudge-pre" }] }],
562
726
  Stop: [{ hooks: [{ type: "command", command: "nodii-dev hook nudge-stop" }] }],
563
727
  },
564
728
  });
package/dist/review.js CHANGED
@@ -9,6 +9,7 @@ import { tmpdir } from "node:os";
9
9
  import { dirname, join } from "node:path";
10
10
  import { promisify } from "node:util";
11
11
  import { CliError, encode } from "./core.js";
12
+ import { pickerPrompt } from "./gather.js";
12
13
  import { gitPrivatePath } from "./safety.js";
13
14
 
14
15
  const execFileAsync = promisify(execFile);
@@ -277,6 +278,67 @@ export async function runReviewer(check, { runtime = "claude", model, profile, p
277
278
  }
278
279
  }
279
280
 
281
+ /** The agent pick's answer schema: one or more of the offered document codes. */
282
+ export function agentPickSchema(codes) {
283
+ return {
284
+ type: "object",
285
+ properties: { documents: { type: "array", items: { type: "string", enum: codes }, minItems: 1 } },
286
+ required: ["documents"],
287
+ additionalProperties: false,
288
+ };
289
+ }
290
+
291
+ /**
292
+ * The Delta gather's pick by the lane's runtime when the local picker fell
293
+ * back (hub-58): the same prompt and shortlist the local model gets, answered
294
+ * headless with no tools. Forced documents are always kept; Dev adds them too.
295
+ */
296
+ /** A pick is one short structured answer; it never needs the reviewer's budget. */
297
+ export const AGENT_PICK_TIMEOUT_MS = 120_000;
298
+
299
+ export async function pickByAgent({ runtime = "claude", model, profile, objective, files = [], triggers, timeoutMs = AGENT_PICK_TIMEOUT_MS, spawnImpl = spawnReviewer }) {
300
+ const codes = [...new Set(triggers.map((trigger) => trigger.code))];
301
+ const input = {
302
+ objective,
303
+ files,
304
+ triggers: triggers.map((trigger) => ({ code: trigger.code, trigger: trigger.sentence ?? trigger.trigger ?? trigger.title ?? "", ...(trigger.forcedBy ? { forcedBy: trigger.forcedBy } : {}) })),
305
+ };
306
+ const schema = agentPickSchema(codes);
307
+ const workdir = await mkdtemp(join(tmpdir(), "nodii-pick-"));
308
+ try {
309
+ const schemaFile = join(workdir, "schema.json");
310
+ const outFile = join(workdir, "answer.json");
311
+ if (runtime === "codex") await writeFile(schemaFile, JSON.stringify(schema));
312
+ const invocation = reviewerInvocation({ runtime, model, profile, schema, workdir, schemaFile, outFile });
313
+ const result = await spawnImpl({ ...invocation, cwd: workdir, input: pickerPrompt(input, schema), timeoutMs });
314
+ const name = invocation.command;
315
+ if (result.missing) throw new ReviewerError(UNAVAILABLE, `${name} is not installed or not on PATH`);
316
+ if (result.timedOut) throw new ReviewerError("TIMEOUT", `${name} gave no pick within ${Math.round(timeoutMs / 1000)} s`);
317
+ if (result.code !== 0) throw new ReviewerError("CRASH", `${name} exited ${result.code ?? "abnormally"}: ${(result.stderr || result.error || result.stdout || "").trim().slice(-500)}`);
318
+ let answer;
319
+ if (runtime === "codex") {
320
+ let text;
321
+ try { text = await readFile(outFile, "utf8"); }
322
+ catch { throw new ReviewerError("UNPARSABLE", "codex wrote no pick"); }
323
+ answer = parseJson(text, "codex's pick");
324
+ } else {
325
+ const envelope = parseJson(result.stdout, "claude's output");
326
+ if (envelope?.is_error) throw new ReviewerError("CRASH", `claude ended in error (${envelope.subtype ?? "unknown"}): ${String(envelope.result ?? "").slice(0, 500)}`);
327
+ answer = envelope?.structured_output ?? (typeof envelope?.result === "string" ? parseJson(envelope.result, "claude's pick") : null);
328
+ }
329
+ // The agent's own answer must name at least one offered document and
330
+ // nothing else: forced documents alone are not a pick (hub-58 integrity).
331
+ const answered = Array.isArray(answer?.documents) ? answer.documents : null;
332
+ if (!answered || !answered.length) throw new ReviewerError("UNPARSABLE", "the pick names no document from the shortlist");
333
+ const outside = answered.filter((code) => !codes.includes(code));
334
+ if (outside.length) throw new ReviewerError("UNPARSABLE", `the pick names documents Dev did not offer: ${outside.join(", ")}`);
335
+ const forcedCodes = input.triggers.filter((trigger) => Array.isArray(trigger.forcedBy) ? trigger.forcedBy.length : trigger.forcedBy).map((trigger) => trigger.code);
336
+ return [...new Set([...answered, ...forcedCodes])];
337
+ } finally {
338
+ await rm(workdir, { recursive: true, force: true });
339
+ }
340
+ }
341
+
280
342
  const text = (value, max) => (typeof value === "string" ? value.trim().slice(0, max) : "");
281
343
  /** The answer as Dev's finding shape, or UNPARSABLE: no finding outside the schema reaches Dev. */
282
344
  export function checkAnswer(check, answer, clauseIds = []) {
@@ -319,14 +381,24 @@ async function inBatches(items, size, work) {
319
381
  * gather over the changed paths, each with its full text. Any gap is an
320
382
  * error: a partial set is never reviewed.
321
383
  */
322
- export async function ruleClauses(ref, { request, freeze, paths, deltaGather }) {
384
+ export async function ruleClauses(ref, { request, freeze, paths, deltaGather, agentPicker }) {
323
385
  const mapped = [...(freeze?.clauseMap?.clauses ?? []), ...(freeze?.pinnedClauses ?? [])].map((x) => x.clauseId);
324
386
  if (!freeze?.clauseMap) throw new ReviewerError(UNAVAILABLE, `${ref} has no Clause map: its Freeze was never written by Gather. Run nodii-dev lane gather ${ref} first.`);
325
387
  if (paths.length > 5000) throw new ReviewerError(UNAVAILABLE, `the diff touches ${paths.length} paths; a Delta gather takes at most 5,000`);
326
388
  let delta;
327
389
  try { delta = await deltaGather(ref, paths); }
328
390
  catch (error) { throw new ReviewerError(UNAVAILABLE, `the Delta gather over the changed paths failed (${error?.code ?? "ERROR"}: ${error?.message ?? error})`); }
329
- const data = delta?.payload?.data;
391
+ let data = delta?.payload?.data;
392
+ // hub-58: no usable local picker on this Mac, so the lane's own runtime picks
393
+ // from the shortlist Dev offered, and Dev records the Gather as picker: agent.
394
+ if (data?.recorded === false && data.shortlistId && data.triggers?.length && agentPicker) {
395
+ let documents;
396
+ try { documents = await agentPicker({ objective: data.objective, files: paths, triggers: data.triggers }); }
397
+ catch (error) { throw new ReviewerError(UNAVAILABLE, `the local picker fell back (${data.fallback ?? "no local pick"}) and the agent pick failed (${error?.outcome ?? error?.code ?? "ERROR"}: ${error?.message ?? error})`); }
398
+ try { delta = await deltaGather(ref, paths, { shortlist: data.shortlistId, documents }); }
399
+ catch (error) { throw new ReviewerError(UNAVAILABLE, `recording the agent's Delta gather pick failed (${error?.code ?? "ERROR"}: ${error?.message ?? error})`); }
400
+ data = delta?.payload?.data;
401
+ }
330
402
  if (data?.recorded === false || !data?.gatherId)
331
403
  throw new ReviewerError(UNAVAILABLE, `the Delta gather over the changed paths recorded nothing${data?.fallback ? ` (${data.fallback})` : ""}; record it with nodii-dev lane gather ${ref} --delta --picker agent, then rerun lane check`);
332
404
  const ids = [...new Set([...mapped, ...(data.clauses ?? []).map((x) => x.clauseId)])].sort();
@@ -461,7 +533,7 @@ const errorCheck = (check, error, iterationCount, inputs) => ({ check, outcome:
461
533
  * caller saves the round (saveLoop) once it is kept: still looping, or
462
534
  * recorded; a run that records nothing leaves the loop where it was.
463
535
  */
464
- export async function runLaneCheck(ref, flags, { request, lane, freeze, current, cwd, store, diff, deltaGather, catalog, designCheck, gate, reviewer = runReviewer, now }) {
536
+ export async function runLaneCheck(ref, flags, { request, lane, freeze, current, cwd, store, diff, deltaGather, catalog, designCheck, gate, reviewer = runReviewer, picker = pickByAgent, now }) {
465
537
  const critical = flags.critical === true;
466
538
  const maxIterations = flags["max-iterations"] === undefined ? MAX_ITERATIONS : Number(flags["max-iterations"]);
467
539
  if (!Number.isInteger(maxIterations) || maxIterations < 1 || maxIterations > 100)
@@ -494,7 +566,7 @@ export async function runLaneCheck(ref, flags, { request, lane, freeze, current,
494
566
  let gathered = null;
495
567
  try {
496
568
  if (tooLarge) throw tooLarge;
497
- gathered = await ruleClauses(ref, { request, freeze, paths: changed.paths, deltaGather });
569
+ gathered = await ruleClauses(ref, { request, freeze, paths: changed.paths, deltaGather, agentPicker: (input) => picker({ ...runner, ...input }) });
498
570
  } catch (error) {
499
571
  if (!(error instanceof ReviewerError)) throw error;
500
572
  rules = errorCheck("rules", error, firstRound("rules"), { clauseIds: [], deltaGatherId: null, clauseMapGatherId: freeze?.clauseMap?.gatherId ?? null });
package/dist/safety.js CHANGED
@@ -613,8 +613,15 @@ export const codexSafetyHooksSnippet = () => ({
613
613
  },
614
614
  });
615
615
 
616
+ // The compact entry re-grounds the Freeze; the other entry prints the session
617
+ // kind on every other start, and the first prompt confirms it (MW1-92). Two
618
+ // entries, so a repository already carrying the compact one gains only the new.
616
619
  export const regroundingHooksSnippet = () => ({
617
620
  hooks: {
618
- SessionStart: [{ matcher: "^compact$", hooks: [{ type: "command", command: "nodii-dev hook session-start" }] }],
621
+ SessionStart: [
622
+ { matcher: "^compact$", hooks: [{ type: "command", command: "nodii-dev hook session-start" }] },
623
+ { matcher: "^(startup|resume|clear)$", hooks: [{ type: "command", command: "nodii-dev hook session-start" }] },
624
+ ],
625
+ UserPromptSubmit: [{ hooks: [{ type: "command", command: "nodii-dev hook session-kind" }] }],
619
626
  },
620
627
  });
@@ -0,0 +1,243 @@
1
+ // Session kind (DEC-0421, MW1-92 to MW1-95).
2
+ //
3
+ // Every session is a lane, a coordinator, a steward or an operator assistant.
4
+ // SessionStart infers the kind from Dev (a lane record for the worktree, a
5
+ // steward registration for this agent, the machine's coordinator role) and
6
+ // the first prompt confirms or corrects it from the prompt's own words. Both
7
+ // print the kind with its contract. A steward is a lane of kind `steward`
8
+ // with no branch or worktree, so it reuses lane Gather, Freeze and the
9
+ // post-compaction re-grounding. Every entry point fails open: no Dev, no
10
+ // sign-in or an unknown payload ends in the operator-assistant reading.
11
+ import { mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
12
+ import { basename, dirname, join } from "node:path";
13
+ import { CliError, configPath, devRequest, encode, query, readConfig, requireFlag } from "./core.js";
14
+ import { currentLane, regroundLane } from "./freeze.js";
15
+ import { gatherText } from "./gather.js";
16
+
17
+ export const SESSION_KINDS = ["lane", "coordinator", "steward", "operator_assistant"];
18
+ const KIND_LABEL = { lane: "lane", coordinator: "coordinator", steward: "steward", operator_assistant: "operator assistant" };
19
+ const LIVE = new Set(["queued", "building", "built", "review", "on_main"]);
20
+ /** A steward's Gather objective: its role and the operator's current focus (MW1-94). */
21
+ export const stewardObjective = (focus) => `Steward role (MW1-93) for the operator's current focus: ${focus}`;
22
+ export const STEWARD_DONE_CHECK = "A steward is never done: it stewards the operator's focus until a staff person stops it (MW1-93).";
23
+ const STATE_DIR = "session-kinds";
24
+ const STATE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
25
+
26
+ export const isLaneConfig = (env = process.env) => /^lane-[a-z0-9_-]+\.json$/i.test(basename(env.NODII_DEV_CONFIG_PATH ?? ""));
27
+
28
+ /** This agent's live steward lane, or null. */
29
+ export async function activeSteward(agentId, { request = devRequest } = {}) {
30
+ if (!agentId) return null;
31
+ const page = await request("GET", `/api/v1/lanes${query({ agent: agentId, kind: "steward", limit: 20 })}`);
32
+ return (page.data ?? []).find((lane) => lane.kind === "steward" && LIVE.has(lane.status)) ?? null;
33
+ }
34
+
35
+ /** What Dev records about this session. */
36
+ export async function kindFromDev({ cwd = process.cwd(), env = process.env } = {}, { request = devRequest, config = readConfig } = {}) {
37
+ let current = null;
38
+ try { current = await config(false); } catch {}
39
+ const lane = current?.agentId ? await currentLane({ cwd }, { request, config }).catch(() => null) : null;
40
+ if (lane) return { kind: "lane", lane, source: `Dev lane ${lane.key} for this worktree` };
41
+ if (isLaneConfig(env)) return { kind: "lane", lane: null, source: `the lane config ${basename(env.NODII_DEV_CONFIG_PATH)}` };
42
+ if (!current?.agentId) return { kind: "operator_assistant", source: "no Dev sign-in in this session" };
43
+ const steward = await activeSteward(current.agentId, { request }).catch(() => null);
44
+ if (steward) return { kind: "steward", steward, source: `Dev steward registration ${steward.key} for this agent` };
45
+ const agent = (await request("GET", `/api/v1/agents/${encode(current.agentId)}`).catch(() => null))?.data;
46
+ if (agent?.role === "coordinator") return { kind: "coordinator", source: "this agent is its machine's coordinator in Dev" };
47
+ return { kind: "operator_assistant", source: "Dev has no lane, steward or coordinator record for this session" };
48
+ }
49
+
50
+ /** What the first prompt says the session is, or null when it does not say. */
51
+ export function kindFromPrompt(prompt) {
52
+ const text = String(prompt ?? "");
53
+ const lane = /\byou are (?:the )?lane\s+[`'"]?([A-Za-z][\w-]*)/i.exec(text);
54
+ if (lane) return { kind: "lane", key: lane[1] };
55
+ if (/\byou are (?:now |the |a )?steward\b|\b(?:act|work) as (?:the |a )?steward\b|\bsteward session\b/i.test(text)) return { kind: "steward" };
56
+ if (/\byou are (?:now |the |a |this machine's )?coordinator\b|\bnodii-dev coordinator start\b/i.test(text)) return { kind: "coordinator" };
57
+ return null;
58
+ }
59
+
60
+ /**
61
+ * Dev's record decides; the prompt fills in only where Dev has none, and a
62
+ * disagreement is said out loud so it is fixed in Dev, not acted on.
63
+ */
64
+ export function resolveKind(dev, prompt) {
65
+ if (!prompt) return { ...dev, notes: [] };
66
+ if (prompt.kind === dev.kind) {
67
+ const other = prompt.kind === "lane" && prompt.key && dev.lane?.key && prompt.key !== dev.lane.key;
68
+ return { ...dev, source: `${dev.source}; the prompt agrees`, notes: other ? [`The prompt names lane ${prompt.key}, but this worktree is Dev lane ${dev.lane.key}. Work ${dev.lane.key}, or open ${prompt.key}'s own worktree.`] : [] };
69
+ }
70
+ if (dev.kind !== "operator_assistant")
71
+ return { ...dev, notes: [`The prompt reads as a ${KIND_LABEL[prompt.kind]} session, but Dev records a ${KIND_LABEL[dev.kind]} (${dev.source}). Act as the ${KIND_LABEL[dev.kind]}; if the prompt is right, fix the record in Dev first.`] };
72
+ const fix = {
73
+ steward: "Register it first: `nodii-dev steward register --focus \"<the operator's focus>\" --repos <repo,...>`, then `nodii-dev lane gather <key> --picker agent` (MW1-93, MW1-94).",
74
+ lane: `Dev has no lane ${prompt.key} for this worktree and agent: check \`nodii-dev lane show ${prompt.key}\` and open the lane's own worktree before working.`,
75
+ coordinator: "Dev does not record this agent as a machine's coordinator: `nodii-dev coordinator start --machine NAME` registers it.",
76
+ }[prompt.kind];
77
+ return { kind: prompt.kind, ...(prompt.key ? { promptKey: prompt.key } : {}), source: "the prompt (Dev has no record of it yet)", notes: [fix] };
78
+ }
79
+
80
+ // A steward's title is the operator's focus itself (S01-46: a name holds no
81
+ // value that has its own field, and the kind is a field).
82
+ const focusOf = (steward) => String(steward?.title ?? "");
83
+
84
+ /** The clauses each kind's contract rests on, printed as Dev serves them (P-19). */
85
+ export const KIND_CLAUSES = {
86
+ lane: ["MW1-92"],
87
+ steward: ["MW1-92", "MW1-93", "MW1-94", "MW1-95"],
88
+ coordinator: ["MW1-92", "K01-22", "MW1-49.1"],
89
+ operator_assistant: ["MW1-92"],
90
+ };
91
+
92
+ async function clauseLines(ids, request) {
93
+ return Promise.all(ids.map(async (id) => {
94
+ try {
95
+ const [clause] = (await request("GET", `/api/v1/rules/clauses/${encode(id)}`)).data ?? [];
96
+ if (clause?.text) return `- ${id}: ${String(clause.text).replace(/\s+/g, " ").trim()}`;
97
+ } catch {}
98
+ return `- ${id}: Dev did not serve its text; read \`nodii-dev rules show ${id}\`.`;
99
+ }));
100
+ }
101
+
102
+ /** The kind's contract: the clauses it rests on, from Dev, then the session's next commands. */
103
+ export async function kindContract(resolved, { request = devRequest } = {}) {
104
+ const { kind } = resolved;
105
+ const next = {
106
+ lane: () => {
107
+ const key = resolved.lane?.key ?? resolved.promptKey ?? "<key>";
108
+ return [`Next: the Lane contract of ${key} is the work. \`nodii-dev lane gather ${key}\` if it has not gathered, then the Task; when the done check is met, \`nodii-dev lane done-check ${key}\` and \`nodii-dev lane land ${key}\`.`];
109
+ },
110
+ steward: () => {
111
+ const key = resolved.steward?.key ?? "<key>";
112
+ return [
113
+ ...(resolved.steward ? [`Focus: ${focusOf(resolved.steward)}`] : []),
114
+ `Next: \`nodii-dev lane gather ${key} --picker agent\`; steer only through the coordinator or \`nodii-dev lane amend <lane>\`, naming the clause or DEC id each time.`,
115
+ ];
116
+ },
117
+ coordinator: () => ["Next: `nodii-dev lane list` for this machine's lanes."],
118
+ operator_assistant: () => [],
119
+ }[kind]();
120
+ return ["Contract (from Dev's rulebook):", ...(await clauseLines(KIND_CLAUSES[kind], request)), ...next];
121
+ }
122
+
123
+ export async function kindText(resolved, { request = devRequest } = {}) {
124
+ return [
125
+ `Session kind: ${KIND_LABEL[resolved.kind]} (MW1-92) · from ${resolved.source}`,
126
+ `kind: ${resolved.kind}`,
127
+ ...(await kindContract(resolved, { request })),
128
+ ...(resolved.notes ?? []).map((note) => `Note: ${note}`),
129
+ ].join("\n");
130
+ }
131
+
132
+ /** The steward's stored Clause map, or how to make one (MW1-94). */
133
+ async function stewardClauseMap(steward, request) {
134
+ try {
135
+ const payload = await request("GET", `/api/v1/lanes/${encode(steward.key)}/gather`);
136
+ return `Clause map ${steward.key} (Gather ${payload.data.gatherId}). Gather again now with the operator's current focus: \`nodii-dev lane gather ${steward.key} --delta --picker agent\` (MW1-94).\n${gatherText(payload, payload.data.objective ?? "")}`;
137
+ } catch {
138
+ return `Clause map: ${steward.key} has no Gather yet. Run \`nodii-dev lane gather ${steward.key} --picker agent\` before anything else (MW1-94).`;
139
+ }
140
+ }
141
+
142
+ /** Plain text for SessionStart: the kind, its contract and, where it has one, its stored contract. */
143
+ export async function sessionStartText(payload, { request = devRequest, config = readConfig, env = process.env, dev = kindFromDev, state = writeKindState } = {}) {
144
+ const cwd = payload?.cwd ?? process.cwd();
145
+ const compact = payload?.source === "compact";
146
+ const resolved = { ...(await dev({ cwd, env }, { request, config })), notes: [] };
147
+ await state(payload?.session_id, { kind: resolved.kind, source: resolved.source }).catch(() => {});
148
+ const parts = [await kindText(resolved, { request })];
149
+ if (resolved.kind === "lane" && resolved.lane && compact) {
150
+ let context = "";
151
+ const result = await regroundLane(resolved.lane, { force: true, write: (text) => { context += text; } }, { request }).catch(() => ({ shown: false }));
152
+ // A Freeze written before it referenced the Clause map has no pointer to it.
153
+ const pointer = result.shown && !context.includes("lane gather show")
154
+ ? `\nFull Clause map: \`nodii-dev lane gather show ${resolved.lane.key}\`; one clause in full: \`nodii-dev rules show <ID>\`.`
155
+ : "";
156
+ parts.push(result.shown ? `${context.trimEnd()}${pointer}` : `Freeze re-grounding: ${resolved.lane.key} has no initialized Freeze; run \`nodii-dev lane freeze show ${resolved.lane.key}\` (and \`nodii-dev lane gather show ${resolved.lane.key}\` for its Clause map) before continuing.`);
157
+ } else if (resolved.kind === "lane" && compact)
158
+ parts.push("Freeze re-grounding: no active Dev lane with initialized Freeze was available for this worktree; run `nodii-dev lane freeze show <key>` (and `nodii-dev lane gather show <key>` for its Clause map) before continuing.");
159
+ if (resolved.kind === "steward") {
160
+ if (compact) {
161
+ let context = "";
162
+ const result = await regroundLane(resolved.steward, { force: true, write: (text) => { context += text; } }, { request }).catch(() => ({ shown: false }));
163
+ if (result.shown) parts.push(`${context.trimEnd()}\nGather again now (MW1-94): \`nodii-dev lane gather ${resolved.steward.key} --delta --picker agent\`; the full Clause map: \`nodii-dev lane gather show ${resolved.steward.key}\`.`);
164
+ else parts.push(await stewardClauseMap(resolved.steward, request));
165
+ } else parts.push(await stewardClauseMap(resolved.steward, request));
166
+ }
167
+ return parts.join("\n\n");
168
+ }
169
+
170
+ /**
171
+ * UserPromptSubmit, first prompt only: what the prompt says the session is.
172
+ * Silent on every later prompt, and when the prompt agrees with what
173
+ * SessionStart already printed.
174
+ */
175
+ export async function firstPromptText(payload, { request = devRequest, config = readConfig, env = process.env, dev = kindFromDev, readState = readKindState, state = writeKindState } = {}) {
176
+ const session = payload?.session_id;
177
+ const before = await readState(session).catch(() => null);
178
+ if (before?.prompted) return null;
179
+ const prompt = kindFromPrompt(payload?.prompt);
180
+ const resolved = resolveKind(await dev({ cwd: payload?.cwd ?? process.cwd(), env }, { request, config }), prompt);
181
+ await state(session, { kind: resolved.kind, source: resolved.source, prompted: true }).catch(() => {});
182
+ // SessionStart already printed this kind and nothing disagrees: say so in one line.
183
+ if (before?.kind === resolved.kind && !resolved.notes.length)
184
+ return prompt ? `Session kind: ${KIND_LABEL[resolved.kind]} (MW1-92), confirmed by the first prompt.` : null;
185
+ const text = await kindText(resolved, { request });
186
+ if (resolved.kind === "steward" && resolved.steward && before?.kind !== "steward")
187
+ return `${text}\n\n${await stewardClauseMap(resolved.steward, request)}`;
188
+ return text;
189
+ }
190
+
191
+ const stateDir = () => join(dirname(configPath()), STATE_DIR);
192
+ const statePath = (session) => join(stateDir(), `${String(session).replace(/[^A-Za-z0-9_-]/g, "_")}.json`);
193
+
194
+ export async function readKindState(session) {
195
+ if (!session) return null;
196
+ return JSON.parse(await readFile(statePath(session), "utf8"));
197
+ }
198
+
199
+ /** One small file per session; files older than a week are removed as they are passed. */
200
+ export async function writeKindState(session, update, { now = Date.now() } = {}) {
201
+ if (!session) return;
202
+ const dir = stateDir();
203
+ await mkdir(dir, { recursive: true, mode: 0o700 });
204
+ let before = {};
205
+ try { before = JSON.parse(await readFile(statePath(session), "utf8")); } catch {}
206
+ const temporary = `${statePath(session)}.${process.pid}.tmp`;
207
+ await writeFile(temporary, `${JSON.stringify({ ...before, ...update, at: new Date(now).toISOString() })}\n`, { mode: 0o600 });
208
+ await rename(temporary, statePath(session));
209
+ for (const name of await readdir(dir).catch(() => [])) {
210
+ const path = join(dir, name);
211
+ const info = await stat(path).catch(() => null);
212
+ if (info && now - info.mtimeMs > STATE_TTL_MS) await rm(path, { force: true }).catch(() => {});
213
+ }
214
+ }
215
+
216
+ /**
217
+ * `nodii-dev steward register|show` (MW1-93): a steward is a lane of kind
218
+ * `steward` with no branch or worktree, started at once on its gather step.
219
+ */
220
+ export async function stewardCommand(action, args, flags, { request = devRequest, config = readConfig } = {}) {
221
+ const current = await config();
222
+ if (action === "show") {
223
+ const steward = await activeSteward(current.agentId, { request });
224
+ if (!steward) throw new CliError("STEWARD_NOT_REGISTERED", "This agent has no live steward registration; `nodii-dev steward register --focus TEXT --repos R,...` makes one.", 1);
225
+ return { payload: { data: steward }, human: (p) => `${p.data.key} · steward · ${p.data.status}\nFocus: ${focusOf(p.data)}\nRepositories: ${(p.data.repos ?? []).join(", ")}` };
226
+ }
227
+ if (action !== "register") throw new CliError("USAGE", "steward register --focus TEXT --repos R,... [--side frontend|backend] [--key KEY] | steward show", 2);
228
+ const focus = String(requireFlag(flags, "focus")).trim();
229
+ if (!focus) throw new CliError("USAGE", "steward register --focus needs the operator's focus", 2);
230
+ const repos = String(requireFlag(flags, "repos")).split(",").map((repo) => repo.trim()).filter(Boolean);
231
+ if (!repos.length) throw new CliError("USAGE", "steward register --repos needs at least one repository", 2);
232
+ const side = flags.side ?? "frontend";
233
+ if (!["frontend", "backend", "both"].includes(side)) throw new CliError("USAGE", "steward register --side is frontend, backend or both", 2);
234
+ const agent = (await request("GET", `/api/v1/agents/${encode(current.agentId)}`)).data;
235
+ if (!agent?.machineId) throw new CliError("MACHINE_REQUIRED", "The current agent is not assigned to a machine.", 1);
236
+ const key = flags.key ?? `steward-${String(agent.name ?? current.agentId).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || current.agentId.slice(0, 8)}`;
237
+ await request("POST", "/api/v1/lanes", {
238
+ key, title: focus, kind: "steward", side, repos,
239
+ agentId: current.agentId, machineId: agent.machineId, issueIds: [], via: "nodii-dev",
240
+ });
241
+ const payload = await request("POST", `/api/v1/lanes/${encode(key)}/start`, { via: "nodii-dev" });
242
+ return { payload, human: () => `Registered steward ${key} for: ${focus}\nNext (MW1-94): \`nodii-dev lane gather ${key} --picker agent\`. A new focus is a lane amendment: \`nodii-dev lane amend ${key} --objective "<focus>" --reason TEXT\`.` };
243
+ }
package/dist/setup.js CHANGED
@@ -3,7 +3,7 @@ import { dirname, join, resolve } from "node:path";
3
3
  import { CliError, checkLogin } from "./core.js";
4
4
  import { codexHooksFromClaude } from "./harness.js";
5
5
  import { regroundingHooksSnippet, safetySettingsSnippet } from "./safety.js";
6
- import { EMBED_MODEL, PICKER_MODEL, setupOllama } from "./gather.js";
6
+ import { EMBED_MODEL, pickerPin, setupOllama } from "./gather.js";
7
7
 
8
8
  export const SKILL_PATH = ".claude/skills/nodii-build-workflow/SKILL.md";
9
9
  const START = "<!-- nodii-dev build workflow:start -->";
@@ -119,21 +119,23 @@ export async function setupPlan(root = process.cwd()) {
119
119
  return changes;
120
120
  }
121
121
 
122
- export async function setupCommand(flags, { root = process.cwd(), authCheck = checkLogin, pickerSetup = setupOllama } = {}) {
122
+ export async function setupCommand(flags, { root = process.cwd(), authCheck = checkLogin, pickerSetup = setupOllama, env = process.env } = {}) {
123
123
  if (flags.yes && flags.check) throw new CliError("USAGE", "setup accepts either --yes or --check, not both.", 2);
124
124
  const changes = await setupPlan(root);
125
125
  let authenticated = true;
126
126
  try { await authCheck(); } catch { authenticated = false; }
127
+ // A model name this CLI does not pin is a usage error, not a picker gap.
128
+ const pickerModel = pickerPin(env).name;
127
129
  let pickerReady = true;
128
130
  let pickerStatus;
129
- try { pickerStatus = await pickerSetup({ check: !flags.yes }); }
131
+ try { pickerStatus = await pickerSetup({ check: !flags.yes, env }); }
130
132
  catch (error) {
131
133
  pickerReady = false;
132
134
  pickerStatus = { code: error?.code ?? "PICKER_UNAVAILABLE", message: error?.message ?? String(error) };
133
135
  }
134
136
  // Only the section embedding pin is missing: the picker itself is ready.
135
137
  const embedOnly = !pickerReady && String(pickerStatus.code).startsWith("EMBED_");
136
- const missingModels = embedOnly ? [EMBED_MODEL] : [PICKER_MODEL, EMBED_MODEL];
138
+ const missingModels = embedOnly ? [EMBED_MODEL] : [pickerModel, EMBED_MODEL];
137
139
  if (flags.check) {
138
140
  const drift = [
139
141
  ...(changes.length ? [`Workflow harness drift: ${changes.map((x) => x.relative).join(", ")}`] : []),
@@ -145,7 +147,7 @@ export async function setupCommand(flags, { root = process.cwd(), authCheck = ch
145
147
  if (!flags.yes) {
146
148
  const preview = [
147
149
  ...(changes.length ? changes.map((x) => `${x.before === null ? "+ create" : "~ update"} ${x.relative}`) : ["No workflow changes."]),
148
- pickerReady ? `Gather picker: ${PICKER_MODEL} and ${EMBED_MODEL} are ready.` : `+ ${embedOnly ? "" : "install Ollama and "}pull ${missingModels.join(" and ")}`,
150
+ pickerReady ? `Gather picker: ${pickerModel} and ${EMBED_MODEL} are ready.` : `+ ${embedOnly ? "" : "install Ollama and "}pull ${missingModels.join(" and ")}`,
149
151
  ].join("\n");
150
152
  return { payload: { dryRun: true, changed: [...changes.map((x) => x.relative), ...(!pickerReady ? missingModels.map((m) => `ollama:${m}`) : [])], authenticated, picker: pickerStatus }, human: `${preview}\n${authenticated ? "Authentication: ready." : "Authentication: not logged in; run `nodii-dev login`."}\nRun \`nodii-dev setup --yes\` to apply.` };
151
153
  }
@@ -154,5 +156,5 @@ export async function setupCommand(flags, { root = process.cwd(), authCheck = ch
154
156
  await mkdir(dirname(change.path), { recursive: true });
155
157
  await writeFile(change.path, change.content);
156
158
  }
157
- return { payload: { applied: true, changed: [...changes.map((x) => x.relative), ...(pickerStatus.changed ?? []).map((x) => `ollama:${x}`)], authenticated, picker: pickerStatus }, human: `${changes.length ? `Applied: ${changes.map((x) => x.relative).join(", ")}` : "Workflow harness already current."}\nGather picker: ${PICKER_MODEL} and ${EMBED_MODEL} ready on Ollama ${pickerStatus.version}.\n${authenticated ? "Authentication: ready." : "Not logged in; run `nodii-dev login`."}` };
159
+ return { payload: { applied: true, changed: [...changes.map((x) => x.relative), ...(pickerStatus.changed ?? []).map((x) => `ollama:${x}`)], authenticated, picker: pickerStatus }, human: `${changes.length ? `Applied: ${changes.map((x) => x.relative).join(", ")}` : "Workflow harness already current."}\nGather picker: ${pickerModel} and ${EMBED_MODEL} ready on Ollama ${pickerStatus.version}.\n${authenticated ? "Authentication: ready." : "Not logged in; run `nodii-dev login`."}` };
158
160
  }