paseo-follow-up 2.0.2-beta.0 → 2.0.2-beta.2

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/CHANGELOG.md CHANGED
@@ -4,49 +4,14 @@ What changed in each version of Follow-up, newest first. Follow-up shows the cur
4
4
 
5
5
  ## 2.0.1 (2026-11-14)
6
6
 
7
- Follow-up 2.0.1 turns fixes into plain tasks you can see and steer, makes merging one click, and runs much lighter on your machine.
8
-
9
- ### Tasks you can see and steer
10
-
11
- - What Follow-up finds on your PRs (conflicts, review comments, failing checks, restacks) is now a task in the workspace's Tasks, with one plain state: Queued, Sent, Needs you or Done.
12
- - The top of Tasks says who the next message goes to, when it goes and why it waits, with Preview and Send now. Turn Auto-send off on a task to keep it for yourself.
13
- - Follow-up checks GitHub instead of asking you to Retry: what's cleared is done, and what's still open goes in the next message. It asks you only when a task went out twice with no change.
14
- - Home's "Follow-up is fixing" is now "Sending": each message on its way, with when and why it goes out.
15
-
16
- ### Merging and review
17
-
18
- - One click on Merge merges, and the button names everything it merges first ("Merge 3 PRs"). A blocker found at click time merges nothing and says why.
19
- - Set a repository to No review in Settings → Shipping PRs, or with "Let the agent merge in" on a no-reviewers row: agents merge their own PRs once checks pass, and Follow-up never asks you for reviewers there.
20
- - A PR without reviewers asks once in Needs you, naming the suggested reviewer.
21
- - Every Needs you row about a PR opens it in one click.
22
-
23
- ### Answering agents
24
-
25
- - "Add note" on a decision card sends your pick with a note ("A, but keep the BOM off").
26
- - On Paseo 0.16, Put in chat adds your answer to the end of the agent's message box. An answer you copied or put in the chat reads "not sent yet" everywhere until it reaches the agent.
27
- - An open question shows once, under one name, in the panel and on Home.
28
-
29
- ### New
30
-
31
- - Rename with AI from a workspace's menu or ⌘K: Follow-up suggests a short name, and Undo puts the old one back.
32
- - Report a bug, an idea or feedback from Settings, ⌘K or any error message. Your agent writes it up, removes private names and shows you the issue before it goes to GitHub.
33
- - When an agent creates another agent or a workspace, the chat shows a card for it with its live status.
34
- - Search results look like your list's rows, with your words highlighted. The sidebar view has a filter and Home's sort, the same on every device, and right-click opens a workspace's menu.
35
- - Home remembers which groups you folded (Needs you always opens), and the phone keeps your settings category and folded sections.
36
-
37
- ### Lighter and faster
38
-
39
- - On Paseo 0.16, Home, the sidebar and the pills update the moment something changes instead of checking every 15 to 60 seconds, and an open Follow-up sends almost nothing while you aren't using it.
40
- - Follow-up uses about half the CPU and much less memory, reads about 50 times less from disk, keeps one connection to Paseo and uses far less of your GitHub API limit.
41
- - Pull requests keep their last known status when GitHub is unreachable or out of API budget, instead of turning Unknown.
42
-
43
- ### Settings and fixes
44
-
45
- - The deploy check is a per-repository setting on your machine: Settings → Following → PR workflow shows it for each repository, or Not set up.
46
- - With Follow every workspace off, only the projects you switch on are followed.
47
- - Follow-up pauses only when you stop the main agent, not after a compaction, a replaced turn or a reload.
48
- - A merged PR reads "Merged", not "PR closed", and a PR merged long ago no longer comes back to Needs you.
49
- - "No ask stated" and "Nothing needed" no longer linger in Needs you above real work.
7
+ Fixes are easier to follow, merging takes one click, and Follow-up runs much lighter.
8
+
9
+ - **Tasks:** what Follow-up finds on your PRs (conflicts, review comments, failing checks) is now a task with one clear state, and Tasks shows what goes to the agent next and when.
10
+ - **One-click merge,** and a No review setting per repository that lets agents merge their own PRs.
11
+ - **Answers:** add a note to your pick on a decision card, or put your answer straight into the agent's message box.
12
+ - **New:** Rename with AI, Report a bug from Settings or any error, and a card in the chat for each agent or workspace an agent creates.
13
+ - **Lighter:** about half the CPU and much less memory, and on Paseo 0.16 changes show up live instead of by polling.
14
+ - Plus many smaller fixes.
50
15
 
51
16
  <details><summary>Full changelog since 2.0.0</summary>
52
17
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "paseo-follow-up",
3
3
  "private": false,
4
- "version": "2.0.2-beta.0",
4
+ "version": "2.0.2-beta.2",
5
5
  "description": "A Paseo plugin that follows every workspace until the work is done: one Home for what needs you, questions you answer anywhere, and repairs that send themselves.",
6
6
  "type": "module",
7
7
  "files": [
@@ -37,6 +37,7 @@
37
37
  "test:scale": "node scripts/scale-check.mjs --workspaces 140 --awake 5 --idle 90 --realistic --rss-budget 300 --idle-rss-budget realistic --cpu-budget 3 --request-budget 2",
38
38
  "test:scale:live": "node scripts/scale-check.mjs --workspaces 140 --awake 5 --live-sized --busy 180 --idle 90 --rss-budget 300 --idle-rss-budget 240 --cpu-budget 3 --request-budget 2 --budgets-report-only",
39
39
  "check:notes": "node scripts/release-notes.mjs --check",
40
+ "release:version": "node scripts/release-notes.mjs --next-version",
40
41
  "release:notes": "node scripts/release-notes.mjs",
41
42
  "test:feeds": "node scripts/screenshots.mjs --only feeds --out .feeds-check",
42
43
  "test:wait": "node scripts/check-wait.mjs",
package/server/cow.ts CHANGED
@@ -19,7 +19,12 @@
19
19
  * stepped 315 → 405 MB with a harness-sized JS heap (the second store with the bug after #139's Store.mutate).
20
20
  */
21
21
  type Obj = Record<string, unknown>;
22
- export type Collection = { kind: "record" } | { kind: "array"; id: (item: never) => string };
22
+ /**
23
+ * How a top-level field is drafted. `record` and `array` hand out a lazy view per item. `frozen` is a field that is only
24
+ * ever read whole and replaced whole (InboxState.briefOrigins, a 500-item log): the draft hands out the saved, frozen
25
+ * value itself (an in-place write throws), and a replacement keeps the saved items it carries over as they are.
26
+ */
27
+ export type Collection = { kind: "record" } | { kind: "array"; id: (item: never) => string } | { kind: "frozen" };
23
28
  export type Changes = {
24
29
  /** Top-level fields whose value changed (a collection counts when an item was added, removed, replaced or changed). */
25
30
  fields: Set<string>;
@@ -64,7 +69,8 @@ export function deepFreeze<T>(value: T): T {
64
69
  /** A plain, mutable copy of a (possibly frozen) JSON value. */
65
70
  const copy = <T>(v: T): T => structuredClone(v);
66
71
 
67
- type Tracked = { target: Obj | unknown[]; copied: Set<string> };
72
+ /** A collection's draft: its target, the items written or copied, and the ids deleted (finish reads only these). */
73
+ type Tracked = { target: Obj | unknown[]; copied: Set<string>; deleted: Set<string> };
68
74
  /** One collection item behind its views: the saved (frozen) item until a real write, then a private copy of it. */
69
75
  type Item = { saved: object; clone: object | null; map: Map<object, object> | null; onCopy: () => void; views: WeakMap<object, object> };
70
76
  /** Every view of a saved node (the item itself or anything inside it): which item, and which saved node. */
@@ -80,6 +86,12 @@ function own(item: Item): void {
80
86
  if (item.clone) return;
81
87
  item.clone = copy(item.saved); item.map = new Map(); pair(item.saved, item.clone, item.map); item.onCopy();
82
88
  }
89
+ /**
90
+ * What a draft value stands for, to read without views: the saved (frozen) node, or the item's copy once written, or
91
+ * the value itself when it isn't a view. A pure reader that walks a whole draft item (InboxStore's reduce copies the
92
+ * entry it is given) reads this instead, so the walk makes no view per nested object; it must never write to it.
93
+ */
94
+ export function peek<T>(v: T): T { return resolve(v) as T; }
83
95
  /** The plain value a view stands for: its item's copy of the node once copied, else the saved node itself. */
84
96
  const resolve = (v: unknown): unknown => {
85
97
  const view = isObject(v) ? views.get(v) : undefined;
@@ -97,11 +109,17 @@ function plain(v: unknown, into?: Item): unknown {
97
109
  const n = view.item === into ? into.map?.get(view.node) : undefined;
98
110
  return n ?? copy(view.item.map?.get(view.node) ?? view.node);
99
111
  }
100
- if (Array.isArray(v)) { let changed = false; const out = v.map(x => { const p = plain(x, into); if (p !== x) changed = true; return p; }); return changed ? out : v; }
101
- if (isObject(v) && Object.getPrototypeOf(v) === Object.prototype) {
102
- let changed = false; const out: Obj = {};
103
- for (const [k, x] of Object.entries(v)) { const p = plain(x, into); if (p !== x) changed = true; out[k] = p; }
104
- return changed ? out : v;
112
+ // A copy only from the first part that holds a view (a-mutation-costs-what-it-changes): 2026-11-14, every new entry
113
+ // a turn stored was shadow-copied whole and the copy thrown away, 37 MB per 5 min under live's turn rate.
114
+ if (Array.isArray(v)) {
115
+ let out: unknown[] | null = null;
116
+ for (let i = 0; i < v.length; i++) { const x = v[i], p = plain(x, into); if (p !== x) (out ??= v.slice())[i] = p; }
117
+ return out ?? v;
118
+ }
119
+ if (Object.getPrototypeOf(v) === Object.prototype) {
120
+ let out: Obj | null = null;
121
+ for (const k of Object.keys(v)) { const x = (v as Obj)[k], p = plain(x, into); if (p !== x) (out ??= { ...(v as Obj) })[k] = p; }
122
+ return out ?? v;
105
123
  }
106
124
  return v;
107
125
  }
@@ -169,7 +187,7 @@ export function copyOnAccess<T extends object>(saved: T, collections: Readonly<R
169
187
  const proxies = new WeakMap<object, Tracked>();
170
188
  const collection = (field: string, value: object): object => {
171
189
  const target: Obj | unknown[] = Array.isArray(value) ? [...value] : { ...(value as Obj) };
172
- const copied = new Set<string>();
190
+ const copied = new Set<string>(); const deleted = new Set<string>();
173
191
  const proxy = new Proxy(target, {
174
192
  get(t, k, receiver) {
175
193
  if (typeof k !== "string" || !Object.hasOwn(t, k) || copied.has(k) || (Array.isArray(t) && k === "length")) return Reflect.get(t, k, receiver);
@@ -178,9 +196,9 @@ export function copyOnAccess<T extends object>(saved: T, collections: Readonly<R
178
196
  return (t as Obj)[k];
179
197
  },
180
198
  set(t, k, v) { if (typeof k === "string") copied.add(k); return Reflect.set(t, k, item(v)); },
181
- deleteProperty(t, k) { if (typeof k === "string") copied.delete(k); return Reflect.deleteProperty(t, k); },
199
+ deleteProperty(t, k) { if (typeof k === "string") { copied.delete(k); deleted.add(k); } return Reflect.deleteProperty(t, k); },
182
200
  });
183
- proxies.set(proxy, { target, copied });
201
+ proxies.set(proxy, { target, copied, deleted });
184
202
  void field;
185
203
  return proxy;
186
204
  };
@@ -189,13 +207,18 @@ export function copyOnAccess<T extends object>(saved: T, collections: Readonly<R
189
207
  const draft = new Proxy(root, {
190
208
  get(t, k, receiver) {
191
209
  if (typeof k !== "string" || !Object.hasOwn(t, k) || touched.has(k)) return Reflect.get(t, k, receiver);
210
+ if (collections[k]?.kind === "frozen") return t[k];
192
211
  const v = t[k]; touched.add(k);
193
212
  if (isObject(v)) t[k] = collections[k] ? collection(k, v) : copy(v);
194
213
  return t[k];
195
214
  },
196
215
  // A collection keeps item views (finish resolves them, keeping untouched items' saved objects); anything else is
197
216
  // stored plain, so no view reaches the saved value.
198
- set(t, k, v) { if (typeof k === "string") touched.add(k); return Reflect.set(t, k, proxies.has(v as object) ? v : collections[k as string] && isObject(v) ? v : plain(v)); },
217
+ set(t, k, v) {
218
+ if (typeof k === "string") touched.add(k);
219
+ const kind = typeof k === "string" ? collections[k]?.kind : undefined;
220
+ return Reflect.set(t, k, proxies.has(v as object) ? v : kind && kind !== "frozen" && isObject(v) ? v : plain(v));
221
+ },
199
222
  deleteProperty(t, k) { if (typeof k === "string") touched.add(k); return Reflect.deleteProperty(t, k); },
200
223
  }) as T;
201
224
 
@@ -207,9 +230,16 @@ export function copyOnAccess<T extends object>(saved: T, collections: Readonly<R
207
230
  if (!Object.hasOwn(root, k)) { if (before[k] !== undefined) changes.fields.add(k); continue; }
208
231
  const was = before[k];
209
232
  if (!touched.has(k)) { next[k] = was; continue; }
210
- const now = unwrap(root[k]);
211
233
  const kind = collections[k];
212
- if (kind && isObject(now) && isObject(was)) {
234
+ const tracked = isObject(root[k]) ? proxies.get(root[k] as object) : undefined;
235
+ if (kind?.kind === "record" && tracked && isObject(was) && !Array.isArray(tracked.target)) {
236
+ const { value, items, removed } = mergeTouched(was as Obj, tracked);
237
+ next[k] = value;
238
+ if (value !== was) { changes.fields.add(k); changes.items.set(k, items); changes.removed.set(k, removed); }
239
+ continue;
240
+ }
241
+ const now = kind?.kind === "frozen" ? root[k] : unwrap(root[k]);
242
+ if (kind && kind.kind !== "frozen" && isObject(now) && isObject(was)) {
213
243
  const { value, items, removed } = merge(kind, was, now, proxies.get(root[k] as object));
214
244
  next[k] = value;
215
245
  if (value !== was) { changes.fields.add(k); changes.items.set(k, items); changes.removed.set(k, removed); }
@@ -232,6 +262,24 @@ export function copyOnAccess<T extends object>(saved: T, collections: Readonly<R
232
262
  return { draft, finish };
233
263
  }
234
264
 
265
+ /**
266
+ * A record collection's next value from only the ids the draft wrote, copied or deleted: the saved record itself when
267
+ * none of them changed, else one copy of it. 2026-11-14: finish rebuilt the whole 86-entry inbox record twice per
268
+ * mutation (unwrap, then merge), no-ops included.
269
+ */
270
+ function mergeTouched(was: Obj, tracked: Tracked) {
271
+ const t = tracked.target as Obj; const items = new Set<string>(); const removed = new Set<string>();
272
+ let value: Obj | null = null;
273
+ for (const id of tracked.copied) {
274
+ if (!Object.hasOwn(t, id)) continue;
275
+ const v = item(t[id]);
276
+ if (Object.hasOwn(was, id) && (v === was[id] || sameJson(v, was[id]))) continue;
277
+ (value ??= { ...was })[id] = v; items.add(id);
278
+ }
279
+ for (const id of tracked.deleted) if (Object.hasOwn(was, id) && !Object.hasOwn(t, id)) { value ??= { ...was }; delete value[id]; removed.add(id); }
280
+ return { value: value ?? was, items, removed };
281
+ }
282
+
235
283
  /** The next collection: saved items where nothing changed (by identity first, then by value), the draft's otherwise. */
236
284
  function merge(kind: Collection, was: object, now: object, tracked: Tracked | undefined) {
237
285
  const items = new Set<string>(); const removed = new Set<string>();
@@ -245,6 +293,7 @@ function merge(kind: Collection, was: object, now: object, tracked: Tracked | un
245
293
  for (const k of Object.keys(a)) if (!Object.hasOwn(b, k)) { removed.add(k); same = false; }
246
294
  return { value: same ? was : value, items, removed };
247
295
  }
296
+ if (kind.kind !== "array") throw new Error(`merge: ${kind.kind} isn't an item collection`);
248
297
  const id = kind.id as (item: unknown) => string;
249
298
  const a = was as unknown[], b = now as unknown[];
250
299
  const byId = new Map(a.map(item => [id(item), item]));
@@ -30,8 +30,15 @@ export const LOOKUP_MAX = 40;
30
30
  * agent (a timeline or subagent read) re-checks that one agent first: see `live`.
31
31
  */
32
32
  export class DaemonDirectory {
33
- private rows: (DirectoryRows & { at: number; agentsAt: number }) | null = null;
33
+ private rows: (DirectoryRows & { at: number; agentsAt: number; projectsAt: number }) | null = null;
34
+ /**
35
+ * In-flight reads, joined by every concurrent caller (concurrent-readers-share-one-request): one request per list,
36
+ * whatever the number of readers. 2026-11-14 live: each repository's PR-workflow detection read the project list
37
+ * itself, ~19 project.list requests back to back every 10 minutes.
38
+ */
34
39
  private loading: Promise<DirectoryRows> | null = null;
40
+ private loadingProjects: Promise<DirectoryRows> | null = null;
41
+ private loadingAgents: Promise<DirectoryRows> | null = null;
35
42
  private dirty = false;
36
43
  private projectsStale = false;
37
44
  /**
@@ -79,7 +86,7 @@ export class DaemonDirectory {
79
86
  const now = this.now();
80
87
  const rows = this.rows;
81
88
  const due = !rows || options.fresh === true || now - rows.at >= BACKSTOP_REFRESH_MS || (this.dirty && now - rows.at >= DIRTY_REFRESH_MS);
82
- if (!due && rows && options.fresh === "agents") return this.listedThisTick() && !options.force ? rows : this.refreshAgents();
89
+ if (!due && rows && options.fresh === "agents") return this.listedThisTick() && !options.force ? rows : this.refreshAgents(options.force === true);
83
90
  if (!due && rows && !this.projectsStale) return rows;
84
91
  if (!due && rows) return this.refreshProjects();
85
92
  let failedProjects = false;
@@ -98,30 +105,42 @@ export class DaemonDirectory {
98
105
  const fresh = await loading;
99
106
  this.rememberArchived(this.rows?.agents); this.rememberArchived(fresh.agents);
100
107
  const at = this.now();
101
- this.rows = { ...fresh, at, agentsAt: at }; this.agentsTick = this.tick;
108
+ this.rows = { ...fresh, at, agentsAt: at, projectsAt: at }; this.agentsTick = this.tick;
102
109
  if (failedProjects) this.projectsStale = true;
103
110
  return this.rows;
104
111
  } catch (error) { this.dirty = true; throw error; }
105
112
  finally { if (this.loading === loading) this.loading = null; }
106
113
  }
107
114
 
108
- private async refreshAgents(): Promise<DirectoryRows> {
115
+ /** Joins a list already in flight, except for `force`: that caller needs a list started after it asked. */
116
+ private refreshAgents(force: boolean): Promise<DirectoryRows> {
117
+ if (this.loadingAgents && !force) return this.loadingAgents;
118
+ const loading = this.listAgents().finally(() => { if (this.loadingAgents === loading) this.loadingAgents = null; });
119
+ this.loadingAgents = loading; return loading;
120
+ }
121
+ private async listAgents(): Promise<DirectoryRows> {
109
122
  const agents = await this.connect(client => this.list("fetch_agents_request", cursor => client.fetchAgents({ page: { limit: 100, ...(cursor ? { cursor } : {}) } })));
110
123
  this.rememberArchived(this.rows?.agents); this.rememberArchived(agents);
111
124
  if (this.rows) { this.rows.agents = agents; this.rows.agentsAt = this.now(); this.agentsTick = this.tick; }
112
125
  return this.rows!;
113
126
  }
114
- private async refreshProjects(): Promise<DirectoryRows> {
115
- const catalog = await this.connect(client => { this.count("project.list.request"); return client.listProjects(); });
116
- this.projectsStale = false;
117
- if (this.rows) this.rows.projects = catalog.projects;
118
- return this.rows!;
127
+ private refreshProjects(): Promise<DirectoryRows> {
128
+ if (this.loadingProjects) return this.loadingProjects;
129
+ const loading = (async () => {
130
+ const catalog = await this.connect(client => { this.count("project.list.request"); return client.listProjects(); });
131
+ this.projectsStale = false;
132
+ if (this.rows) { this.rows.projects = catalog.projects; this.rows.projectsAt = this.now(); }
133
+ return this.rows!;
134
+ })().finally(() => { if (this.loadingProjects === loading) this.loadingProjects = null; });
135
+ this.loadingProjects = loading; return loading;
119
136
  }
120
137
 
121
138
  /** The project list, re-read when older than `maxAgeMs` (Settings opening it), else the cached one. */
122
139
  async projects(maxAgeMs = BACKSTOP_REFRESH_MS): Promise<Project[]> {
123
140
  const rows = await this.read();
124
- if (this.rows && this.now() - this.rows.at >= maxAgeMs) { this.projectsStale = true; return (await this.read()).projects; }
141
+ // Judged by when the projects were listed, not the whole directory: a project re-read doesn't refresh `at`, so this
142
+ // used to re-list on every call once the directory was a minute old.
143
+ if (this.rows && this.now() - this.rows.projectsAt >= maxAgeMs) { this.projectsStale = true; return (await this.read()).projects; }
125
144
  return rows.projects;
126
145
  }
127
146
 
package/server/inbox.ts CHANGED
@@ -1,14 +1,14 @@
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 } from "node:fs/promises";
3
+ import { mkdir, open, readFile, rename, unlink, type FileHandle } from "node:fs/promises";
4
4
  import { join } from "node:path";
5
5
  import { randomUUID } from "node:crypto";
6
6
  import { realTimers, stableMessageId, withDeadline, type Timers } from "./delivery";
7
7
  import { BackgroundAgents } from "./background-agents";
8
8
  import { deepFreeze } from "./store";
9
- import { copyOnAccess, detach, type Changes } from "./cow";
9
+ import { copyOnAccess, detach, peek, type Changes } from "./cow";
10
10
  import { z } from "zod";
11
- import { emptyInbox, entrySchema, expired, inboxStateSchema, type OutboxEntry, newEntry, reduce, StaleSignOff, type Entry, type InboxEvent, type InboxRow, type InboxState, type Reason, liveFlag, withoutRunState, FACT_REASONS, prEndEvent, reviewersBriefPr, markNotified, notifiedBefore, prNotice, pruneNotified } from "../shared/inbox";
11
+ import { BRIEF_ORIGINS_MAX, briefOriginSchema, emptyInbox, entrySchema, expired, inboxStateSchema, type OutboxEntry, newEntry, reduce, StaleSignOff, type Entry, type InboxEvent, type InboxRow, type InboxState, type Reason, liveFlag, withoutRunState, FACT_REASONS, prEndEvent, reviewersBriefPr, markNotified, notifiedBefore, prNotice, pruneNotified } from "../shared/inbox";
12
12
  import type { State as FollowState, Workspace as FollowWorkspace } from "../shared/model";
13
13
  import { asksForReviewers } from "../shared/attention";
14
14
  import { followUpObligations } from "../shared/follow-up";
@@ -84,10 +84,10 @@ export class InboxStore {
84
84
  async mutate<T>(work: (state: InboxState) => T | Promise<T>): Promise<T> {
85
85
  const next = this.tail.then(async () => {
86
86
  const current = await this.load();
87
- const { draft, finish } = copyOnAccess(current, { entries: { kind: "record" } });
87
+ const { draft, finish } = copyOnAccess(current, INBOX_COLLECTIONS);
88
88
  const value = await work(draft);
89
89
  const done = finish();
90
- if (done.changed) await this.save(done.next, done.changes);
90
+ if (done.changed) await this.save(done.next, done.changes, current);
91
91
  return detach(value);
92
92
  });
93
93
  this.tail = next.catch(() => undefined);
@@ -103,7 +103,7 @@ export class InboxStore {
103
103
  const next = this.tail.then(async () => {
104
104
  const current = await this.load();
105
105
  if (current.lastSeen === at) return;
106
- await this.save({ ...current, lastSeen: at }, { fields: new Set(["lastSeen"]), items: new Map(), removed: new Map() });
106
+ await this.save({ ...current, lastSeen: at }, { fields: new Set(["lastSeen"]), items: new Map(), removed: new Map() }, current);
107
107
  });
108
108
  this.tail = next.catch(() => undefined);
109
109
  return next;
@@ -125,14 +125,17 @@ export class InboxStore {
125
125
  (this.timer as { unref?: () => void }).unref?.();
126
126
  }
127
127
  /**
128
- * Validates what changed (each changed entry, and the small top-level fields when one of them changed), then writes
129
- * a real change at once and a lastSeen-only change at most every LAST_SEEN_WRITE_MS.
128
+ * Validates what changed (each changed entry, each changed top-level field, and of briefOrigins only the items it
129
+ * didn't hold before), then writes a real change at once and a lastSeen-only change at most every LAST_SEEN_WRITE_MS.
130
130
  */
131
- private async save(next: InboxState, changes: Changes): Promise<void> {
131
+ private async save(next: InboxState, changes: Changes, before: InboxState): Promise<void> {
132
132
  const entries = next.entries as Record<string, unknown>;
133
133
  for (const id of changes.items.get("entries") ?? []) entrySchema.parse(entries[id]);
134
134
  const top = [...changes.fields].filter(f => f !== "entries");
135
- if (top.length) topSchema.parse({ ...next, entries: {} });
135
+ for (const f of top) {
136
+ if (f === "briefOrigins") validateOrigins(next.briefOrigins, before.briefOrigins);
137
+ else (inboxStateSchema.shape as Record<string, z.ZodType>)[f]!.parse((next as Record<string, unknown>)[f]);
138
+ }
136
139
  for (const id of changes.items.get("entries") ?? []) deepFreeze(entries[id]);
137
140
  for (const f of top) deepFreeze((next as Record<string, unknown>)[f]);
138
141
  Object.freeze(entries); Object.freeze(next);
@@ -146,13 +149,88 @@ export class InboxStore {
146
149
  const temporary = join(this.directory, `inbox.${randomUUID()}.tmp`);
147
150
  try {
148
151
  const file = await open(temporary, "wx", 0o600);
149
- try { await file.writeFile(JSON.stringify(state)); await file.sync(); } finally { await file.close(); }
152
+ try { await writeParts(file, inboxJsonParts(state)); await file.sync(); } finally { await file.close(); }
150
153
  await rename(temporary, this.path);
151
154
  this.written = { at: this.now() }; this.unsaved = null; this.saved = deepFreeze(state); this.writes++;
152
155
  } finally { await unlink(temporary).catch(() => undefined); }
153
156
  }
154
157
  }
155
- const topSchema = inboxStateSchema.omit({ entries: true }).extend({ entries: z.object({}) });
158
+ /**
159
+ * a-mutation-costs-what-it-changes, for the write: inbox.json is JSON.stringify(state), byte for byte, written as the
160
+ * UTF-8 of each part in order (writev), from a cached buffer per saved (frozen) value: each entry, and each top-level
161
+ * field (briefOrigins is 26 KB). The saved state is deep-frozen and a frozen object never changes, so its bytes stay
162
+ * right for as long as the object lives, and a write encodes only what changed since the last one. Cached strings
163
+ * wouldn't do: joining them back into one 133 KB string per write allocated twice what JSON.stringify did. 2026-11-14
164
+ * (2.0.2-beta.1, live mix): stringifying the whole inbox, ~20 writes a minute, was 26.5 of the inbox's 76 MB per 5 min.
165
+ */
166
+ const frozenBytes = new WeakMap<object, Buffer>();
167
+ const keyBytes = new Map<string, Buffer>();
168
+ const OPEN = Buffer.from("{"), CLOSE = Buffer.from("}"), COMMA = Buffer.from(",");
169
+ function valueBytes(value: unknown): Buffer | undefined {
170
+ const frozen = value !== null && typeof value === "object" && Object.isFrozen(value);
171
+ const cached = frozen ? frozenBytes.get(value) : undefined;
172
+ if (cached) return cached;
173
+ const text = JSON.stringify(value);
174
+ if (text === undefined) return undefined;
175
+ const bytes = Buffer.from(text);
176
+ if (frozen) frozenBytes.set(value, bytes);
177
+ return bytes;
178
+ }
179
+ function memberKey(key: string): Buffer {
180
+ let bytes = keyBytes.get(key);
181
+ if (!bytes) { bytes = Buffer.from(`${JSON.stringify(key)}:`); keyBytes.set(key, bytes); }
182
+ return bytes;
183
+ }
184
+ /** JSON.stringify of a plain object as parts: members in insertion order, undefined, functions and symbols left out. */
185
+ function objectParts(value: Record<string, unknown>, out: Buffer[], member: (v: unknown, out: Buffer[]) => boolean): void {
186
+ out.push(OPEN); let first = true;
187
+ for (const key of Object.keys(value)) {
188
+ const at = out.length;
189
+ if (!first) out.push(COMMA);
190
+ out.push(memberKey(key));
191
+ if (member(value[key], out)) first = false; else out.length = at;
192
+ }
193
+ out.push(CLOSE);
194
+ }
195
+ const pushValue = (v: unknown, out: Buffer[]): boolean => { const b = valueBytes(v); if (b) out.push(b); return !!b; };
196
+ /** inbox.json's bytes, in parts: the same bytes as Buffer.from(JSON.stringify(state)). */
197
+ export function inboxJsonParts(state: InboxState): Buffer[] {
198
+ const out: Buffer[] = [];
199
+ objectParts(state as Record<string, unknown>, out, (v, o) => {
200
+ if (v !== state.entries) return pushValue(v, o);
201
+ objectParts(state.entries as Record<string, unknown>, o, pushValue);
202
+ return true;
203
+ });
204
+ // Agent ids come and go: keep the key cache to the keys this inbox has.
205
+ if (keyBytes.size > 4 * (Object.keys(state.entries).length + 32)) keyBytes.clear();
206
+ return out;
207
+ }
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
+ /**
221
+ * a-mutation-costs-what-it-changes: entries draft per entry; briefOrigins, read whole and replaced whole, drafts as the
222
+ * saved frozen array (2026-11-14: each turn end structuredCloned, shadow-walked and re-validated all 500 origins,
223
+ * 685 KB per turn, 68 MB per 5 min under live's turn rate).
224
+ */
225
+ const INBOX_COLLECTIONS = { entries: { kind: "record" }, briefOrigins: { kind: "frozen" } } as const;
226
+ /** A replaced briefOrigins: its cap, and the items it didn't hold before (the ones it kept were validated when saved). */
227
+ function validateOrigins(next: InboxState["briefOrigins"], before: InboxState["briefOrigins"]): void {
228
+ if (next.length > BRIEF_ORIGINS_MAX) throw new Error(`briefOrigins holds ${next.length} origins; the cap is ${BRIEF_ORIGINS_MAX}.`);
229
+ // A replacement keeps a run of the saved items (an append drops the oldest): match them by identity at their offset,
230
+ // without a lookup structure; anything else is validated.
231
+ const offset = next.length ? before.indexOf(next[0]!) : -1;
232
+ for (let i = 0; i < next.length; i++) if (offset < 0 || next[i] !== before[offset + i]) briefOriginSchema.parse(next[i]);
233
+ }
156
234
 
157
235
  /**
158
236
  * F7: whether a completed turn adds nothing. needs_you kind=done is "nothing for the developer"; and while Paseo
@@ -247,7 +325,6 @@ export function pauseSource(p: GuardPause): { note: string | null; resetsAt: str
247
325
  const at = typeof p.anchorResetsAt === "string" && Number.isFinite(Date.parse(p.anchorResetsAt)) ? new Date(p.anchorResetsAt) : null;
248
326
  return { note, resetsAt: at ? `${String(at.getHours()).padStart(2, "0")}:${String(at.getMinutes()).padStart(2, "0")}` : null };
249
327
  }
250
- const ORIGINS = 500;
251
328
  export type Root = { rootId: string; subagent: AgentInfo | null; delegated: boolean };
252
329
  const DAY = 24 * 3_600_000;
253
330
  /** A cached directory snapshot younger than this answers a list without asking Paseo again. */
@@ -306,7 +383,7 @@ export class Inbox {
306
383
  const appends: { agentId: string; brief: Brief }[] = [];
307
384
  await this.store.mutate(state => {
308
385
  for (const { agentId, event, brief } of events) {
309
- const prev = state.entries[agentId] ?? newEntry(agentId);
386
+ const prev = peek(state.entries[agentId]) ?? newEntry(agentId);
310
387
  const next = reduce(prev, event, at);
311
388
  state.entries[agentId] = next;
312
389
  const steps = [autoBrief(event, prev), brief?.(prev, next, at) ?? null].filter((s): s is BriefEvent => !!s);
@@ -325,7 +402,7 @@ export class Inbox {
325
402
  if (result.brief === e.brief) return;
326
403
  e.brief = result.brief;
327
404
  for (const b of result.appends) appends.push({ agentId, brief: b });
328
- if (event.type === "create" && event.flagged) state.briefOrigins = [...state.briefOrigins, { at, origin: briefOrigin(event.content.source) }].slice(-ORIGINS);
405
+ if (event.type === "create" && event.flagged) state.briefOrigins = [...state.briefOrigins, { at, origin: briefOrigin(event.content.source) }].slice(-BRIEF_ORIGINS_MAX);
329
406
  }
330
407
 
331
408
  private async flush(appends: { agentId: string; brief: Brief }[]): Promise<void> {
@@ -539,14 +616,18 @@ export class Inbox {
539
616
  */
540
617
  async questionsChanged(workspaces: readonly { id: string; questions: Question[] }[]): Promise<void> {
541
618
  const snap = await this.store.snapshot();
542
- const due = Object.entries(snap.entries).filter(([, e]) => e?.brief?.state === "open" && e.brief.questionIds.length && e.brief.workspaceId);
619
+ const eventFor = (b: Brief | null | undefined) => {
620
+ const w = b?.workspaceId ? workspaces.find(w => w.id === b.workspaceId) : undefined;
621
+ return b && w ? briefQuestionsEvent(b, w.questions) : null;
622
+ };
623
+ // a-mutation-costs-what-it-changes: decide on the frozen snapshot, and draft the inbox only when a brief's questions
624
+ // moved (2026-11-14: half the turns called this, and every call changed nothing).
625
+ const due = Object.entries(snap.entries).filter(([, e]) => e?.brief?.state === "open" && e.brief.questionIds.length && e.brief.workspaceId && eventFor(e.brief));
543
626
  if (!due.length) return;
544
627
  const appends: { agentId: string; brief: Brief }[] = [];
545
628
  await this.store.mutate(state => {
546
629
  for (const [agentId] of due) {
547
- const b = state.entries[agentId]?.brief;
548
- const w = b?.workspaceId ? workspaces.find(w => w.id === b.workspaceId) : undefined;
549
- const event = b && w ? briefQuestionsEvent(b, w.questions) : null;
630
+ const event = eventFor(state.entries[agentId]?.brief);
550
631
  if (event) this.step(state, agentId, event, this.iso(), appends);
551
632
  }
552
633
  });
@@ -889,7 +970,7 @@ export class Inbox {
889
970
  await this.store.mutate(state => {
890
971
  const each = (event: (id: string) => InboxEvent) => {
891
972
  for (const agentId of input.agentIds ?? []) {
892
- const prev = state.entries[agentId] ?? newEntry(agentId);
973
+ const prev = peek(state.entries[agentId]) ?? newEntry(agentId);
893
974
  const ev = event(agentId);
894
975
  try { state.entries[agentId] = reduce(prev, ev, at); results.push({ agentId, ok: true, cameBack: false }); }
895
976
  catch (error) { if (!(error instanceof StaleSignOff)) throw error; results.push({ agentId, ok: false, cameBack: true }); continue; }
@@ -55,6 +55,8 @@ export async function hasFixPr(claudeHome = process.env.CLAUDE_CONFIG_DIR ?? joi
55
55
  }
56
56
 
57
57
  type Detected = { at: number; workflow: PrWorkflow; reason: string; path: string | null };
58
+ /** How long one detect pass's checkout map is reused: a pass over every repository takes well under this. */
59
+ export const PATHS_PASS_MS = 30_000;
58
60
  export class PrWorkflowStore {
59
61
  private tail: Promise<unknown> = Promise.resolve();
60
62
  private cached: PrWorkflowConfig | null = null;
@@ -65,6 +67,17 @@ export class PrWorkflowStore {
65
67
  * working directories of tracked workspaces with PRs there (a repository often has no project registered). Set by the server.
66
68
  */
67
69
  paths: () => Promise<Map<string, string[]>> = async () => new Map();
70
+ /**
71
+ * One `paths()` per detect pass: repositories detected together (an observe loop, `warm`) share one map, so the
72
+ * pass reads Paseo's project list once (concurrent-readers-share-one-request). Kept briefly after it settles.
73
+ */
74
+ private pathsRead: { at: number; value: Promise<Map<string, string[]>> } | null = null;
75
+ private passPaths(): Promise<Map<string, string[]>> {
76
+ if (this.pathsRead && this.now() - this.pathsRead.at < PATHS_PASS_MS) return this.pathsRead.value;
77
+ const value = this.paths(); this.pathsRead = { at: this.now(), value };
78
+ void value.catch(() => { if (this.pathsRead?.value === value) this.pathsRead = null; });
79
+ return value;
80
+ }
68
81
  /** Called after every save, so derived files (scopes.json) can be rewritten. */
69
82
  onChanged: () => void = () => undefined;
70
83
  constructor(readonly directory: string, private probe: Probe = fsProbe(), private now = Date.now, private ttl = 600_000) {}
@@ -127,7 +140,7 @@ export class PrWorkflowStore {
127
140
  const hit = this.detected.get(key);
128
141
  if (!fresh && hit && this.now() - hit.at < this.ttl) return hit;
129
142
  const machine = await this.machineState(freshMachine);
130
- const candidates = [...new Set((await this.paths()).get(key) ?? [])];
143
+ const candidates = [...new Set((await this.passPaths()).get(key) ?? [])];
131
144
  let path = candidates[0] ?? null;
132
145
  const detection: Detection = { gtInstalled: machine.gtInstalled, signedIn: machine.signedIn, path, initialised: false };
133
146
  // File reads only, stopping at the first checkout set up for Graphite.
package/shared/inbox.ts CHANGED
@@ -67,6 +67,9 @@ export const outboxSchema = z.object({
67
67
  attempts: z.number().int().default(0), state: z.enum(["sending", "failed"]).default("sending"), error: z.string().nullable().default(null),
68
68
  });
69
69
  export type OutboxEntry = z.infer<typeof outboxSchema>;
70
+ /** The newest flagged briefs' origins kept (InboxState.briefOrigins). */
71
+ export const BRIEF_ORIGINS_MAX = 500;
72
+ export const briefOriginSchema = z.object({ at: isoSchema, origin: z.enum(["tool", "structured", "extraction", "fallback"]) });
70
73
  export const inboxStateSchema = z.object({
71
74
  version: z.literal(1),
72
75
  entries: z.record(z.string(), entrySchema).default({}),
@@ -98,9 +101,15 @@ export const inboxStateSchema = z.object({
98
101
  /** One-time repairs applied to this store (additive; `version` stays 1 so older builds still read it). */
99
102
  revision: z.number().int().default(0),
100
103
  /** Where each flagged turn's brief came from, newest last, for the adoption share (R2). Capped. */
101
- briefOrigins: z.array(z.object({ at: isoSchema, origin: z.enum(["tool", "structured", "extraction", "fallback"]) })).default([]),
104
+ /**
105
+ * Where each flagged brief's content came from, newest last, for the brief share (briefShare). Only ever read whole and
106
+ * replaced whole (InboxStore drafts it as cow kind "frozen"), so it is readonly: a reader never changes it in place.
107
+ */
108
+ briefOrigins: z.array(briefOriginSchema).max(BRIEF_ORIGINS_MAX).default([]),
102
109
  });
103
- export type InboxState = z.infer<typeof inboxStateSchema>;
110
+ export type BriefOrigin = z.infer<typeof briefOriginSchema>;
111
+ /** briefOrigins is readonly for every reader (the store deep-freezes it; see its schema). */
112
+ export type InboxState = Omit<z.infer<typeof inboxStateSchema>, "briefOrigins"> & { briefOrigins: readonly BriefOrigin[] };
104
113
  export const emptyInbox = (): InboxState => inboxStateSchema.parse({ version: 1 });
105
114
 
106
115
  export type InboxEvent =