paseo-follow-up 2.0.2-beta.2 → 2.1.0-beta.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/server/inbox.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  import { prLink } from "../shared/presentation";
2
2
  import { DEVELOPER, ledgerBy, onBehalfLine, type Actor } from "../shared/actor";
3
- import { mkdir, open, readFile, rename, unlink, type FileHandle } from "node:fs/promises";
3
+ import { readFile } from "node:fs/promises";
4
4
  import { join } from "node:path";
5
5
  import { randomUUID } from "node:crypto";
6
+ import { WriteBehind } from "./write-behind";
6
7
  import { realTimers, stableMessageId, withDeadline, type Timers } from "./delivery";
7
8
  import { BackgroundAgents } from "./background-agents";
8
9
  import { deepFreeze } from "./store";
@@ -50,10 +51,19 @@ export class InboxStore {
50
51
  private saved: InboxState | null = null;
51
52
  /** Writes to inbox.json, for tests. */
52
53
  writes = 0;
53
- /** The pending window's write (the-inbox-writes-at-most-once-per-window). */
54
- private timer: ReturnType<typeof setTimeout> | null = null;
54
+ /**
55
+ * inbox.json's writer (the-inbox-writes-at-most-once-per-window): one write per window of the newest state, outside
56
+ * the mutation queue (an-ack-never-waits-on-the-disk, server/write-behind.ts), so a read or a mutation never waits
57
+ * on a write's fsync. 2026-11-13 (CI): follow.inbox-list waited 664 ms for one, queued behind it.
58
+ */
59
+ readonly persist: WriteBehind<InboxState>;
55
60
  /** `writeMs` 0 writes each real change through at once (tools, tests); the worker passes INBOX_WRITE_MS. */
56
- constructor(readonly directory: string, private now: () => number = Date.now, private writeMs = 0) {}
61
+ constructor(readonly directory: string, private now: () => number = Date.now, private writeMs = 0) {
62
+ this.persist = new WriteBehind({
63
+ path: this.path, delayMs: writeMs, encode: inboxJsonParts,
64
+ onWritten: state => { this.written = { at: this.now() }; this.saved = state; if (this.unsaved === state) this.unsaved = null; this.writes++; },
65
+ });
66
+ }
57
67
  private get path() { return join(this.directory, "inbox.json"); }
58
68
  /** A private, mutable copy of the whole inbox. Nothing in the worker needs one; mutate() hands out a draft instead. */
59
69
  async read(): Promise<InboxState> { return structuredClone(await this.load()); }
@@ -110,19 +120,9 @@ export class InboxStore {
110
120
  }
111
121
  /** Writes a held change or lastSeen now; the worker's stop calls it. */
112
122
  async flush(): Promise<void> {
113
- if (this.timer) { clearTimeout(this.timer); this.timer = null; }
114
123
  await this.tail;
115
- const pending = this.unsaved;
116
- if (pending) await this.write(pending);
117
- }
118
- /** One write for everything the window changed, queued behind the mutations in flight. */
119
- private schedule(): void {
120
- this.timer ??= setTimeout(() => {
121
- this.timer = null;
122
- const next = this.tail.then(async () => { const pending = this.unsaved; if (pending) await this.write(pending); });
123
- this.tail = next.catch(() => this.schedule()); // a failed write keeps the change and tries again next window
124
- }, this.writeMs);
125
- (this.timer as { unref?: () => void }).unref?.();
124
+ if (this.unsaved) this.persist.set(this.unsaved);
125
+ await this.persist.flush();
126
126
  }
127
127
  /**
128
128
  * Validates what changed (each changed entry, each changed top-level field, and of briefOrigins only the items it
@@ -140,19 +140,10 @@ export class InboxStore {
140
140
  for (const f of top) deepFreeze((next as Record<string, unknown>)[f]);
141
141
  Object.freeze(entries); Object.freeze(next);
142
142
  const lastSeenOnly = top.length === 1 && top[0] === "lastSeen" && !changes.fields.has("entries");
143
- if (lastSeenOnly && this.written && this.now() - this.written.at < LAST_SEEN_WRITE_MS) { this.unsaved = next; return; }
144
- if (this.writeMs > 0) { this.unsaved = next; this.schedule(); return; }
145
- await this.write(next);
146
- }
147
- private async write(state: InboxState): Promise<void> {
148
- await mkdir(this.directory, { recursive: true, mode: 0o700 });
149
- const temporary = join(this.directory, `inbox.${randomUUID()}.tmp`);
150
- try {
151
- const file = await open(temporary, "wx", 0o600);
152
- try { await writeParts(file, inboxJsonParts(state)); await file.sync(); } finally { await file.close(); }
153
- await rename(temporary, this.path);
154
- this.written = { at: this.now() }; this.unsaved = null; this.saved = deepFreeze(state); this.writes++;
155
- } finally { await unlink(temporary).catch(() => undefined); }
143
+ // A lastSeen-only change rides a write that is already waiting, else waits for LAST_SEEN_WRITE_MS.
144
+ if (lastSeenOnly && !this.persist.queued && this.written && this.now() - this.written.at < LAST_SEEN_WRITE_MS) { this.unsaved = next; return; }
145
+ this.unsaved = next; this.persist.set(next);
146
+ if (this.writeMs <= 0) await this.persist.flush();
156
147
  }
157
148
  }
158
149
  /**
@@ -205,18 +196,6 @@ export function inboxJsonParts(state: InboxState): Buffer[] {
205
196
  if (keyBytes.size > 4 * (Object.keys(state.entries).length + 32)) keyBytes.clear();
206
197
  return out;
207
198
  }
208
- /** Writes every part, however the OS splits a vectored write. */
209
- async function writeParts(file: FileHandle, parts: Buffer[]): Promise<void> {
210
- let rest = parts;
211
- while (rest.length) {
212
- const { bytesWritten } = await file.writev(rest.length > 512 ? rest.slice(0, 512) : rest);
213
- let n = bytesWritten, i = 0;
214
- while (i < rest.length && n >= rest[i]!.length) n -= rest[i++]!.length;
215
- rest = rest.slice(i);
216
- if (n > 0) rest = [rest[0]!.subarray(n), ...rest.slice(1)];
217
- if (bytesWritten === 0 && rest.length) throw new Error("inbox.json: the write made no progress");
218
- }
219
- }
220
199
  /**
221
200
  * a-mutation-costs-what-it-changes: entries draft per entry; briefOrigins, read whole and replaced whole, drafts as the
222
201
  * saved frozen array (2026-11-14: each turn end structuredCloned, shadow-walked and re-validated all 500 origins,
@@ -57,7 +57,7 @@ export const mcpSource: string = [
57
57
  " [\"track\", \"Follow a workspace again after the developer opted it out in Settings. Follow-up follows every workspace by default. Only when the developer asked.\", \"follow.agent-act\", { workspace: string }, [\"workspace\"]],",
58
58
  " [\"workspace_about\", \"Read a workspace's Summary: one sentence on what the workspace is for (a reminder, not a status), plus the Linear issues, PRs, Slack threads and docs found in its own text. Read-only unless refresh=true, which writes a new sentence like the panel's Rewrite; otherwise it writes one only when none is cached (up to ~90 s). workspaceId is a workspace id or exact title from list_prs.\", \"follow.agent-act\", { workspaceId: string, refresh: boolean }, [\"workspaceId\"]],",
59
59
  " [\"link_items\", \"Read any workspace's linked items: Linear issues, Slack threads, docs, artifacts (the spec among them) and GitHub issues, each with its origin (registered, manual, spec, published, extracted), plus what was removed. workspaceId is a workspace id from list_prs.\" + read, \"follow.agent-act\", { workspaceId: string }, [\"workspaceId\"]],",
60
- " [\"ai_rename\", \"Rename a workspace with a short AI-suggested name, like Rename with AI. title skips the model; undo=true restores the name before the last rename (24 h).\" + ask, \"follow.agent-act\", { workspaceId: string, title: string, undo: boolean, ...planned }, [\"workspaceId\"]],",
60
+ " [\"ai_rename\", \"Rename a workspace with a short AI-suggested name, like Rename title with AI. title skips the model; undo=true restores the name before the last rename (24 h).\" + ask, \"follow.agent-act\", { workspaceId: string, title: string, undo: boolean, ...planned }, [\"workspaceId\"]],",
61
61
  " [\"set_linked_items\", \"Change a workspace's linked items for the developer, like the Linked items list: action add (ref: URL or Linear key), remove (ref) or undo (ref, a removal).\" + ask, \"follow.agent-act\", { workspaceId: string, action: { type: \"string\", enum: [\"add\", \"remove\", \"undo\"] }, ref: string, title: string, ...planned }, []],",
62
62
  " [\"agent_settings\", \"Read which agent each of Follow-up's special roles uses (Summaries, Overseer, Recovery, AI priority): provider, model, effort, mode and limits, and whether Wait for background jobs is on. Read-only; the developer changes them in Follow-up settings → Agents.\", \"follow.agent-act\", {}, []],",
63
63
  " [\"inbox_list\", \"Read the developer's Needs-you inbox: each root agent, whether it is flagged and why, snoozes and finish flags. Your own row has self=true; prs lists the PRs a row is about, each with the url its row opens.\", \"follow.agent-act\", { flagged_only: boolean }, []],",
package/server/mcp.mjs CHANGED
@@ -55,7 +55,7 @@ const actionTools = [
55
55
  ["track", "Follow a workspace again after the developer opted it out in Settings. Follow-up follows every workspace by default. Only when the developer asked.", "follow.agent-act", { workspace: string }, ["workspace"]],
56
56
  ["workspace_about", "Read a workspace's Summary: one sentence on what the workspace is for (a reminder, not a status), plus the Linear issues, PRs, Slack threads and docs found in its own text. Read-only unless refresh=true, which writes a new sentence like the panel's Rewrite; otherwise it writes one only when none is cached (up to ~90 s). workspaceId is a workspace id or exact title from list_prs.", "follow.agent-act", { workspaceId: string, refresh: boolean }, ["workspaceId"]],
57
57
  ["link_items", "Read any workspace's linked items: Linear issues, Slack threads, docs, artifacts (the spec among them) and GitHub issues, each with its origin (registered, manual, spec, published, extracted), plus what was removed. workspaceId is a workspace id from list_prs." + read, "follow.agent-act", { workspaceId: string }, ["workspaceId"]],
58
- ["ai_rename", "Rename a workspace with a short AI-suggested name, like Rename with AI. title skips the model; undo=true restores the name before the last rename (24 h)." + ask, "follow.agent-act", { workspaceId: string, title: string, undo: boolean, ...planned }, ["workspaceId"]],
58
+ ["ai_rename", "Rename a workspace with a short AI-suggested name, like Rename title with AI. title skips the model; undo=true restores the name before the last rename (24 h)." + ask, "follow.agent-act", { workspaceId: string, title: string, undo: boolean, ...planned }, ["workspaceId"]],
59
59
  ["set_linked_items", "Change a workspace's linked items for the developer, like the Linked items list: action add (ref: URL or Linear key), remove (ref) or undo (ref, a removal)." + ask, "follow.agent-act", { workspaceId: string, action: { type: "string", enum: ["add", "remove", "undo"] }, ref: string, title: string, ...planned }, []],
60
60
  ["agent_settings", "Read which agent each of Follow-up's special roles uses (Summaries, Overseer, Recovery, AI priority): provider, model, effort, mode and limits, and whether Wait for background jobs is on. Read-only; the developer changes them in Follow-up settings → Agents.", "follow.agent-act", {}, []],
61
61
  ["inbox_list", "Read the developer's Needs-you inbox: each root agent, whether it is flagged and why, snoozes and finish flags. Your own row has self=true; prs lists the PRs a row is about, each with the url its row opens.", "follow.agent-act", { flagged_only: boolean }, []],
@@ -12,7 +12,7 @@ import { isOpen as questionOpen } from "../shared/questions";
12
12
  import { classify, latestPrompt, ledgerSender, type Sources } from "./inbox-classifier";
13
13
  import {
14
14
  EMPTY_OVERSEER, OVERSEER_LABEL, OVERSEER_TITLE, approvesNewWorkspace, branchFor, digestFile, forwardText, forwardedSender, linearKeys,
15
- overseerStateSchema, pageRows, routeDecision, scoreCandidates, workspaceTitleFor, workstreams, type OverseerState, type WorkstreamRow,
15
+ overseerStateSchema, pageRows, type DigestFile, routeDecision, scoreCandidates, workspaceTitleFor, workstreams, type OverseerState, type WorkstreamRow,
16
16
  } from "../shared/overseer";
17
17
  import { overseerPrompt } from "./overseer-prompt-source";
18
18
  import { isLoaded, type LoadSignals } from "../shared/agent-load";
@@ -38,6 +38,9 @@ export type OverseerPaseo = {
38
38
  providers?: { listModels(provider: string): Promise<unknown> };
39
39
  };
40
40
 
41
+ /** The backstop: while an Overseer exists, its digest is built at least this often, so the hook's fallback is bounded. */
42
+ export const DIGEST_BACKSTOP_MS = 10 * 60_000;
43
+
41
44
  export type OverseerDeps = {
42
45
  directory: string;
43
46
  store: { snapshot(): Promise<State> };
@@ -86,6 +89,10 @@ export class Overseer {
86
89
  private plans = new Map<string, { expiresAt: number; run: () => Promise<unknown> }>();
87
90
  private starting: Promise<OverseerState> | null = null;
88
91
  private written: string | null = null;
92
+ private writtenAt: string | null = null;
93
+ private builtAt = -Infinity;
94
+ /** Digest builds since start, for tests and the scale check. */
95
+ digestBuilds = 0;
89
96
  private checkedAt = 0;
90
97
  constructor(private d: OverseerDeps) {}
91
98
  private now() { return this.d.now?.() ?? Date.now(); }
@@ -225,18 +232,40 @@ export class Overseer {
225
232
 
226
233
  /**
227
234
  * The file the agent hook reads at the start of every Overseer turn, from metadata and Follow-up's state only.
228
- * Checked on the inbox tick, rewritten only when its content hash moves, and skipped while the resource governor pauses background work.
235
+ * a-derived-view-is-built-when-read: built when the Overseer's turn starts (turnStarted), at start() and recreation,
236
+ * and by a backstop every DIGEST_BACKSTOP_MS while an Overseer exists, never on the 15 s inbox tick. 2026-11-14 (main
237
+ * 8c54f00, live mix): the tick rebuilt it from the whole Home model, 2.7 MB at 139 workspaces, ~55 of the worker's
238
+ * ~480 MB per 5 min, for a file only the Overseer's prompt hook reads. A turn's build always writes, so `builtAt` tells
239
+ * the hook it is fresh; other builds rewrite only when the content hash moves. `at` stays the last content change.
240
+ * Skipped while the resource governor pauses background work.
229
241
  */
230
- async writeDigest(): Promise<"written" | "same" | "skipped"> {
242
+ async writeDigest(options: { turn?: boolean } = {}): Promise<"written" | "same" | "skipped"> {
231
243
  const s = await this.state();
232
244
  if (!s.agentId || !await this.d.enabled()) return "skipped";
233
245
  if (await this.d.tight?.()) return "skipped";
234
- if (this.written === null) this.written = await readFile(this.digestPath, "utf8").then(t => JSON.parse(t)?.hash ?? "", () => "");
235
- const file = digestFile(s.agentId, await this.workstreams(), this.now());
236
- if (file.hash === this.written) return "same";
237
- await atomic(this.digestPath, file);
238
- this.written = file.hash;
239
- return "written";
246
+ if (this.written === null) {
247
+ const prior = await readFile(this.digestPath, "utf8").then(t => JSON.parse(t) as Partial<DigestFile>, () => null);
248
+ this.written = prior?.hash ?? ""; this.writtenAt = prior?.at ?? null;
249
+ }
250
+ const now = this.now();
251
+ const file = digestFile(s.agentId, await this.workstreams(), now);
252
+ this.builtAt = now; this.digestBuilds++;
253
+ const same = file.hash === this.written;
254
+ if (same && !options.turn) return "same";
255
+ const at = same ? this.writtenAt ?? file.at : file.at;
256
+ await atomic(this.digestPath, { ...file, at, builtAt: new Date(now).toISOString() });
257
+ this.written = file.hash; this.writtenAt = at;
258
+ return same ? "same" : "written";
259
+ }
260
+ /** Builds the digest for the Overseer's turn that just started; any other agent's turn builds nothing. */
261
+ async turnStarted(agentId: string): Promise<"written" | "same" | "skipped"> {
262
+ if ((await this.state()).agentId !== agentId) return "skipped";
263
+ return this.writeDigest({ turn: true });
264
+ }
265
+ /** The inbox tick's call: a build only once DIGEST_BACKSTOP_MS passed since the last, so a fallback is never older. */
266
+ async backstopDigest(): Promise<"written" | "same" | "skipped" | "later"> {
267
+ if (this.now() - this.builtAt < DIGEST_BACKSTOP_MS) return "later";
268
+ return this.writeDigest();
240
269
  }
241
270
 
242
271
  /** One Overseer tool call. The caller must be the current Overseer agent. */
@@ -1,7 +1,7 @@
1
- import { access, constants, mkdir, open, readFile, rename, stat, unlink } from "node:fs/promises";
1
+ import { access, constants, readFile, stat } from "node:fs/promises";
2
2
  import { delimiter, isAbsolute, join, resolve } from "node:path";
3
3
  import { homedir } from "node:os";
4
- import { randomUUID } from "node:crypto";
4
+ import { WriteBehind } from "./write-behind";
5
5
  import { repoKey } from "../shared/reviewers";
6
6
  import {
7
7
  commandName, detect, emptyPrWorkflowConfig, prWorkflowConfigSchema, repoSetting, resolveWorkflow, reviewFixFor,
@@ -80,8 +80,14 @@ export class PrWorkflowStore {
80
80
  }
81
81
  /** Called after every save, so derived files (scopes.json) can be rewritten. */
82
82
  onChanged: () => void = () => undefined;
83
- constructor(readonly directory: string, private probe: Probe = fsProbe(), private now = Date.now, private ttl = 600_000) {}
83
+ /** pr-workflow.json, written behind the reply (an-ack-never-waits-on-the-disk, server/write-behind.ts). */
84
+ readonly persist: WriteBehind<PrWorkflowConfig>;
85
+ constructor(readonly directory: string, private probe: Probe = fsProbe(), private now = Date.now, private ttl = 600_000) {
86
+ this.persist = new WriteBehind({ path: this.path, encode: config => JSON.stringify(config, null, 2) });
87
+ }
84
88
  private get path() { return join(this.directory, "pr-workflow.json"); }
89
+ /** Waits for the mutations in flight, then writes what is pending; the worker's stop calls it. */
90
+ async flush(): Promise<void> { await this.tail; await this.persist.flush(); }
85
91
 
86
92
  async read(): Promise<PrWorkflowConfig> {
87
93
  if (this.cached) return this.cached;
@@ -104,8 +110,8 @@ export class PrWorkflowStore {
104
110
  work(config);
105
111
  for (const [key, value] of Object.entries(config.repos)) { if (value.review === "team") delete value.review; if (!value.workflow && !value.mergeMethod && !value.reviewFix && !value.review && !value.deploy) delete config.repos[key]; }
106
112
  const parsed = prWorkflowConfigSchema.parse(config);
107
- await this.write(parsed);
108
113
  this.cached = parsed; setNoReviewRepos(noReviewRepos(parsed));
114
+ this.persist.set(parsed);
109
115
  this.onChanged();
110
116
  return parsed;
111
117
  });
@@ -195,14 +201,4 @@ export class PrWorkflowStore {
195
201
  return { gt: { installed: machine.gtInstalled, signedIn: machine.signedIn }, default: config.default, reviewFix: config.reviewFix, repos: rows };
196
202
  }
197
203
 
198
- private async write(config: PrWorkflowConfig): Promise<void> {
199
- await mkdir(this.directory, { recursive: true, mode: 0o700 });
200
- const temporary = join(this.directory, `pr-workflow.${randomUUID()}.tmp`);
201
- try {
202
- const file = await open(temporary, "wx", 0o600);
203
- try { await file.writeFile(JSON.stringify(config, null, 2)); await file.sync(); }
204
- finally { await file.close(); }
205
- await rename(temporary, this.path);
206
- } finally { await unlink(temporary).catch(() => undefined); }
207
- }
208
204
  }
package/server/rename.ts CHANGED
@@ -11,7 +11,7 @@ import {
11
11
  import type { AiJobs, JobResult } from "./ai-jobs";
12
12
 
13
13
  /**
14
- * Rename with AI (docs/ai-roles.md#rename-with-ai). The suggestion is one small job on Summaries' model, built from
14
+ * Rename title with AI (docs/ai-roles.md#rename-title-with-ai). The suggestion is one small job on Summaries' model, built from
15
15
  * stored data only (state, the Summary record, linked items, the cached directory's agent titles), so it never reads
16
16
  * a chat or loads an agent. The rename itself is Paseo's own workspace title, and every rename is kept in
17
17
  * `rename.json` for 24 hours so it can be undone.
@@ -24,18 +24,32 @@ export type WorkspaceTitles = {
24
24
  };
25
25
 
26
26
  /**
27
- * The daemon side of WorkspaceTitles: fetch_workspaces narrowed to one id, and set_workspace_title. Nothing else is
27
+ * The daemon side of WorkspaceTitles: workspace list reads paged until the exact id is found, and set_workspace_title. Nothing else is
28
28
  * reachable from here: no agent fetch, no timeline (rename-never-wakes-an-agent, tests/rename.test.ts).
29
29
  */
30
+ type WorkspaceTitleRow = { id: string; name: string; title?: string | null };
30
31
  type TitleDaemon = {
31
- fetchWorkspaces(options?: unknown): Promise<{ entries: { id: string; name: string; title?: string | null }[] }>;
32
+ supportsBackgroundWorkspaces?(): boolean;
33
+ findWorkspace?(workspaceId: string): Promise<WorkspaceTitleRow | null>;
34
+ fetchWorkspaces(options?: unknown): Promise<{ entries: WorkspaceTitleRow[]; pageInfo: { hasMore: boolean; nextCursor: string | null } }>;
32
35
  setWorkspaceTitle(workspaceId: string, title: string | null): Promise<unknown>;
33
36
  };
34
37
  export function renameDaemon(connect: <T>(work: (client: TitleDaemon) => Promise<T>) => Promise<T>, onChange?: () => void): WorkspaceTitles {
35
38
  return {
36
39
  get: id => connect(async client => {
37
- const page = await client.fetchWorkspaces({ filter: { idPrefix: id }, page: { limit: 5 } });
38
- const row = page.entries.find(e => e.id === id);
40
+ // idPrefix is accepted on the wire but ignored by the server. Never treat a list as an id lookup.
41
+ let row: WorkspaceTitleRow | null = null;
42
+ if (typeof client.findWorkspace === "function") row = await client.findWorkspace(id);
43
+ else {
44
+ const filter = client.supportsBackgroundWorkspaces?.() === true ? { includeBackground: true } : {};
45
+ let cursor: string | undefined;
46
+ do {
47
+ const page = await client.fetchWorkspaces({ filter, page: { limit: 200, ...(cursor ? { cursor } : {}) } });
48
+ row = page.entries.find(e => e.id === id) ?? null;
49
+ if (row) break;
50
+ cursor = page.pageInfo.nextCursor ?? undefined;
51
+ } while (cursor);
52
+ }
39
53
  return row ? { title: typeof row.title === "string" && row.title.trim() ? row.title : null, name: row.name } : null;
40
54
  }),
41
55
  set: async (id, title) => { await connect(client => client.setWorkspaceTitle(id, title)); onChange?.(); },
@@ -89,7 +103,7 @@ export class RenameService {
89
103
  // One retry with the reason; never a bigger model or more effort.
90
104
  for (let attempt = 0; attempt < 2; attempt++) {
91
105
  const allowed = await this.d.store.mutate(file => { const b = dailyBudget(file.daily, this.now(), RENAME_DAILY_CAP); if (b.allowed) file.daily = b.next; return b.allowed; });
92
- if (!allowed) throw new Error(`Rename with AI has made its ${RENAME_DAILY_CAP} suggestions for today. Type a name instead.`);
106
+ if (!allowed) throw new Error(`Rename title with AI has made its ${RENAME_DAILY_CAP} suggestions for today. Type a name instead.`);
93
107
  const r: JobResult<{ name: string }> = await this.d.jobs.run({ name: "rename", prompt: renamePrompt(inputs, rejected), schema: renameReplySchema, system: RENAME_SYSTEM,
94
108
  provider: role.provider, model: role.model ?? undefined, thinking: role.thinking, timeoutMs: 45_000, maxPromptChars: 8000, maxOutputChars: 600 });
95
109
  if (!r.ok) { if (r.reason === "invalid-json" || r.reason === "invalid-shape") { rejected = { name: "", reason: "It wasn't the JSON object asked for." }; continue; } throw new Error(`Couldn't suggest a name: ${r.error}`); }
@@ -1,19 +1,24 @@
1
- import { mkdir, open, readFile, rename, unlink } from "node:fs/promises";
1
+ import { readFile } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
- import { randomUUID } from "node:crypto";
3
+ import { WriteBehind } from "./write-behind";
4
4
  import type { State } from "../shared/model";
5
5
  import { githubApi, type GithubApi } from "./github-api";
6
6
  import { cleanList, emptyReviewerConfig, isTeam, repoKey, reviewerConfigSchema, setReviewerConfig, type ReviewerConfig, type ReviewerEntry } from "../shared/reviewers";
7
7
 
8
8
  /**
9
- * The developer's reviewer lists, in their own small file next to state.json (`reviewers.json`). Writes are serialized,
9
+ * The developer's reviewer lists, in their own small file next to state.json (`reviewers.json`). Mutations are
10
+ * serialized and validated, then saved behind the reply (an-ack-never-waits-on-the-disk, server/write-behind.ts):
10
11
  * atomic and owner-only. Every load and save also updates the process-wide config shared code reads.
11
12
  */
12
13
  export class ReviewerConfigStore {
13
14
  private tail: Promise<unknown> = Promise.resolve();
14
15
  private cached: ReviewerConfig | null = null;
15
- constructor(readonly directory: string) {}
16
+ /** reviewers.json, written behind the reply. */
17
+ readonly persist: WriteBehind<ReviewerConfig>;
18
+ constructor(readonly directory: string) { this.persist = new WriteBehind({ path: this.path, encode: config => JSON.stringify(config, null, 2) }); }
16
19
  private get path() { return join(this.directory, "reviewers.json"); }
20
+ /** Waits for the mutations in flight, then writes what is pending; the worker's stop calls it. */
21
+ async flush(): Promise<void> { await this.tail; await this.persist.flush(); }
17
22
 
18
23
  async read(): Promise<ReviewerConfig> {
19
24
  if (this.cached) return this.cached;
@@ -34,8 +39,8 @@ export class ReviewerConfigStore {
34
39
  for (const [key, list] of Object.entries(config.repos)) { const clean = cleanList(list); if (clean.length) config.repos[key] = clean; else delete config.repos[key]; }
35
40
  config.defaults = cleanList(config.defaults);
36
41
  const parsed = reviewerConfigSchema.parse(config);
37
- await this.write(parsed);
38
42
  this.cached = parsed; setReviewerConfig(parsed);
43
+ this.persist.set(parsed);
39
44
  return parsed;
40
45
  });
41
46
  this.tail = next.catch(() => undefined);
@@ -59,16 +64,6 @@ export class ReviewerConfigStore {
59
64
  });
60
65
  }
61
66
 
62
- private async write(config: ReviewerConfig): Promise<void> {
63
- await mkdir(this.directory, { recursive: true, mode: 0o700 });
64
- const temporary = join(this.directory, `reviewers.${randomUUID()}.tmp`);
65
- try {
66
- const file = await open(temporary, "wx", 0o600);
67
- try { await file.writeFile(JSON.stringify(config, null, 2)); await file.sync(); }
68
- finally { await file.close(); }
69
- await rename(temporary, this.path);
70
- } finally { await unlink(temporary).catch(() => undefined); }
71
- }
72
67
  }
73
68
 
74
69
  /**
package/server/store.ts CHANGED
@@ -4,6 +4,7 @@ import { join } from "node:path";
4
4
  import { createHash, randomUUID } from "node:crypto";
5
5
  import { stateSchema, workspaceSchema, type State, type Workspace } from "../shared/model";
6
6
  import { sameJson, deepFreeze, copyOnAccess, detach } from "./cow";
7
+ import { retryBackoff, SURFACE_AFTER, type WriteHealth } from "./write-behind";
7
8
  export { sameJson, deepFreeze } from "./cow";
8
9
 
9
10
  /**
@@ -47,6 +48,17 @@ export class Store {
47
48
  private holds = 0;
48
49
  private held: { volatile: boolean } | null = null;
49
50
  private holdTimer: ReturnType<typeof setTimeout> | null = null;
51
+ /**
52
+ * an-ack-never-waits-on-the-disk, for state.json's own write: a batched write that fails keeps the state in memory,
53
+ * logs, and retries with backoff (it waited for the next change before, and said nothing). From SURFACE_AFTER failed
54
+ * attempts it reports to `health`, the worker's error line, until a write lands.
55
+ */
56
+ health: WriteHealth | undefined;
57
+ retryMs: (attempt: number) => number = retryBackoff;
58
+ log: (line: string) => void = line => console.warn(line);
59
+ /** Consecutive failed state.json writes; 0 once one lands. */
60
+ attempts = 0;
61
+ private retryTimer: ReturnType<typeof setTimeout> | null = null;
50
62
  /** Writes to state.json, for tests and the resource check. */
51
63
  writes = 0;
52
64
  /** `writeMs` 0 writes through inside each mutation (tools, tests); the worker batches with 1000. */
@@ -151,9 +163,24 @@ export class Store {
151
163
  while (this.flushing) await this.flushing;
152
164
  const current = this.state;
153
165
  if (!current) return;
154
- this.flushing = this.write(current).then(saved => { if (this.state === current) this.state = saved; }).finally(() => { this.flushing = null; });
166
+ this.flushing = this.write(current).then(saved => { if (this.state === current) this.state = saved; this.landed(); }, error => { this.failed(error); throw error; }).finally(() => { this.flushing = null; });
155
167
  await this.flushing;
156
168
  }
169
+ private landed(): void {
170
+ if (!this.attempts) return;
171
+ this.log(`[follow-up] saved state.json after ${this.attempts} failed attempt${this.attempts === 1 ? "" : "s"}`);
172
+ this.attempts = 0; this.health?.clear(this.path);
173
+ }
174
+ private failed(error: unknown): void {
175
+ this.attempts++;
176
+ const message = error instanceof Error ? error.message : String(error);
177
+ this.log(`[follow-up] couldn't save state.json (attempt ${this.attempts}): ${message}; kept in memory, retrying`);
178
+ if (this.attempts >= SURFACE_AFTER) this.health?.fail(this.path, this.attempts, message);
179
+ if (this.closing || this.retryTimer) return;
180
+ this.retryTimer = setTimeout(() => { this.retryTimer = null; void this.flush().catch(() => undefined); }, this.retryMs(this.attempts));
181
+ (this.retryTimer as { unref?: () => void }).unref?.();
182
+ }
183
+ private get path(): string { return join(this.directory, "state.json"); }
157
184
  /**
158
185
  * The worker's last word on its state. Refuses new mutations at once; mutations already accepted commit if they
159
186
  * finish by `work`, and anything finishing later is dropped. Then it writes what is pending, by `save` (the end of
@@ -188,6 +215,7 @@ export class Store {
188
215
  if (this.timer) { clearTimeout(this.timer); this.timer = null; }
189
216
  if (this.volatileTimer) { clearTimeout(this.volatileTimer); this.volatileTimer = null; }
190
217
  if (this.holdTimer) { clearTimeout(this.holdTimer); this.holdTimer = null; }
218
+ if (this.retryTimer) { clearTimeout(this.retryTimer); this.retryTimer = null; }
191
219
  }
192
220
  /** Validates (applying schema defaults), writes when changed and returns the saved state, frozen. */
193
221
  private async write(state: State): Promise<State> {
@@ -45,6 +45,8 @@ export interface WorkerParts {
45
45
  store: { close(work: Deadline, save: Deadline): Promise<void> };
46
46
  /** The inbox's held lastSeen (store-writes-only-real-changes), written with the store before the lock goes. */
47
47
  inbox?: { flush(): Promise<void> };
48
+ /** Files saved behind the reply (an-ack-never-waits-on-the-disk): what is pending is written before the lock goes. */
49
+ files?: { flush(): Promise<void> }[];
48
50
  unlock?: (() => Promise<unknown>) | null;
49
51
  }
50
52
  /**
@@ -64,5 +66,6 @@ export async function stopWorker(parts: WorkerParts, ms = STOP_WAIT_MS): Promise
64
66
  await settleWithin(parts.ready, work);
65
67
  await step(() => parts.store.close(work, save), save);
66
68
  if (parts.inbox) await step(() => parts.inbox!.flush(), save);
69
+ if (parts.files?.length) await step(() => Promise.allSettled(parts.files!.map(f => f.flush())), save);
67
70
  if (parts.unlock) await step(parts.unlock, save);
68
71
  }
@@ -0,0 +1,144 @@
1
+ import { mkdir, open, rename, unlink, type FileHandle } from "node:fs/promises";
2
+ import { basename, dirname, join } from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+
5
+ /**
6
+ * an-ack-never-waits-on-the-disk: a small JSON file that is saved behind the reply. 2026-11-14 (CI, rpc-ack):
7
+ * follow.save-reviewers waited 1458 ms on reviewers.json's fsync, and follow.inbox-list 664 ms on an inbox.json write it
8
+ * queued behind. The event loop was idle both times; a loaded runner's fsync alone outlasted the 500 ms budget.
9
+ *
10
+ * The owner keeps the value in memory, validated and authoritative, and hands each new value to set(). The write runs
11
+ * outside the owner's queue, the way Store.flush does: one write at a time, always of the newest value (coalesced), as a
12
+ * temp file, fsync, then rename. A failed write keeps the value, logs, and retries with backoff. From the third failed
13
+ * attempt it reports to `WriteHealth`, which the worker shows as its error line until the write lands. flush() (the
14
+ * worker's stop) writes what is pending and waits for it.
15
+ *
16
+ * Durability: a crash before the write lands loses that value, as it does for state.json and inbox.json.
17
+ */
18
+ export type Encoded = string | Buffer[];
19
+ export interface WriteBehindOptions<T> {
20
+ path: string;
21
+ encode: (value: T) => Encoded;
22
+ /** 0: as soon as the reply is out. More: at most one write per window (the inbox). */
23
+ delayMs?: number;
24
+ /** The wait before retry `attempt` (1-based) after a failure. */
25
+ retryMs?: (attempt: number) => number;
26
+ /** Called once a value has landed in the file. */
27
+ onWritten?: (value: T) => void;
28
+ health?: WriteHealth;
29
+ log?: (line: string) => void;
30
+ }
31
+ /** Failed attempts that make a failure the developer's business (until then it's logged only). */
32
+ export const SURFACE_AFTER = 3;
33
+ export const retryBackoff = (attempt: number) => Math.min(1_000 * 2 ** (attempt - 1), 30_000);
34
+
35
+ export class WriteBehind<T> {
36
+ private pending: { value: T } | null = null;
37
+ private inflight: { value: T } | null = null;
38
+ private writing: Promise<void> | null = null;
39
+ private timer: ReturnType<typeof setTimeout> | null = null;
40
+ private written: { value: T } | null = null;
41
+ /** Consecutive failed attempts; 0 once a write lands. */
42
+ attempts = 0;
43
+ writes = 0;
44
+ lastError: string | null = null;
45
+ /** Where a failure that keeps failing is reported; the worker sets its own. */
46
+ health: WriteHealth | undefined;
47
+ constructor(private o: WriteBehindOptions<T>) { this.health = o.health; }
48
+
49
+ /** Saves `value` behind the caller: it returns at once. A newer set() before the write starts replaces it. */
50
+ set(value: T): void {
51
+ if (this.inflight?.value === value && !this.pending) return;
52
+ if (this.written?.value === value && !this.pending && !this.inflight) return;
53
+ this.pending = { value };
54
+ this.arm(this.attempts ? this.retryDelay() : this.o.delayMs ?? 0);
55
+ }
56
+ /** Writes what is pending now and waits for it (and any write in flight). Throws when the write fails. */
57
+ async flush(): Promise<void> {
58
+ this.disarm();
59
+ while (this.writing) await this.writing.catch(() => undefined);
60
+ if (this.pending) await this.start();
61
+ }
62
+ /** Whether a value waits for its write to start (a newer set() would replace it at no cost). */
63
+ get queued(): boolean { return !!this.pending; }
64
+ /** Whether a value hasn't landed yet. */
65
+ get dirty(): boolean { return !!(this.pending || this.inflight); }
66
+
67
+ private retryDelay(): number { return (this.o.retryMs ?? retryBackoff)(this.attempts); }
68
+ private arm(ms: number): void {
69
+ if (this.timer || this.writing) return;
70
+ this.timer = setTimeout(() => { this.timer = null; void this.start().catch(() => undefined); }, ms);
71
+ (this.timer as { unref?: () => void }).unref?.();
72
+ }
73
+ private disarm(): void { if (this.timer) { clearTimeout(this.timer); this.timer = null; } }
74
+ private start(): Promise<void> {
75
+ if (this.writing) return this.writing;
76
+ const job = this.pending;
77
+ if (!job) return Promise.resolve();
78
+ this.pending = null; this.inflight = job;
79
+ const run = this.writeOnce(job).finally(() => {
80
+ this.inflight = null; this.writing = null;
81
+ if (this.pending) this.arm(this.attempts ? this.retryDelay() : this.o.delayMs ?? 0);
82
+ });
83
+ this.writing = run;
84
+ return run;
85
+ }
86
+ private async writeOnce(job: { value: T }): Promise<void> {
87
+ try {
88
+ await writeAtomic(this.o.path, this.o.encode(job.value));
89
+ } catch (error) {
90
+ this.attempts++;
91
+ this.lastError = error instanceof Error ? error.message : String(error);
92
+ this.pending ??= job; // a newer value supersedes it; otherwise it's retried
93
+ (this.o.log ?? console.warn)(`[follow-up] couldn't save ${basename(this.o.path)} (attempt ${this.attempts}): ${this.lastError}; kept in memory, retrying`);
94
+ if (this.attempts >= SURFACE_AFTER) this.health?.fail(this.o.path, this.attempts, this.lastError);
95
+ throw error;
96
+ }
97
+ if (this.attempts) (this.o.log ?? console.warn)(`[follow-up] saved ${basename(this.o.path)} after ${this.attempts} failed attempt${this.attempts === 1 ? "" : "s"}`);
98
+ this.attempts = 0; this.lastError = null; this.writes++; this.written = job;
99
+ this.health?.clear(this.o.path);
100
+ this.o.onWritten?.(job.value);
101
+ }
102
+ }
103
+
104
+ /** Files whose saving keeps failing, for the worker's error line (loadError ?? hookError ?? saveError ?? engine.error). */
105
+ export class WriteHealth {
106
+ private failing = new Map<string, { attempts: number; error: string }>();
107
+ fail(path: string, attempts: number, error: string): void { this.failing.set(path, { attempts, error }); }
108
+ clear(path: string): void { this.failing.delete(path); }
109
+ /** One line for the first failing file, or null when every save has landed. */
110
+ message(): string | null {
111
+ const first = [...this.failing][0];
112
+ if (!first) return null;
113
+ const [path, { attempts, error }] = first;
114
+ return `Follow-up couldn't save ${basename(path)} (${attempts} attempts: ${error}). Your change is kept and saving keeps retrying; check the disk and Follow-up's data folder.`;
115
+ }
116
+ }
117
+
118
+ /** Temp file, fsync, rename: the file holds the old value or the new one, never part of one. Owner-only. */
119
+ export async function writeAtomic(path: string, data: Encoded): Promise<void> {
120
+ const directory = dirname(path);
121
+ await mkdir(directory, { recursive: true, mode: 0o700 });
122
+ const temporary = join(directory, `${basename(path, ".json")}.${randomUUID()}.tmp`);
123
+ try {
124
+ const file = await open(temporary, "wx", 0o600);
125
+ try {
126
+ if (typeof data === "string") await file.writeFile(data); else await writeParts(file, data);
127
+ await file.sync();
128
+ } finally { await file.close(); }
129
+ await rename(temporary, path);
130
+ } finally { await unlink(temporary).catch(() => undefined); }
131
+ }
132
+
133
+ /** Writes every part, however the OS splits a vectored write. */
134
+ export async function writeParts(file: FileHandle, parts: Buffer[]): Promise<void> {
135
+ let rest = parts;
136
+ while (rest.length) {
137
+ const { bytesWritten } = await file.writev(rest.length > 512 ? rest.slice(0, 512) : rest);
138
+ let n = bytesWritten, i = 0;
139
+ while (i < rest.length && n >= rest[i]!.length) n -= rest[i++]!.length;
140
+ rest = rest.slice(i);
141
+ if (n > 0) rest = [rest[0]!.subarray(n), ...rest.slice(1)];
142
+ if (bytesWritten === 0 && rest.length) throw new Error(`${file.fd}: the write made no progress`);
143
+ }
144
+ }
@@ -92,7 +92,7 @@ export const prioritiesRpc = defineRpc({ name: "follow.priorities", input: z.obj
92
92
  /** Provider session limits from the Smart Session plugin, for Home's meters. Hidden when it isn't installed. */
93
93
  /** Summary: collapsed reads the cache; open may start an overview; refresh always does. */
94
94
  export const workspaceAboutRpc = defineRpc({ name: "follow.workspace-about", input: z.object({ workspaceId: idSchema, open: z.boolean().optional(), refresh: z.boolean().optional() }), output: aboutViewSchema });
95
- // Rename with AI (shared/rename.ts): the dialog's state and one suggestion, and the rename or its Undo.
95
+ // Rename title with AI (shared/rename.ts): the dialog's state and one suggestion, and the rename or its Undo.
96
96
  export const renameStatusRpc = defineRpc({ name: "follow.rename-status", input: z.object({ workspaceId: idSchema, suggest: z.boolean().optional() }), output: renameStatusSchema });
97
97
  export const renameWorkspaceRpc = defineRpc({ name: "follow.rename-workspace", input: z.object({ workspaceId: idSchema, title: z.string().max(300).optional(), undo: z.boolean().optional() }), output: renameResultSchema });
98
98
  export const usageRpc = defineRpc({ name: "follow.usage", input: z.object({}), output: usageSchema });