flowviant 0.125.26 → 0.125.28

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/lib/vault.mjs CHANGED
@@ -29,6 +29,7 @@ import { execFileSync } from 'node:child_process';
29
29
  import { join, relative, sep } from 'node:path';
30
30
  import { gitRaw } from './git.mjs';
31
31
  import { planVaultSync } from './vaultDiff.mjs';
32
+ import { realDirState } from './ownedDirs.mjs';
32
33
 
33
34
  const SYNC_STATE = '.flowviant-sync.json';
34
35
 
@@ -96,6 +97,7 @@ export function vaultConfigForeignKey(dir) {
96
97
  * of its own, which `git init` copies in (measured, git 2.55) — and which the
97
98
  * check above would then refuse on every sync. A vault needs none of it. */
98
99
  export function ensureVault(dir) {
100
+ if (realDirState(dir) === 'other') throw new Error('wiki vault must be a real directory');
99
101
  mkdirSync(dir, { recursive: true });
100
102
  if (!existsSync(join(dir, '.git'))) {
101
103
  try {
@@ -18,6 +18,7 @@
18
18
  */
19
19
 
20
20
  import { createHash } from 'node:crypto';
21
+ import { protectedWikiPage } from './wikiOwnership.mjs';
21
22
 
22
23
  // Mirror the server contract (shared schema) — a page that violates it is
23
24
  // skipped with a warning (and carried forward if previously synced), never
@@ -44,6 +45,18 @@ export const isSafePath = (p) =>
44
45
 
45
46
  const SKIPPED = Object.freeze({ pages: 0, uploaded: 0, deleted: 0, skipped: true });
46
47
 
48
+ /** Draft publication uses exactly the uplink's page/count limits. Keep the
49
+ * constants here so pre-publication validation cannot drift from sync. */
50
+ export function assertWikiDraftFits(changes, beforeCount, resultingCount) {
51
+ for (const [path, content] of changes) {
52
+ if (!isSafePath(path) || (content !== null && Buffer.byteLength(content) > MAX_FILE_BYTES)) {
53
+ throw new Error(`wiki draft page exceeds sync contract: ${path}`);
54
+ }
55
+ }
56
+ if (resultingCount === 0 && beforeCount > 0) throw new Error('wiki draft would empty the vault');
57
+ if (resultingCount > MAX_FILES && resultingCount > beforeCount) throw new Error('wiki draft exceeds page ceiling');
58
+ }
59
+
47
60
  /**
48
61
  * Plan one sync.
49
62
  *
@@ -97,6 +110,10 @@ export function planVaultSync({ found, walkErrors = 0, prev = {}, read, scrub =
97
110
  carry(p, 'unreadable');
98
111
  continue;
99
112
  }
113
+ if (protectedWikiPage(p, text)) {
114
+ carry(p, 'human/reference source, outside generated output');
115
+ continue;
116
+ }
100
117
  // Uplink scrub: the cartographer quotes real repo files, and a repo file
101
118
  // can contain a synced secret — redact known values before upload. The
102
119
  // hash is computed on the SCRUBBED text so the diff state stays coherent.
@@ -122,6 +139,11 @@ export function planVaultSync({ found, walkErrors = 0, prev = {}, read, scrub =
122
139
  if (!(p in current)) current[p] = prev[p];
123
140
  }
124
141
  }
142
+ // A generated-output sync has no authority to delete sources, including
143
+ // reserved legacy pages that are no longer present in this local snapshot.
144
+ for (const p of Object.keys(prev)) {
145
+ if (!(p in current) && protectedWikiPage(p)) current[p] = prev[p];
146
+ }
125
147
 
126
148
  // A readable vault that suddenly presents ZERO pages while the server holds
127
149
  // many is almost always a broken/moved dir, not an intentional wipe — refuse
@@ -0,0 +1,105 @@
1
+ /** A cartographer edits a disposable draft, never the persistent wiki or the
2
+ * Knowledge store. Publish only a complete turn; failures leave last-good bytes.
3
+ * Portable page metadata is an assertion by the CLI, not a sync-time attestation. */
4
+ import { lstatSync, readdirSync, readFileSync, writeFileSync, mkdtempSync, rmSync, renameSync } from 'node:fs';
5
+ import { randomUUID } from 'node:crypto';
6
+ import { join, dirname, basename } from 'node:path';
7
+ import { ensureRealSubdir } from './ownedDirs.mjs';
8
+ import { isSafePath, assertWikiDraftFits } from './vaultDiff.mjs';
9
+
10
+ import { wikiScalars as scalars, protectedWikiPage } from './wikiOwnership.mjs';
11
+
12
+ /** Never follow links into an imported vault. A partial read cannot be a draft
13
+ * basis: fail before the CLI starts rather than infer missing pages as deleted. */
14
+ function pages(dir, prefix = '', out = new Map(), rejectLinks = false) {
15
+ if (!lstatSync(dir).isDirectory()) throw new Error('wiki directory must be a real directory');
16
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
17
+ if (entry.name.startsWith('.')) continue;
18
+ const path = prefix + entry.name;
19
+ if (entry.isSymbolicLink()) {
20
+ if (rejectLinks) throw new Error(`wiki draft contains a symlink: ${path}`);
21
+ continue;
22
+ }
23
+ if (entry.isDirectory()) pages(join(dir, entry.name), `${path}/`, out, rejectLinks);
24
+ else if (entry.isFile() && entry.name.endsWith('.md')) out.set(path, readFileSync(join(dir, entry.name), 'utf8'));
25
+ }
26
+ return out;
27
+ }
28
+
29
+ function put(dir, path, text) {
30
+ if (!isSafePath(path)) throw new Error(`unsafe wiki page: ${path}`);
31
+ const parent = dirname(path);
32
+ if (parent !== '.' && !ensureRealSubdir(dir, parent)) throw new Error(`wiki parent is not a real directory: ${parent}`);
33
+ try {
34
+ if (!lstatSync(join(dir, path)).isFile()) throw new Error(`wiki destination is not a file: ${path}`);
35
+ } catch (e) {
36
+ if (e.code !== 'ENOENT') throw e;
37
+ }
38
+ const target = join(dir, path);
39
+ const temporary = join(dirname(target), `.${basename(target)}.${randomUUID()}`);
40
+ try {
41
+ writeFileSync(temporary, text, { flag: 'wx' });
42
+ renameSync(temporary, target);
43
+ } finally {
44
+ rmSync(temporary, { force: true });
45
+ }
46
+ }
47
+
48
+ export function beginWikiDraft(vaultDir) {
49
+ if (lstatSync(vaultDir).isSymbolicLink()) throw new Error('wiki vault must not be a symlink');
50
+ const before = pages(vaultDir);
51
+ const dir = mkdtempSync(join(dirname(vaultDir), '.wiki-draft-'));
52
+ try {
53
+ for (const [path, text] of before) put(dir, path, text);
54
+ } catch (e) {
55
+ rmSync(dir, { recursive: true, force: true });
56
+ throw e;
57
+ }
58
+ return {
59
+ dir,
60
+ discard: () => rmSync(dir, { recursive: true, force: true }),
61
+ publish({ sha, repoFullName }) {
62
+ const candidate = pages(dir, '', new Map(), true);
63
+ const changes = new Map();
64
+ for (const [path, text] of candidate) {
65
+ const old = before.get(path);
66
+ if (old === text || protectedWikiPage(path, old ?? text)) continue;
67
+ const meta = scalars(text);
68
+ // Changed prose carrying a previous commit must not masquerade as
69
+ // verified. Preserve other frontmatter bytes and unknown custom fields.
70
+ const verified = meta('wiki-verified-at');
71
+ let content = text;
72
+ if (verified && (verified.toLowerCase() !== sha?.toLowerCase() || !/^[a-f0-9]{40}$/i.test(verified) ||
73
+ meta('wiki-origin') !== 'generated' || meta('wiki-repo') !== (repoFullName ?? ''))) {
74
+ content = text.replace(/^(---\r?\n[\s\S]*?\r?\n)---/, (fm) => fm.replace(/^wiki-verified-at:.*\r?\n/gm, ''));
75
+ }
76
+ changes.set(path, content);
77
+ }
78
+ for (const [path, text] of before) {
79
+ if (!candidate.has(path) && !protectedWikiPage(path, text)) changes.set(path, null);
80
+ }
81
+ const resulting = new Set(before.keys());
82
+ for (const [p, text] of changes) text === null ? resulting.delete(p) : resulting.add(p);
83
+ assertWikiDraftFits(changes, before.size, resulting.size);
84
+ // Human edits made during the turn win. Validate the complete read set
85
+ // before any write, including deletions and untouched source pages.
86
+ const current = pages(vaultDir);
87
+ if (current.size !== before.size || [...before].some(([p, text]) => current.get(p) !== text)) throw new Error('wiki changed during generation; draft not published');
88
+ const applied = [];
89
+ try {
90
+ for (const [p, text] of changes) {
91
+ if (text === null) rmSync(join(vaultDir, p));
92
+ else put(vaultDir, p, text);
93
+ applied.push(p);
94
+ }
95
+ } catch (e) {
96
+ for (const p of applied.reverse()) {
97
+ if (before.has(p)) put(vaultDir, p, before.get(p));
98
+ else rmSync(join(vaultDir, p), { force: true });
99
+ }
100
+ throw e;
101
+ }
102
+ return changes.size;
103
+ },
104
+ };
105
+ }
@@ -0,0 +1,19 @@
1
+ /** Generated wiki ownership; never grants writes to imported context. */
2
+ export const wikiScalars = (text) => {
3
+ const fm = text.replace(/\r\n/g, '\n').match(/^---\n([\s\S]*?)\n---/);
4
+ return (key) => {
5
+ const lines = (fm?.[1] ?? '').split('\n').filter((line) => line.startsWith(`${key}:`));
6
+ return lines.length === 1 ? lines[0].slice(key.length + 1).trim().replace(/^["']|["']$/g, '') : '';
7
+ };
8
+ };
9
+
10
+ /** Reserved namespaces are never generated output, even for legacy pages.
11
+ * Legacy decisions are human-owned unless explicitly marked generated. */
12
+ export function protectedWikiPage(path, text = '') {
13
+ const p = path.toLowerCase();
14
+ const origin = wikiScalars(text)('wiki-origin');
15
+ return p.split('/').at(-1) === 'instructions.md' ||
16
+ /^(imports|references|sources)\//.test(p) ||
17
+ (p.startsWith('decisions/') && origin !== 'generated') ||
18
+ (origin !== '' && origin !== 'generated');
19
+ }
@@ -30,6 +30,7 @@ import { sawSentinel } from './claude.mjs';
30
30
  import { runTurn as defaultRunTurn } from './runTurn.mjs';
31
31
  import { SYSTEM_WIKI, WIKI_KICKOFF, SYSTEM_REGROUND, REGROUND_KICKOFF } from './prompts.mjs';
32
32
  import { ensureVault, syncVault } from './vault.mjs';
33
+ import { beginWikiDraft } from './wikiDraft.mjs';
33
34
  import { scrub as envScrub } from './uplinkScrub.mjs';
34
35
  import { runtimeLabel } from './runtimes.mjs';
35
36
  import { pickRuntimeFor as defaultPickRuntimeFor } from './runtimeDetection.mjs';
@@ -238,7 +239,8 @@ export function createWikiRunner({
238
239
  // always taken (audit 2026-10-10, F749).
239
240
  if (!SHA1_ABBREV_RE.test(String(sha).toLowerCase())) continue;
240
241
  try {
241
- const out = gitRaw(['show', '--name-only', '--pretty=format:', String(sha)], repoRoot);
242
+ // Report both sides of a rename so old files: citations are affected.
243
+ const out = gitRaw(['show', '--no-renames', '--name-only', '--pretty=format:', String(sha)], repoRoot);
242
244
  for (const line of out.split('\n')) {
243
245
  const f = line.trim();
244
246
  if (f) files.add(f);
@@ -374,6 +376,7 @@ export function createWikiRunner({
374
376
  * readout. Null (and absent from the frame) when no CLI ran.
375
377
  */
376
378
  let usage = null;
379
+ let draft = null;
377
380
  const onUsage = (rt) => (u) => {
378
381
  usage = addUsage(usage, { ...u, runtime: rt });
379
382
  };
@@ -394,20 +397,23 @@ export function createWikiRunner({
394
397
  resetWorktree(wikiWt, getBaseRef());
395
398
  // No HEAD → '' — still writes the map, just ungrounded.
396
399
  const sha = gitOrNull(['rev-parse', 'HEAD'], wikiWt) ?? '';
397
- // Sync the vault after the turn regardless of the sentinel: a died
398
- // sweep's partial pages still persist (merge, no prune) — only a
399
- // COMPLETED sweep finalizes, so an interrupted one can't erase pages.
400
+ const repoFullName = originSlug(repoRoot) || undefined;
401
+ const persistentVaultDir = vaultDir;
402
+ draft = beginWikiDraft(persistentVaultDir);
403
+ vaultDir = draft.dir;
404
+ // Only a complete draft can replace last-good pages or prune them.
405
+ // The CLI's write fence names the draft, never Knowledge or sources.
400
406
  const runSync = async (finalize) => {
401
407
  try {
402
408
  const r = await syncVault({
403
- dir: vaultDir,
409
+ dir: persistentVaultDir,
404
410
  url: WIKI_VAULT_URL,
405
411
  token: FLEET_TOKEN,
406
412
  userAgent: USER_AGENT,
407
413
  finalize,
408
414
  groundedAtSha: sha || undefined,
409
415
  // Powers the GitHub blob links behind every cited file path.
410
- repoFullName: originSlug(repoRoot) || undefined,
416
+ repoFullName,
411
417
  warn,
412
418
  // Redact synced secrets a page may have quoted from the repo.
413
419
  scrub: envScrub,
@@ -435,7 +441,7 @@ export function createWikiRunner({
435
441
  sweepAttempts++;
436
442
  note(`${c.cyan('wiki')} ${c.dim(`— regenerating: your ${wikiLabel} is reading the repo…`)}`);
437
443
  const out = await runTurn({
438
- prompt: WIKI_KICKOFF(sha, vaultDir),
444
+ prompt: WIKI_KICKOFF(sha, vaultDir, repoFullName),
439
445
  resume: false,
440
446
  system: SYSTEM_WIKI(vaultDir),
441
447
  cwd: wikiWt,
@@ -454,12 +460,13 @@ export function createWikiRunner({
454
460
  });
455
461
  const complete = sawSentinel(out, 'WIKI_DONE');
456
462
  if (complete) {
463
+ draft.publish({ sha, repoFullName });
457
464
  sweepCompleted = true;
458
465
  ok(`${c.cyan('wiki')} ${c.dim('— vault regenerated from your code.')}`);
459
466
  } else {
460
- warn('wiki sweep ended without WIKI_DONE — partial pages synced');
467
+ warn('wiki sweep ended without WIKI_DONE — last good pages retained');
461
468
  }
462
- await runSync(complete);
469
+ if (complete) await runSync(true);
463
470
  } else {
464
471
  const files = changedFilesForShas(task.shas);
465
472
  if (files === null) {
@@ -484,6 +491,7 @@ export function createWikiRunner({
484
491
  title: task.title,
485
492
  files,
486
493
  vaultDir,
494
+ repoFullName,
487
495
  predictedPages: task.dirtiesPages ?? [],
488
496
  }),
489
497
  resume: false,
@@ -499,10 +507,11 @@ export function createWikiRunner({
499
507
  wikiChild = ch;
500
508
  },
501
509
  });
502
- if (sawSentinel(out, 'REGROUND_DONE'))
510
+ if (sawSentinel(out, 'REGROUND_DONE')) {
511
+ draft.publish({ sha, repoFullName });
503
512
  ok(`${c.cyan('wiki')} ${c.dim(`— vault updated for "${task.title}".`)}`);
504
- else warn(`wiki re-ground for "${task.title}" ended without REGROUND_DONE.`);
505
- await runSync(false);
513
+ await runSync(false);
514
+ } else warn(`wiki re-ground for "${task.title}" ended without REGROUND_DONE — last good pages retained.`);
506
515
  }
507
516
  // Consume the durable job: attempted = done (success or not — the
508
517
  // sync is idempotent and a failed turn heals on the next full
@@ -521,6 +530,7 @@ export function createWikiRunner({
521
530
  } catch (e) {
522
531
  warn(`wiki ${task.type} failed: ${e.message}`);
523
532
  } finally {
533
+ draft?.discard();
524
534
  wikiChild = null;
525
535
  if (heartbeat) clearInterval(heartbeat);
526
536
  /**
@@ -27,13 +27,15 @@ import { postureToolsNote } from './postureTools.mjs';
27
27
  import { machineMcpServers } from './claudeMachineMcp.mjs';
28
28
  import { ORCHESTRATOR_SERVER } from './orchestratorProtocol.mjs';
29
29
  import { VIDEO_SERVER } from './videoRender.mjs';
30
+ import { BROWSER_SERVER } from './managedBrowser.mjs';
30
31
 
31
32
  /** The servers the daemon itself mounts on a card turn, by the names the
32
33
  * agent calls them: a multi-repository card's add_repository, an
33
34
  * orchestrated card's routing, a build's UI review and a video card's
34
- * render_video (2026-10-26). Never a project server's, whatever the base
35
+ * render_video (2026-10-26), and a code turn's managed browser (2026-10-30).
36
+ * Never a project server's, whatever the base
35
37
  * `.mcp.json` names. */
36
- export const CARD_TURN_SERVERS = Object.freeze({ repositories: 'card_repositories', orchestrator: ORCHESTRATOR_SERVER, uiReview: 'card_ui_review', video: VIDEO_SERVER });
38
+ export const CARD_TURN_SERVERS = Object.freeze({ repositories: 'card_repositories', orchestrator: ORCHESTRATOR_SERVER, uiReview: 'card_ui_review', video: VIDEO_SERVER, browser: BROWSER_SERVER });
37
39
 
38
40
  /**
39
41
  * The card turn's tools, prepared, and what it is told of them.
@@ -46,7 +48,7 @@ export const CARD_TURN_SERVERS = Object.freeze({ repositories: 'card_repositorie
46
48
  * from here), the note, the mount's part of the CLI's `mcpEnv` and whether it
47
49
  * needs one, and the keys the runner takes the mount as.
48
50
  */
49
- export function prepareCardTools({ rt, posture, wt, repoRoot, baseRef, sources = [], repositoryTool = null, orchestratorConfig = null, uiReviewConfig = null, videoConfig = null, orchestrated = false, codexHome = null, env = process.env, machineServers = machineMcpServers }) {
51
+ export function prepareCardTools({ rt, posture, wt, repoRoot, baseRef, sources = [], repositoryTool = null, orchestratorConfig = null, uiReviewConfig = null, videoConfig = null, browserConfig = null, orchestrated = false, codexHome = null, env = process.env, machineServers = machineMcpServers }) {
50
52
  // A turn reads the base ref afresh. Changes the agent has made to its
51
53
  // own worktree cannot silently change the next turn's tools.
52
54
  const source = sources.find((r) => r.wt === wt);
@@ -59,6 +61,7 @@ export function prepareCardTools({ rt, posture, wt, repoRoot, baseRef, sources =
59
61
  ...(repositoryTool ? { [CARD_TURN_SERVERS.repositories]: repositoryTool.config } : {}),
60
62
  ...(orchestratorConfig ? { [CARD_TURN_SERVERS.orchestrator]: orchestratorConfig } : {}),
61
63
  ...(posture === 'build' && uiReviewConfig ? { [CARD_TURN_SERVERS.uiReview]: uiReviewConfig } : {}),
64
+ ...(posture === 'build' && browserConfig ? { [CARD_TURN_SERVERS.browser]: browserConfig } : {}),
62
65
  // A video card's render tool rides its fenced posture (videoRender.mjs).
63
66
  ...(videoConfig ? { [CARD_TURN_SERVERS.video]: videoConfig } : {}),
64
67
  } });
@@ -70,6 +70,7 @@ import { measuredRuntimeVersion } from './runtimeDetection.mjs';
70
70
  import { createIntermediateArtifacts, IntermediateArtifactCapacityError } from './intermediateArtifacts.mjs';
71
71
  import { createUiReview } from './uiReview.mjs';
72
72
  import { createVideoRender } from './videoRender.mjs';
73
+ import { createManagedBrowser } from './managedBrowser.mjs';
73
74
  import { withUiReview, appendUiReviewEvidence } from './uiReviewTurn.mjs';
74
75
 
75
76
  export function createAgentTurnExecution({
@@ -102,6 +103,7 @@ export function createAgentTurnExecution({
102
103
  exportModel,
103
104
  makeUiReview = createUiReview,
104
105
  makeVideoRender = createVideoRender,
106
+ makeManagedBrowser = createManagedBrowser,
105
107
  }) {
106
108
  const reportDelivery = createDeliveryReporter();
107
109
  /** How long the final flush may hold the settle. Bounded because the settle
@@ -410,6 +412,8 @@ export function createAgentTurnExecution({
410
412
  /** The CLI, unless a person already asked to stop this turn (Interrupt
411
413
  * now): then nothing starts — no fresh retry, no continuation. */
412
414
  let uiReview = null;
415
+ let managedBrowser = null;
416
+ let browserNote = '';
413
417
  let uiReviewNote = '';
414
418
  let uiReviewEvidence = '';
415
419
  // A video card's render tool (videoRender.mjs), and the words a turn
@@ -424,6 +428,8 @@ export function createAgentTurnExecution({
424
428
  args.verifiedWorktree = true;
425
429
  args = withUiReview(args, uiReviewNote, uiReview?.env);
426
430
  args = withUiReview(args, videoNote);
431
+ args = withUiReview(args, browserNote, managedBrowser?.env);
432
+ args.managedBrowser = Boolean(managedBrowser);
427
433
  return runTurnImpl(args);
428
434
  };
429
435
  /**
@@ -473,6 +479,15 @@ export function createAgentTurnExecution({
473
479
  let orchestrator = null;
474
480
  let intermediateDelivery = null;
475
481
  try {
482
+ if (posture === 'build' && job.kind !== 'merge_resolve' && ['claude', 'codex'].includes(rt)) {
483
+ try {
484
+ managedBrowser = await makeManagedBrowser({ wt, turnId, signal: setupController.signal, onChild: ch => {
485
+ workChildren.set(ch, agentId); groupKillChildren?.add(ch);
486
+ return () => { workChildren.delete(ch); groupKillChildren?.delete(ch); };
487
+ } });
488
+ browserNote = managedBrowser.instructions;
489
+ } catch (error) { browserNote = `The managed browser could not start: ${envScrub(error.message)}. Report interactive browser checks unavailable.`; }
490
+ }
476
491
  if (posture === 'build' && job.kind !== 'merge_resolve') {
477
492
  try {
478
493
  uiReview = await makeUiReview({ wt, signal: setupController.signal, onChild: ch => {
@@ -499,7 +514,7 @@ export function createAgentTurnExecution({
499
514
  notify: message => liveInput ? run.live?.inject(message) === true : false,
500
515
  taken: id => run.live?.onTaken(id) });
501
516
  }
502
- const tools = prepareCardTools({ rt, posture, wt, repoRoot, baseRef, sources: repositoryRun?.sources ?? [], repositoryTool: repositoryRun?.tool ?? null, orchestratorConfig: orchestrator?.config ?? null, uiReviewConfig: uiReview?.config, videoConfig: videoRender?.config ?? null, orchestrated: Boolean(orchestrator), codexHome: agentResume.codexHome });
517
+ const tools = prepareCardTools({ rt, posture, wt, repoRoot, baseRef, sources: repositoryRun?.sources ?? [], repositoryTool: repositoryRun?.tool ?? null, orchestratorConfig: orchestrator?.config ?? null, uiReviewConfig: uiReview?.config, videoConfig: videoRender?.config ?? null, browserConfig: managedBrowser?.config, orchestrated: Boolean(orchestrator), codexHome: agentResume.codexHome });
503
518
  projectTools = tools.projectTools;
504
519
  localCleanup?.begin(turnId);
505
520
  const { toolsNote } = tools;
@@ -759,6 +774,7 @@ export function createAgentTurnExecution({
759
774
  // owned by its review tool, then bind evidence to the final source
760
775
  // before the existing artifact upload and delivery settlement.
761
776
  try { await videoRender?.close(); } catch { /* a closed listener */ }
777
+ try { await managedBrowser?.close(); } catch { /* turn teardown continues */ }
762
778
  try { await uiReview?.close(); }
763
779
  finally {
764
780
  try { uiReviewEvidence = uiReview?.finalize() ?? uiReviewEvidence; }
@@ -55,6 +55,11 @@ export function createAgentTurnReports({ REJECT_RETRY_MS, baseDir = null }) {
55
55
  const persistRecovery = () => journal?.save(new Map(agentReported), new Map()); // turnId -> { body, at }
56
56
  const agentRejectedUntil = new Map(); // turnId -> earliest re-POST of a refused body
57
57
  const AGENT_REPORT_GRACE_MS = 30 * 60_000;
58
+ // A roster read can race the settle's acknowledgement. Forgetting the
59
+ // completed id with its outbox body let that stale offer run a second CLI
60
+ // under an already answered turn, hiding its output from the real retry.
61
+ // These ids are not pending reports and must not keep the machine busy.
62
+ const settledAt = new Map();
58
63
 
59
64
  /** Returns the server's reply, because it carries ONE instruction the machine
60
65
  * can act on immediately: `review: true` means the agent's queue just
@@ -81,6 +86,7 @@ export function createAgentTurnReports({ REJECT_RETRY_MS, baseDir = null }) {
81
86
  * re-POST backs off instead of hammering a body the server just refused.
82
87
  */
83
88
  if (res.ok && (body.mergeResolved === undefined || typeof j?.data?.settled === 'boolean')) {
89
+ settledAt.set(turnId, Date.now());
84
90
  agentReported.delete(turnId);
85
91
  agentRejectedUntil.delete(turnId);
86
92
  persistRecovery();
@@ -165,9 +171,12 @@ export function createAgentTurnReports({ REJECT_RETRY_MS, baseDir = null }) {
165
171
  * the grace only covers its POST racing a final offer.
166
172
  */
167
173
  const pruneHeldReports = (list) => {
168
- if (!agentReported.size) return;
169
174
  const offered = new Set(list.map((j) => String(j?.id || '')));
170
175
  const now = Date.now();
176
+ for (const [id, at] of settledAt) {
177
+ if (offered.has(id)) settledAt.set(id, now);
178
+ else if (now - at > AGENT_REPORT_GRACE_MS) settledAt.delete(id);
179
+ }
171
180
  for (const [id, held] of agentReported) {
172
181
  if (offered.has(id)) held.at = now;
173
182
  else if (now - held.at > AGENT_REPORT_GRACE_MS) {
@@ -187,5 +196,6 @@ export function createAgentTurnReports({ REJECT_RETRY_MS, baseDir = null }) {
187
196
  pruneHeldReports,
188
197
  agentReported,
189
198
  agentRejectedUntil,
199
+ hasSettledTurn: id => settledAt.has(id),
190
200
  };
191
201
  }
@@ -73,6 +73,7 @@ export function createWorkAgentTurns({
73
73
  pruneHeldReports,
74
74
  agentReported,
75
75
  agentRejectedUntil,
76
+ hasSettledTurn,
76
77
  } = createAgentTurnReports({ REJECT_RETRY_MS, baseDir });
77
78
 
78
79
  // ── AGENT TURNS: one task per prompt ───────────────────────────────────────
@@ -300,6 +301,7 @@ export function createWorkAgentTurns({
300
301
  for (const job of list.slice(0, 4)) {
301
302
  const id = String(job?.id || '');
302
303
  if (!id) continue;
304
+ if (hasSettledTurn(id)) continue;
303
305
  if (agentTurns.has(id)) {
304
306
  const reason = agentRuns.get(id)?.waitingReason;
305
307
  if (reason) reportDelivery('agent', job, 'queued', reason);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "flowviant",
3
- "version": "0.125.26",
3
+ "version": "0.125.28",
4
4
  "description": "Run your own coding CLIs as build agents for Flowviant \u2014 Claude Code, Codex or Antigravity, on your own credentials. Holds your sessions, keeps a worktree per tab, and ships branches on your word.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -18,7 +18,7 @@
18
18
  },
19
19
  "scripts": {
20
20
  "test": "node --test bin/lib/*.test.mjs",
21
- "prepublishOnly": "bun scripts/check-app-parity.mjs"
21
+ "prepublishOnly": "node scripts/check-publisher.mjs && bun scripts/check-app-parity.mjs"
22
22
  },
23
23
  "dependencies": {
24
24
  "libsodium-wrappers-sumo": "^0.8.4",