flowviant 0.28.10 → 0.30.0

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/bin/cli.mjs CHANGED
@@ -101,6 +101,16 @@ if (process.argv[2] === 'clean') {
101
101
  process.exit(0);
102
102
  }
103
103
 
104
+ // `flowviant shot <url>` — capture a headless-browser screenshot of a running
105
+ // page. Build agents shell out to this to attach REAL visual evidence to the
106
+ // delivery card. Self-contained + graceful (no browser → exit 1, agent falls
107
+ // back to text evidence); needs no credential, so it runs before the auth gate.
108
+ if (process.argv[2] === 'shot') {
109
+ const { runShot } = await import('./lib/shot.mjs');
110
+ await runShot(process.argv.slice(3));
111
+ process.exit(0);
112
+ }
113
+
104
114
  // `flowviant env <import|set|show>` — the CLI half of team env sync. Values
105
115
  // are sealed to the project pubkey ON THIS MACHINE (same write-only crypto as
106
116
  // the browser); `show` decrypts locally — it only works on an ENROLLED machine.
@@ -16,11 +16,12 @@ server. There is NO interactive user and NO terminal to ask in. The ONLY way to
16
16
  reach a human is the blocker loop. Never ask the user directly; never wait on stdin.
17
17
 
18
18
  Operate this loop:
19
- 1. Call claim_next_intent. If it returns claimed:false, output exactly ALL_CLEAR on
20
- its own line and stop.
21
- 2. Read the brief. If it has an existing "branch" (a REVISION the human bounced back),
22
- \`git checkout <branch>\` to resume your prior work and address the review feedback in
23
- the description (under " Review feedback —"). Use get_module_files / search_wiki /
19
+ 1. Call claim_next_intent to PICK UP the next task someone @mentioned you on. If it
20
+ returns claimed:false, output exactly ALL_CLEAR on its own line and stop.
21
+ 2. Read the brief, and read its "thread" FIRST that is the task conversation, and the
22
+ newest human message is usually the specific reason you were brought in. If the brief
23
+ has an existing "branch" (a REVISION), \`git checkout <branch>\` to resume your prior
24
+ work and address what the thread asks for. Use get_module_files / search_wiki /
24
25
  list_related_intents for context. Call report_progress as you go.
25
26
  3. If you hit ANYTHING only a human can decide, call report_blocker with a clear
26
27
  question (and options when you can), then call get_blocker_resolution. If it is
@@ -34,51 +35,62 @@ Operate this loop:
34
35
  the merge runs separately.
35
36
  5. Return to step 1.
36
37
 
37
- Keep every change scoped to the claimed intent. If a tool errors, report_progress with
38
- the error, then retry or report_blocker.
38
+ Keep every change scoped to the task you picked up. If a tool errors, report_progress
39
+ with the error, then retry or report_blocker.
39
40
  SECRETS: env files (.env, .dev.vars, …) hold the team's synced secrets. Their VALUES
40
41
  must NEVER appear in evidence, progress, summaries, commits, or PRs — reference keys
41
42
  by NAME only. Never commit an env file.`;
42
43
 
43
- // Single-task turn (FLEET mode): claim EXACTLY ONE intent, then stop. The daemon
44
+ // Single-task turn (FLEET mode): pick up EXACTLY ONE task, then stop. The daemon
44
45
  // owns the loop so it can reset the worktree + start a fresh conversation per task.
45
46
  export const SYSTEM_SINGLE = `You are a Flowviant build agent running FULLY AUTONOMOUSLY via the "flowviant" MCP
46
47
  server. There is NO interactive user and NO terminal to ask in. The ONLY way to
47
48
  reach a human is the blocker loop. Never ask the user directly; never wait on stdin.
48
49
 
49
50
  Do EXACTLY ONE task this turn:
50
- 1. Call claim_next_intent. If it returns claimed:false, output exactly NOTHING on its
51
- own line and stop. Do NOT retry.
52
- 2. Read the brief. If it has an existing "branch" (a REVISION the human bounced back),
53
- first \`git fetch && git checkout <branch>\` to resume YOUR prior work, and address
54
- the review feedback in the description (under "— Review feedback —"). Otherwise work
55
- from the clean base checkout. Use get_module_files / search_wiki /
51
+ 1. Call claim_next_intent to PICK UP the task someone @mentioned you on. If it returns
52
+ claimed:false, output exactly NOTHING on its own line and stop. Do NOT retry.
53
+ 2. Read the brief, and read its "thread" FIRST that is the task conversation, and the
54
+ newest human message is usually the specific reason you were brought in. If the brief
55
+ has an existing "branch" (a REVISION), first \`git fetch && git checkout <branch>\` to
56
+ resume YOUR prior work and address what the thread asks for. Otherwise work from the
57
+ clean base checkout. Use get_module_files / search_wiki /
56
58
  list_related_intents for context. report_progress as you go.
57
59
  3. If you hit ANYTHING only a human can decide, call report_blocker (with options when
58
60
  you can), then get_blocker_resolution. If unresolved, output exactly
59
61
  BLOCKED:<blockerId> on its own line and STOP. Do NOT guess past a real decision.
60
- 4. Ship: if this is a revision, \`git push\` to the SAME existing branch (the open PR
61
- updates in place) and re-call attach_pr with that same PR URL. Otherwise open ONE
62
- draft PR (git push + \`gh pr create --draft\`) and call attach_pr. Then call complete
63
- with a plain-language summary AND a criteria self-report (index into the brief's
64
- "done when" list + met true/false + a short note) your delivery card in the task
65
- thread. NEVER merge. Then output exactly DONE on its own line and stop.
66
-
67
- Do NOT claim a second intent exactly one per turn. Keep every change scoped to the
68
- claimed intent. If a tool errors, report_progress with the error, then retry or
62
+ 4. Ship this depends on the brief's "placement":
63
+ - placement "patch" (a small, targeted change landing in the owner's own checkout):
64
+ do NOT create a branch, do NOT push, do NOT open a PR. Commit your change with a
65
+ one-line message and STOP there the daemon applies it and the human keeps or
66
+ reverts it. Then call complete with a plain-language summary and the criteria
67
+ self-report.
68
+ - placement "branch" (the default): if this is a revision, \`git push\` to the SAME
69
+ existing branch (the open PR updates in place) and re-call attach_pr with that same
70
+ PR URL. Otherwise create the branch the brief names in "branchName" (\`git checkout
71
+ -b <branchName>\` — use that exact name, do not invent one), push it, open ONE draft
72
+ PR with \`gh pr create --draft\`, and call attach_pr. If the brief has a "baseBranch",
73
+ your worktree is already based on it — target the PR at it (\`--base <baseBranch>\`)
74
+ so the stack stays reviewable. Then call complete with a plain-language summary AND a
75
+ criteria self-report (index into the brief's "done when" list + met true/false + a
76
+ short note) — your delivery card in the task thread.
77
+ NEVER merge. Then output exactly DONE on its own line and stop.
78
+
79
+ Do NOT pick up a second task — exactly one per turn. Keep every change scoped to the
80
+ task you picked up. If a tool errors, report_progress with the error, then retry or
69
81
  report_blocker.
70
82
  SECRETS: env files (.env, .dev.vars, …) hold the team's synced secrets. Their VALUES
71
83
  must NEVER appear in evidence, progress, summaries, commits, or PRs — reference keys
72
84
  by NAME only. Never commit an env file.`;
73
85
 
74
86
  export const KICKOFF =
75
- 'Begin the loop: claim and complete all dispatched Flowviant intents per your instructions.';
87
+ 'Begin the loop: pick up and complete every Flowviant task you have been @mentioned on, per your instructions.';
76
88
  export const RESUME =
77
89
  'Resume. First call get_blocker_resolution for any blocker you reported; if resolved, ' +
78
- 'apply the human’s answer and continue. Otherwise keep claiming and completing ' +
79
- 'dispatched intents per your instructions.';
90
+ 'apply the human’s answer and continue. Otherwise keep picking up and completing ' +
91
+ 'the tasks you were @mentioned on, per your instructions.';
80
92
  export const SINGLE_KICKOFF =
81
- 'Claim and complete exactly ONE dispatched Flowviant intent per your instructions, then stop.';
93
+ 'Pick up and complete exactly ONE Flowviant task per your instructions, then stop.';
82
94
  export const SINGLE_RESUME =
83
95
  'Resume your current task. Call get_blocker_resolution for the blocker you reported; ' +
84
96
  'if resolved, apply the human’s answer and finish this one intent, then stop.';
@@ -259,11 +271,21 @@ Steps:
259
271
  Ground every claim in files you actually read. Be efficient — look only at the
260
272
  changed area, not the whole repo; spend little quota.`;
261
273
 
262
- export const REGROUND_KICKOFF = ({ sha, title, files, vaultDir }) =>
274
+ export const REGROUND_KICKOFF = ({ sha, title, files, vaultDir, predictedPages = [] }) =>
263
275
  `A feature just merged. Re-ground the knowledge vault (${vaultDir}) for it.\n\n` +
264
276
  `Feature: ${title}\n` +
265
277
  `Grounded commit: ${sha}\n` +
266
278
  `Changed files:\n${files.map((f) => `- ${f}`).join('\n')}\n\n` +
279
+ // The plan's own prediction, made when this work was drafted. Overlapping
280
+ // changed files against each page's frontmatter finds most of what moved, but
281
+ // misses a page whose file list has drifted or that documents a CONCEPT rather
282
+ // than a directory. This is a hint to CHECK, never a list to trust.
283
+ (predictedPages.length
284
+ ? `When this work was planned, these vault pages were expected to go stale.\n` +
285
+ `Treat it as a lead, not a fact — verify each against the code before\n` +
286
+ `editing, and ignore any that turned out to be unaffected:\n` +
287
+ `${predictedPages.map((p) => `- ${p}`).join('\n')}\n\n`
288
+ : '') +
267
289
  `Follow your instructions: update the touched vault pages (and any docs/\n` +
268
290
  `chapter that covers them), append the feature-history entry to log.md,\n` +
269
291
  `then output REGROUND_DONE.`;
@@ -511,3 +533,44 @@ export function runTurn({ prompt, resume, system, cwd, mcpConfig, label, onSpawn
511
533
  child.on('close', () => resolve(out));
512
534
  });
513
535
  }
536
+
537
+ /**
538
+ * Plan check — the ground-truth pass.
539
+ *
540
+ * Generation runs on the server, where the repo does not exist. It grounds
541
+ * itself in proxies: a module manifest (names and file counts) and wiki pages
542
+ * (summaries of code). Those are good enough to draft a plan and not good
543
+ * enough to be sure of one — the summary can be stale, the anchors can be
544
+ * guesses, and "you already have this" can be wrong in the direction that
545
+ * wastes a day.
546
+ *
547
+ * This turn runs where the checkout is. It opens the actual files and corrects
548
+ * the plan. It is READ-ONLY by construction: it reports, it never edits.
549
+ */
550
+ export const SYSTEM_PLAN_CHECK = `You are Flowviant's plan checker, running FULLY AUTONOMOUSLY in a real checkout of this repository.
551
+
552
+ You are given a set of PROPOSED tasks that were drafted by a planner with no access to this repo. Your job is to check them against the actual code and report corrections. You are READ-ONLY: read files, search, and report. Do NOT edit, create, delete, commit, or run builds.
553
+
554
+ For each proposed task, verify three things by opening real files:
555
+ 1. ALREADY BUILT — does this already exist? Only say so when you have SEEN the implementation; name the file and symbol. A similar-but-different capability is NOT already built.
556
+ 2. ANCHORS — are the listed module paths the ones this work would actually touch? Correct them to real directories that exist in this repo. Drop invented ones. Add the obvious misses.
557
+ 3. SIZE — is the points estimate plausible given how much code this really involves? Only comment when it is clearly wrong (a "1" that spans six files, an "8" that is a one-line constant).
558
+
559
+ Respond with ONLY a JSON object on the final line, no markdown fence:
560
+ {"checks":[{"id":"<the task id you were given>","alreadyBuilt":false,"evidence":"<file:symbol proving it, when alreadyBuilt>","anchors":["<corrected module paths>"],"points":<number or null>,"note":"<one short sentence, or empty>"}]}
561
+
562
+ Rules:
563
+ - Include an entry ONLY for tasks you actually have a correction or confirmation for. An empty "checks" array is a valid answer meaning "the plan looks right".
564
+ - "anchors" must be paths that EXIST in this repo. Verify before listing.
565
+ - "note" is read by a developer in a chat thread. One sentence, concrete, no preamble.
566
+ - Never invent a file path or symbol. If you could not check something, leave it out.`;
567
+
568
+ export const PLAN_CHECK_KICKOFF = ({ title, intents }) =>
569
+ `Check this plan against the real code.\n\nPLAN: ${title}\n\nPROPOSED TASKS:\n${intents
570
+ .map(
571
+ (i) =>
572
+ `- id: ${i.id}\n title: ${i.title}\n claimed anchors: ${
573
+ i.anchors.length ? i.anchors.join(', ') : '(none)'
574
+ }\n points: ${i.points}`
575
+ )
576
+ .join('\n')}\n\nOpen the files these tasks claim to touch, verify each of the three checks, then output the JSON object on the final line.`;
@@ -43,6 +43,11 @@ function argFlag(name) {
43
43
  return i >= 0 ? process.argv[i + 1] : undefined;
44
44
  }
45
45
 
46
+ /** A bare boolean flag (no value follows it). */
47
+ function hasFlag(name) {
48
+ return process.argv.includes(name);
49
+ }
50
+
46
51
  const API_BASE = process.env.FLOWVIANT_API_URL || 'https://api.flowviant.com/api/v2';
47
52
  export const MCP_URL = process.env.FLOWVIANT_MCP_URL || `${API_BASE}/mcp`;
48
53
  export const FLEET_URL = process.env.FLOWVIANT_FLEET_URL || `${API_BASE}/fleet/agents`;
@@ -73,6 +78,22 @@ export const AUTO_UPDATE = process.env.FLOWVIANT_NO_UPDATE !== '1';
73
78
  // path (one-shot `claude -p` turns) survives behind FLOWVIANT_POLL=1 as the
74
79
  // escape hatch; FLOWVIANT_LIVE=1 is still honored for old scripts.
75
80
  export const LIVE = process.env.FLOWVIANT_POLL !== '1';
81
+ /**
82
+ * Does this machine accept PATCHES — commits cherry-picked straight into your
83
+ * working checkout, with no PR and no review?
84
+ *
85
+ * Patch placement is chosen by a model, and any teammate who @mentions one of
86
+ * your agents can trigger it, so whether it happens at all belongs to whoever
87
+ * owns the checkout. Turning it off does not lose the work: the task falls back
88
+ * to branch placement and arrives as a PR like anything else.
89
+ *
90
+ * On by default — the guard that actually protects you (never touching a file
91
+ * you have uncommitted edits in) is enforced at apply time, and the whole point
92
+ * of patches is to spare you a review cycle for a nine-character diff.
93
+ * `--no-patches` or FLOWVIANT_PATCHES=0 to refuse them.
94
+ */
95
+ export const ALLOW_PATCHES =
96
+ !hasFlag('--no-patches') && process.env.FLOWVIANT_PATCHES !== '0';
76
97
  // Sent on the daemon's own HTTP calls so Cloudflare Bot Fight Mode doesn't 403
77
98
  // them (Node's default UA is treated as a bot). Claude Code sends its own UA.
78
99
  export const USER_AGENT = `flowviant/${VERSION}`;
package/bin/lib/fleet.mjs CHANGED
@@ -23,6 +23,7 @@ import {
23
23
  REFRESH_BEFORE_SECONDS,
24
24
  LIVE,
25
25
  AUTO_UPDATE,
26
+ ALLOW_PATCHES,
26
27
  } from './config.mjs';
27
28
  import { handleVersionSignal } from './update.mjs';
28
29
  import {
@@ -31,11 +32,13 @@ import {
31
32
  repoRootOrDie,
32
33
  detectBaseRef,
33
34
  originSlug,
35
+ baseBranchName,
34
36
  isValidPrUrl,
35
37
  isValidBranch,
36
38
  isSafePathSegment,
37
39
  } from './git.mjs';
38
40
  import { c, LABEL_COLORS, info, note, ok, warn, fail } from './ui.mjs';
41
+ import { revertPatch, withPatchLock } from './patch.mjs';
39
42
  import {
40
43
  sleep,
41
44
  mcpConfigFor,
@@ -48,6 +51,8 @@ import {
48
51
  SYSTEM_WIKI,
49
52
  WIKI_KICKOFF,
50
53
  SYSTEM_REGROUND,
54
+ SYSTEM_PLAN_CHECK,
55
+ PLAN_CHECK_KICKOFF,
51
56
  REGROUND_KICKOFF,
52
57
  } from './claude.mjs';
53
58
  import { runLiveWorker } from './live.mjs';
@@ -197,6 +202,13 @@ export async function runFleetDaemon() {
197
202
  info(SAFE ? 'mode · safe (restricted toolset)' : 'mode · unattended (skips permission prompts)');
198
203
  info(`repo · ${repoRoot}`);
199
204
  info(`base · ${baseRef}`);
205
+ // Stated out loud because it is the one setting that lets something else write
206
+ // into the checkout you are sitting in.
207
+ info(
208
+ ALLOW_PATCHES
209
+ ? 'patches· accepted — small changes land in your checkout for Keep/Revert (--no-patches to refuse)'
210
+ : 'patches· refused — everything arrives as a branch + PR'
211
+ );
200
212
  info(`server · ${FLEET_URL}`);
201
213
  console.log('');
202
214
  await preflight({ needGit: true });
@@ -301,6 +313,149 @@ export async function runFleetDaemon() {
301
313
  /* best-effort — the job reappears next poll if this failed */
302
314
  }
303
315
  };
316
+ // Patch reverts: a patch landed straight in this checkout, and a human took it
317
+ // back. The commits are HERE, not on the server, so the reverse-apply happens
318
+ // here too — a revert, never a reset, because the owner has almost certainly
319
+ // worked on top by now. Serialised through the same lock as applies.
320
+ const PATCH_REVERT_DONE_URL = FLEET_URL.replace(/\/agents\/?$/, '/patch-revert-done');
321
+ const reverting = new Set();
322
+ const processPatchRevertJobs = (jobs) => {
323
+ for (const job of jobs ?? []) {
324
+ if (!job || typeof job.id !== 'string' || !Array.isArray(job.shas)) continue;
325
+ if (reverting.has(job.id)) continue;
326
+ reverting.add(job.id);
327
+ (async () => {
328
+ try {
329
+ note(`${c.cyan('revert')} ${c.dim(`— ${job.title}`)}`);
330
+ const res = await withPatchLock(() =>
331
+ Promise.resolve(revertPatch({ repoRoot, shas: job.shas }))
332
+ );
333
+ if (res.ok) ok(`${c.dim('reverted')} ${job.title}`);
334
+ else warn(`revert failed for "${job.title}": ${res.error}`);
335
+ // ALWAYS report, success or not. Without this the flag stays set, the
336
+ // roster re-serves the job every poll, and each pass reverts the
337
+ // revert — the change flapping in and out of the owner's tree forever.
338
+ await reportMergeOutcome(PATCH_REVERT_DONE_URL, {
339
+ intentId: job.id,
340
+ ok: res.ok,
341
+ error: res.ok ? undefined : String(res.error ?? 'revert failed'),
342
+ });
343
+ } finally {
344
+ reverting.delete(job.id);
345
+ }
346
+ })();
347
+ }
348
+ };
349
+
350
+ // Plan checks: the ground-truth pass. Generation drafted these against a
351
+ // module manifest and wiki summaries — proxies for the repo. This runs where
352
+ // the checkout is, opens the real files, and reports corrections back into the
353
+ // thread. Read-only by construction; it never edits.
354
+ /**
355
+ * Pull the plan-check JSON off the tail of a Claude turn.
356
+ *
357
+ * The model is told to end with a bare JSON object, but a turn can trail
358
+ * prose, a fence, or a stray newline. Scan backwards for the last balanced
359
+ * object and validate it hard: anything shaped wrong is dropped rather than
360
+ * written into someone's plan. Returns null when nothing usable was found.
361
+ */
362
+ const parsePlanChecks = (out, intents) => {
363
+ const text = String(out ?? '');
364
+ const known = new Set(intents.map((i) => i.id));
365
+ const end = text.lastIndexOf('}');
366
+ if (end === -1) return null;
367
+ // NOTE: `lastIndexOf(x, -1)` returns 0, NOT -1 — the position argument is
368
+ // clamped, so the obvious `start = lastIndexOf('{', start - 1)` loop spins
369
+ // forever once it reaches index 0 and the parse fails. That hangs the
370
+ // daemon's event loop, not just this job. Walk with an explicit stop, and
371
+ // cap the attempts so a pathological turn can't burn the poll cycle either.
372
+ let start = text.lastIndexOf('{', end);
373
+ for (let attempts = 0; start !== -1 && attempts < 200; attempts++) {
374
+ let parsed = null;
375
+ try {
376
+ parsed = JSON.parse(text.slice(start, end + 1));
377
+ } catch {
378
+ /* not a complete object at this offset — step back and retry */
379
+ }
380
+ if (!parsed || !Array.isArray(parsed.checks)) {
381
+ if (start === 0) break;
382
+ start = text.lastIndexOf('{', start - 1);
383
+ continue;
384
+ }
385
+ return parsed.checks
386
+ .filter((ch) => ch && typeof ch.id === 'string' && known.has(ch.id))
387
+ .map((ch) => ({
388
+ id: ch.id,
389
+ alreadyBuilt: ch.alreadyBuilt === true,
390
+ evidence: typeof ch.evidence === 'string' ? ch.evidence.slice(0, 300) : '',
391
+ anchors: Array.isArray(ch.anchors)
392
+ ? ch.anchors.filter((a) => typeof a === 'string' && a.length < 200).slice(0, 6)
393
+ : [],
394
+ points:
395
+ typeof ch.points === 'number' && Number.isFinite(ch.points)
396
+ ? Math.max(0, Math.min(13, Math.round(ch.points)))
397
+ : null,
398
+ note: typeof ch.note === 'string' ? ch.note.slice(0, 400) : '',
399
+ }))
400
+ .slice(0, 30);
401
+ }
402
+ return null;
403
+ };
404
+
405
+ const PLAN_CHECK_DONE_URL = FLEET_URL.replace(/\/agents\/?$/, '/plan-check-done');
406
+ const checkingPlans = new Set();
407
+ const processPlanCheckJobs = (jobs) => {
408
+ for (const job of jobs ?? []) {
409
+ if (!job || typeof job.id !== 'string' || !Array.isArray(job.intents)) continue;
410
+ if (checkingPlans.has(job.id)) continue;
411
+ if (job.intents.length === 0) continue;
412
+ checkingPlans.add(job.id);
413
+ (async () => {
414
+ try {
415
+ note(`${c.cyan('plan')} ${c.dim(`— checking "${job.title}" against your code…`)}`);
416
+ // Reuse the wiki worktree: a clean detached checkout at base, which is
417
+ // what "the real code" should mean here — not whatever half-finished
418
+ // state an agent worktree happens to be in.
419
+ if (!existsSync(wikiWt)) {
420
+ try {
421
+ git(['worktree', 'add', '--detach', wikiWt, baseRef], repoRoot);
422
+ } catch {
423
+ git(['worktree', 'prune'], repoRoot);
424
+ git(['worktree', 'add', '--detach', wikiWt, baseRef], repoRoot);
425
+ }
426
+ }
427
+ const out = await runTurn({
428
+ prompt: PLAN_CHECK_KICKOFF({ title: job.title, intents: job.intents }),
429
+ resume: false,
430
+ system: SYSTEM_PLAN_CHECK,
431
+ cwd: wikiWt,
432
+ wikiPerm: true, // read-only file perms — no MCP, no shell writes
433
+ label: c.cyan('[plan]'),
434
+ });
435
+ const checks = parsePlanChecks(out, job.intents);
436
+ if (checks === null) {
437
+ warn(`plan check for "${job.title}": no usable JSON — leaving the plan as drafted`);
438
+ }
439
+ await reportMergeOutcome(PLAN_CHECK_DONE_URL, {
440
+ intentId: job.id,
441
+ checks: checks ?? [],
442
+ });
443
+ if (checks?.length) {
444
+ ok(`${c.cyan('plan')} ${c.dim(`— ${checks.length} correction${checks.length === 1 ? '' : 's'} for "${job.title}"`)}`);
445
+ } else {
446
+ ok(`${c.cyan('plan')} ${c.dim(`— "${job.title}" checks out against your code`)}`);
447
+ }
448
+ } catch (e) {
449
+ warn(`plan check failed for "${job.title}": ${e?.message ?? e}`);
450
+ // Clear the flag anyway — a stuck job would re-run every poll forever.
451
+ await reportMergeOutcome(PLAN_CHECK_DONE_URL, { intentId: job.id, checks: [] });
452
+ } finally {
453
+ checkingPlans.delete(job.id);
454
+ }
455
+ })();
456
+ }
457
+ };
458
+
304
459
  const processMergeJobs = (jobs) => {
305
460
  for (const job of jobs ?? []) {
306
461
  if (!job || typeof job.id !== 'string') continue; // a null element would wedge the loop
@@ -323,6 +478,35 @@ export async function runFleetDaemon() {
323
478
  warn(`merge REFUSED for "${job.title}": untrusted PR URL ${String(job.prUrl)}`);
324
479
  return;
325
480
  }
481
+ // STACKED PR: it targets its blocker's branch so the review shows only
482
+ // its own diff. The server holds this job until that blocker merged, so
483
+ // by now the blocker's commits are in the base ref — re-point before
484
+ // squashing, or the change lands in the blocker's branch and never
485
+ // reaches the trunk while the card cheerfully says "Merged".
486
+ if (job.retargetToBase) {
487
+ try {
488
+ // baseBranchName, not baseRef: `gh pr edit --base` needs a branch
489
+ // that exists in the repo, and detectBaseRef hands back a
490
+ // remote-tracking ref (origin/main) that GitHub 422s on.
491
+ execFileSync('gh', ['pr', 'edit', job.prUrl, '--base', baseBranchName(baseRef)], {
492
+ cwd: repoRoot,
493
+ stdio: ['ignore', 'pipe', 'pipe'],
494
+ });
495
+ } catch (e) {
496
+ // Already targeting base is the common no-op; anything else is
497
+ // reported rather than merged into the wrong place.
498
+ const err = e.stderr?.toString?.() || e.message || '';
499
+ if (!/no changes|already/i.test(err)) {
500
+ mergeAttempts.delete(job.id);
501
+ await reportMergeOutcome(MERGE_FAILED_URL, {
502
+ intentId: job.id,
503
+ message: `could not retarget the stacked PR onto ${baseBranchName(baseRef)} — merging it now would land in the branch below it, not ${baseBranchName(baseRef)}`,
504
+ });
505
+ warn(`merge held for "${job.title}": retarget failed — ${err.split('\n')[0]}`);
506
+ return;
507
+ }
508
+ }
509
+ }
326
510
  try {
327
511
  execFileSync('gh', ['pr', 'merge', job.prUrl, '--squash', '--delete-branch'], {
328
512
  cwd: repoRoot,
@@ -359,7 +543,7 @@ export async function runFleetDaemon() {
359
543
  // Direct enqueue = immediacy; the server's durable regroundJobs list
360
544
  // (created by merge-done above, cleared by our reground-done report)
361
545
  // is the restart-safe backstop — dedup'd here by groundedIntents.
362
- enqueueReground(job.id, job.prUrl, job.title);
546
+ enqueueReground(job.id, job.prUrl, job.title, job.dirtiesPages);
363
547
  } else if (failedReason) {
364
548
  // Report into the thread (server narrates + re-arms the merge
365
549
  // button + notifies) — the job disappears from the roster.
@@ -503,10 +687,20 @@ export async function runFleetDaemon() {
503
687
  wikiQueue.push({ type: 'sweep' });
504
688
  void drainWiki();
505
689
  };
506
- const enqueueReground = (intentId, prUrl, title) => {
690
+ const enqueueReground = (intentId, prUrl, title, dirtiesPages) => {
507
691
  if (!intentId || groundedIntents.has(intentId)) return;
508
692
  groundedIntents.add(intentId);
509
- wikiQueue.push({ type: 'reground', intentId, prUrl, title: title || 'a delivered task' });
693
+ wikiQueue.push({
694
+ type: 'reground',
695
+ intentId,
696
+ prUrl,
697
+ title: title || 'a delivered task',
698
+ // What the PLAN thought this would invalidate. A hint, not the truth —
699
+ // the turn still reads the real changed files; this catches pages whose
700
+ // frontmatter file list has drifted, or that document a concept rather
701
+ // than a directory.
702
+ dirtiesPages: Array.isArray(dirtiesPages) ? dirtiesPages : [],
703
+ });
510
704
  void drainWiki();
511
705
  };
512
706
 
@@ -674,7 +868,13 @@ export async function runFleetDaemon() {
674
868
  } else {
675
869
  note(`${c.cyan('wiki')} ${c.dim(`— re-grounding after "${task.title}"…`)}`);
676
870
  const out = await runTurn({
677
- prompt: REGROUND_KICKOFF({ sha, title: task.title, files, vaultDir }),
871
+ prompt: REGROUND_KICKOFF({
872
+ sha,
873
+ title: task.title,
874
+ files,
875
+ vaultDir,
876
+ predictedPages: task.dirtiesPages ?? [],
877
+ }),
678
878
  resume: false,
679
879
  system: SYSTEM_REGROUND(vaultDir),
680
880
  cwd: wikiWt,
@@ -820,6 +1020,8 @@ export async function runFleetDaemon() {
820
1020
  if (updating) return;
821
1021
  }
822
1022
  processMergeJobs(roster.mergeJobs);
1023
+ processPatchRevertJobs(roster.patchRevertJobs);
1024
+ processPlanCheckJobs(roster.planCheckJobs);
823
1025
  processCleanupJobs(roster.cleanupJobs);
824
1026
  const rosterIds = new Set(roster.agents.map((a) => a.agentId));
825
1027
 
@@ -912,7 +1114,7 @@ export async function runFleetDaemon() {
912
1114
  enqueueSweep(roster.codeMapJob);
913
1115
  for (const j of roster.regroundJobs ?? []) {
914
1116
  if (!j || typeof j.intentId !== 'string') continue; // a null element would throw + wedge the loop
915
- enqueueReground(j.intentId, j.prUrl, j.title);
1117
+ enqueueReground(j.intentId, j.prUrl, j.title, j.dirtiesPages);
916
1118
  }
917
1119
  void drainWiki();
918
1120
 
package/bin/lib/git.mjs CHANGED
@@ -6,6 +6,26 @@ export function git(args, cwd) {
6
6
  return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
7
7
  }
8
8
 
9
+ /**
10
+ * Same call, UNTRIMMED — for `-z` (NUL-separated) output, where trimming would
11
+ * eat the final separator and the leading space of a status code.
12
+ *
13
+ * Anything that COMPARES two path lists has to use this. Git's default
14
+ * line-based output quotes and escapes any path that isn't plain ASCII, and it
15
+ * does so inconsistently between commands — so a comparison of `git status`
16
+ * paths against `git diff` paths silently stops matching the moment a filename
17
+ * has an accent in it. For the patch collision check, "silently stops matching"
18
+ * means "overwrites the edits it exists to protect".
19
+ */
20
+ export function gitRaw(args, cwd) {
21
+ return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
22
+ }
23
+
24
+ /** Split NUL-separated git output into entries. */
25
+ export function splitNul(out) {
26
+ return String(out).split('\0').filter(Boolean);
27
+ }
28
+
9
29
  export function repoRootOrDie() {
10
30
  try {
11
31
  return git(['rev-parse', '--show-toplevel'], process.cwd());
@@ -53,6 +73,14 @@ export function isValidBranch(branch, repoRoot, baseRef) {
53
73
  }
54
74
  }
55
75
 
76
+ /** A commit sha from the server, before it reaches `git revert` argv. Server
77
+ * values reaching git are validated here by convention (see isValidBranch,
78
+ * isValidPrUrl) — a revision RANGE ("HEAD~10..HEAD") or a leading-dash option
79
+ * must never pass, whatever the roster says. */
80
+ export function isValidSha(sha) {
81
+ return typeof sha === 'string' && /^[0-9a-f]{7,40}$/.test(sha);
82
+ }
83
+
56
84
  /** A roster agent id used as a filesystem path segment — strict allowlist so
57
85
  * it can't traverse (`..`, `/`) out of the worktrees dir. */
58
86
  export function isSafePathSegment(id) {
@@ -72,6 +100,19 @@ export function detectBaseRef(repoRoot) {
72
100
  }
73
101
  }
74
102
 
103
+ /**
104
+ * The BRANCH NAME behind a base ref.
105
+ *
106
+ * `detectBaseRef` returns a remote-tracking ref (`origin/main`) because that is
107
+ * what you check out and reset against. GitHub's API has never heard of it: a PR
108
+ * base must be a branch that exists in the repo, so `gh pr edit --base
109
+ * origin/main` 422s every time. Anything that talks to the provider needs this
110
+ * form, not the ref.
111
+ */
112
+ export function baseBranchName(baseRef) {
113
+ return String(baseRef || '').replace(/^origin\//, '') || 'main';
114
+ }
115
+
75
116
  export function resetWorktree(wt, baseRef) {
76
117
  try {
77
118
  git(['fetch', 'origin', '--quiet'], wt);