paseo-follow-up 2.0.1 → 2.0.2-beta.1

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.
Files changed (46) hide show
  1. package/CHANGELOG.md +8 -43
  2. package/client/brief.tsx +9 -4
  3. package/client/home.tsx +11 -3
  4. package/client/linked.tsx +1 -1
  5. package/client/live-copies.ts +19 -1
  6. package/client/live.tsx +16 -12
  7. package/client/merge-button.tsx +1 -1
  8. package/client/needs-you.tsx +1 -1
  9. package/client/pill.tsx +13 -9
  10. package/client/questions.tsx +8 -7
  11. package/client/spec.tsx +1 -1
  12. package/client/workspace-data.ts +36 -19
  13. package/package.json +2 -1
  14. package/server/cow.ts +62 -13
  15. package/server/daemon.ts +18 -33
  16. package/server/deployments.ts +55 -20
  17. package/server/directory.ts +29 -10
  18. package/server/feeds.ts +3 -2
  19. package/server/inbox.ts +37 -18
  20. package/server/list-cache.ts +21 -10
  21. package/server/pr-workflow.ts +14 -1
  22. package/shared/activity.ts +1 -1
  23. package/shared/attention.ts +8 -7
  24. package/shared/brief.ts +5 -5
  25. package/shared/contracts.ts +3 -2
  26. package/shared/follow-up.ts +2 -2
  27. package/shared/home.ts +4 -3
  28. package/shared/inbox.ts +11 -2
  29. package/shared/list.ts +86 -0
  30. package/shared/merge-click.ts +1 -1
  31. package/shared/model.ts +8 -7
  32. package/shared/overseer.ts +3 -3
  33. package/shared/poll.ts +1 -1
  34. package/shared/pr-actions.ts +7 -6
  35. package/shared/presentation.ts +6 -5
  36. package/shared/questions.ts +9 -7
  37. package/shared/reviewers.ts +1 -1
  38. package/shared/row-menu.ts +1 -1
  39. package/shared/search.ts +3 -3
  40. package/shared/send-decision.ts +2 -1
  41. package/shared/sending.ts +1 -1
  42. package/shared/status-invariants.ts +1 -1
  43. package/shared/status.ts +1 -1
  44. package/shared/task-rows.ts +4 -2
  45. package/shared/task-status.ts +2 -1
  46. package/shared/task-trigger.ts +1 -1
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]));
package/server/daemon.ts CHANGED
@@ -7,7 +7,6 @@ import { homedir } from "node:os";
7
7
  import { join } from "node:path";
8
8
  import { readSharedJson } from "./shared-file";
9
9
  import { createRequire } from "node:module";
10
- import { TICK_MS } from "../shared/poll";
11
10
  import type { Workspace, Batch } from "../shared/model";
12
11
  import type { Gateway, Runtime } from "./engine";
13
12
  import type { State } from "../shared/model";
@@ -130,44 +129,32 @@ export function withDaemon<T>(work: (client: Daemon) => Promise<T>): Promise<T>
130
129
  * opened a WebSocket per workspace per tick through withDaemon (96 a minute live, each with its own hello and status).
131
130
  * It is in `clients`, so closeConnections closes it within the stop's deadline, and nothing opens after stop.
132
131
  *
133
- * The connection outlives the gap between ticks (a-running-worker-holds-one-daemon-connection): it closes only after
134
- * SHARED_CLIENT_IDLE_MS unused, which is the engine's TICK_MS plus a named margin, so a worker that keeps ticking
135
- * holds one connection. 2026-11-13 live: with a 5 s idle close and a 60 s replacement, every 15 s tick opened a new
136
- * WebSocket (the worker said hello 39 times in 12 min, each with its own handshake, status and buffers). A dropped
137
- * connection is still retired at once, and SHARED_CLIENT_MAX_MS replaces a long-lived one now and then.
132
+ * A running worker holds it (a-running-worker-holds-one-daemon-connection): nothing closes it for being unused. It
133
+ * closes on stop, when it drops (retired at once, the next call opens a fresh one), and SHARED_CLIENT_MAX_MS replaces a
134
+ * long-lived one. No idle bound is safe: the engine's loop waits TICK_MS after a tick ends, a tick's daemon calls come
135
+ * before its GitHub reads, and a paused tick (the governor) calls the daemon not at all. 2026-11-13 live (2.0.1-beta.7):
136
+ * with a TICK_MS + 10 s idle close the worker closed and reopened it every 80-130 s (22 hellos in 30 min); before that,
137
+ * a 5 s idle close opened one per tick (39 hellos in 12 min).
138
138
  */
139
- /** How far past one tick interval the shared connection stays open unused: a slow tick still finds it. */
140
- export const SHARED_CLIENT_MARGIN_MS = 10_000;
141
- export const SHARED_CLIENT_IDLE_MS = TICK_MS + SHARED_CLIENT_MARGIN_MS;
142
139
  export const SHARED_CLIENT_MAX_MS = 30 * 60_000;
143
- export type SharedConnect = (<T>(work: (client: Daemon) => Promise<T>) => Promise<T>) & { idle(): Promise<void> };
144
- type Shared = { client: Promise<Daemon>; opened: number; users: number; lastUsed: number; retired: boolean; timer: ReturnType<typeof setTimeout> | null };
145
- export function sharedDaemon(open: () => Promise<Daemon> = openDaemon, o: { idleMs?: number; maxMs?: number; now?: () => number } = {}): SharedConnect {
146
- const idleMs = o.idleMs ?? SHARED_CLIENT_IDLE_MS, maxMs = o.maxMs ?? SHARED_CLIENT_MAX_MS, now = o.now ?? Date.now;
140
+ export type SharedConnect = <T>(work: (client: Daemon) => Promise<T>) => Promise<T>;
141
+ type Shared = { client: Promise<Daemon>; opened: number; users: number; retired: boolean };
142
+ export function sharedDaemon(open: () => Promise<Daemon> = openDaemon, o: { maxMs?: number; now?: () => number } = {}): SharedConnect {
143
+ const maxMs = o.maxMs ?? SHARED_CLIENT_MAX_MS, now = o.now ?? Date.now;
147
144
  let current: Shared | null = null;
148
145
  const close = async (entry: Shared) => {
149
146
  if (current === entry) current = null;
150
- if (entry.timer) { clearTimeout(entry.timer); entry.timer = null; }
151
147
  const client = await entry.client.catch(() => null);
152
148
  if (client) { clients.delete(client); await client.close().catch(() => undefined); }
153
149
  };
154
- const settle = (entry: Shared) => { if (entry.users === 0 && (entry.retired || now() - entry.lastUsed >= idleMs)) void close(entry); };
155
- // One idle timer per connection, re-armed for what is left of the idle bound (not a timer per call).
156
- const arm = (entry: Shared) => {
157
- if (entry.timer) return;
158
- entry.timer = setTimeout(() => {
159
- entry.timer = null;
160
- if (current !== entry && !entry.retired) return;
161
- if (entry.users === 0 && now() - entry.lastUsed < idleMs) arm(entry); else settle(entry);
162
- }, Math.max(0, idleMs - (now() - entry.lastUsed)) || idleMs);
163
- (entry.timer as { unref?: () => void }).unref?.();
164
- };
165
- const connect = (async <T>(work: (client: Daemon) => Promise<T>): Promise<T> => {
150
+ // A retired connection closes once its last call is done; the current one stays open.
151
+ const settle = (entry: Shared) => { if (entry.users === 0 && entry.retired) void close(entry); };
152
+ return async <T>(work: (client: Daemon) => Promise<T>): Promise<T> => {
166
153
  if (stopped) throw new Error("Follow-up is stopping");
167
154
  if (current && now() - current.opened >= maxMs) { current.retired = true; const old = current; current = null; settle(old); }
168
155
  if (!current) {
169
156
  const client = open().then(c => { if (stopped) { void c.close().catch(() => undefined); throw new Error("Follow-up is stopping"); } clients.add(c); return c; });
170
- const entry: Shared = { client, opened: now(), users: 0, lastUsed: now(), retired: false, timer: null };
157
+ const entry: Shared = { client, opened: now(), users: 0, retired: false };
171
158
  current = entry;
172
159
  void client.catch(() => { if (current === entry) current = null; });
173
160
  }
@@ -179,16 +166,14 @@ export function sharedDaemon(open: () => Promise<Daemon> = openDaemon, o: { idle
179
166
  catch (error) {
180
167
  // A dropped connection isn't reused: the next call opens a fresh one.
181
168
  const status = (client as unknown as { connectionState?: { status?: string } }).connectionState?.status;
182
- if (status !== undefined && status !== "connected") entry.retired = true;
169
+ if (status !== undefined && status !== "connected") { entry.retired = true; if (current === entry) current = null; }
183
170
  throw error;
184
171
  }
185
172
  } finally {
186
- entry.users--; entry.lastUsed = now();
187
- if (entry.users === 0) { if (entry.retired) settle(entry); else arm(entry); }
173
+ entry.users--;
174
+ settle(entry);
188
175
  }
189
- }) as SharedConnect;
190
- connect.idle = async () => { if (current) { const entry = current; if (entry.users === 0 && now() - entry.lastUsed >= idleMs) await close(entry); } };
191
- return connect;
176
+ };
192
177
  }
193
178
  async function openDaemon(): Promise<Daemon> {
194
179
  const module = require(["@getpaseo", "client", "internal", "daemon-client"].join("/")) as Module;
@@ -11,17 +11,22 @@ type Run = (command: string, args: string[]) => Promise<string>;
11
11
  type Fleet = { commits: string[]; evidence: string; observedAt: string };
12
12
  /** The deploy check's configuration for a repository (host settings, pr-workflow.json); undefined: no deploy check. */
13
13
  export type DeployConfigFor = (repo: string) => DeployConfig | undefined;
14
+ /** How long one `gcloud auth print-access-token` is reused: under the token's hour, with margin. */
15
+ export const TOKEN_MS = 2_700_000;
16
+ /** Every registry and Cloud Run read is aborted after this long. */
17
+ export const READ_TIMEOUT_MS = 8_000;
18
+ const IMAGE_ACCEPT = "application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json";
14
19
  const escape = (text: string) => text.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
15
20
 
16
21
  /** Messages this probe throws itself. Anything else (gcloud, gh, fetch) is summarized so no transport detail leaks. */
17
- const OWN_REASONS = new Set(["Deployment image unavailable", "Deployment image metadata exceeds the read limit", "Serving image must have an immutable production digest", "Serving image config unavailable", "Serving source revision is unknown", "Production service catalog incomplete", "Production traffic is not ready", "Serving revision unavailable", "Serving revision is not ready"]);
22
+ const OWN_REASONS = new Set(["Deployment image unavailable", "Deployment image metadata exceeds the read limit", "Serving image must have an immutable production digest", "Serving image config unavailable", "Serving source revision is unknown", "Production service catalog incomplete", "Production traffic is not ready", "Serving revision unavailable", "Serving revision is not ready", "Production services unavailable", "Production services exceed the read limit", "Serving revision exceeds the read limit"]);
18
23
  export function probeReason(error: unknown): string {
19
24
  const message = error instanceof Error ? error.message : "";
20
25
  if (OWN_REASONS.has(message)) return message;
21
26
  const command = (error as { cmd?: unknown; path?: unknown } | null)?.cmd ?? (error as { path?: unknown } | null)?.path;
22
27
  if (typeof command === "string" && /^(gcloud|gh)\b/.test(command)) return `${command.split(" ")[0]} call failed`;
23
28
  if (error instanceof SyntaxError) return "unreadable response";
24
- if (error instanceof Error && error.name === "AbortError") return "registry timed out";
29
+ if (error instanceof Error && error.name === "AbortError") return "read timed out";
25
30
  return "lookup failed";
26
31
  }
27
32
 
@@ -35,7 +40,10 @@ export class Deployments {
35
40
  private ancestry = new Map<string, Promise<boolean>>();
36
41
  private token: { value: string; until: number } | null = null;
37
42
  constructor(
38
- /** gcloud only: GitHub reads go through `api`, in process (worker-reads-github-in-process). */
43
+ /**
44
+ * gcloud only, and only for the access token (cached TOKEN_MS): the registry and Cloud Run are read in process with
45
+ * it (cloud-run-reads-in-process). GitHub reads go through `api`, in process (worker-reads-github-in-process).
46
+ */
39
47
  private run: Run = async (command, args) => (await exec(command, args, { env: process.env, timeout: 25_000, maxBuffer: 4 * 1024 * 1024 })).stdout,
40
48
  private request: typeof fetch = fetch,
41
49
  private now = Date.now,
@@ -45,17 +53,35 @@ export class Deployments {
45
53
  ) {}
46
54
  /** Whether `repo` has a deploy check on this machine. */
47
55
  configured(repo: string): boolean { return !!this.configFor(repo); }
48
- private async json(url: string): Promise<Node> {
49
- if (!this.token || this.token.until <= this.now()) this.token = { value: (await this.run("gcloud", ["auth", "print-access-token"])).trim(), until: this.now() + 2_700_000 };
50
- const abort = new AbortController(); const timeout = setTimeout(() => abort.abort(), 8_000);
51
- let body: string;
52
- try {
53
- const response = await this.request(url, { headers: { Authorization: `Bearer ${this.token.value}`, Accept: "application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json" }, redirect: "error", signal: abort.signal });
54
- if (!response.ok) { this.token = null; throw new Error("Deployment image unavailable"); }
55
- body = await response.text();
56
- } finally { clearTimeout(timeout); }
57
- if (body.length > 1_000_000) throw new Error("Deployment image metadata exceeds the read limit");
58
- return JSON.parse(body);
56
+ private async accessToken(): Promise<string> {
57
+ if (!this.token || this.token.until <= this.now()) this.token = { value: (await this.run("gcloud", ["auth", "print-access-token"])).trim(), until: this.now() + TOKEN_MS };
58
+ return this.token.value;
59
+ }
60
+ /**
61
+ * One authorized JSON read (the registry and Cloud Run), each under READ_TIMEOUT_MS. A 401/403 drops the cached
62
+ * token and retries once with a fresh one; any other failure throws `failure`, and a body over `limit` throws
63
+ * `tooLarge`: each caller names what it read, with no transport detail.
64
+ */
65
+ private async json(url: string, failure: string, o: { tooLarge: string; accept?: string; limit?: number }): Promise<Node> {
66
+ for (let attempt = 0; ; attempt++) {
67
+ const token = await this.accessToken();
68
+ const abort = new AbortController(); const timeout = setTimeout(() => abort.abort(), READ_TIMEOUT_MS);
69
+ let body: string;
70
+ try {
71
+ const response = await this.request(url, { headers: { Authorization: `Bearer ${token}`, ...(o.accept ? { Accept: o.accept } : {}) }, redirect: "error", signal: abort.signal });
72
+ if (response.status === 401 || response.status === 403) { this.token = null; if (attempt === 0) continue; }
73
+ if (!response.ok) throw new Error(failure);
74
+ body = await response.text();
75
+ } finally { clearTimeout(timeout); }
76
+ if (body.length > (o.limit ?? 1_000_000)) throw new Error(o.tooLarge);
77
+ return JSON.parse(body);
78
+ }
79
+ }
80
+ /** Cloud Run's v1 (Knative) API: the global endpoint lists every region; a revision is read from its region's. */
81
+ private runUrl(region: string | null, path: string): string {
82
+ // FOLLOW_UP_CLOUD_RUN_API points harness runs (scripts/poll-cost.mjs) at a fake Cloud Run.
83
+ const fake = process.env.FOLLOW_UP_CLOUD_RUN_API?.replace(/\/$/, "");
84
+ return `${fake || (region ? `https://${region}-run.googleapis.com` : "https://run.googleapis.com")}/apis/serving.knative.dev/v1/${path}`;
59
85
  }
60
86
  private imageCommit(image: string, deploy: DeployConfig): Promise<string> {
61
87
  const cached = this.images.get(image); if (cached) return cached;
@@ -64,9 +90,9 @@ export class Deployments {
64
90
  if (!match) throw new Error("Serving image must have an immutable production digest");
65
91
  // FOLLOW_UP_DEPLOY_REGISTRY points harness runs (scripts/poll-cost.mjs) at a fake registry.
66
92
  const base = `${(process.env.FOLLOW_UP_DEPLOY_REGISTRY || `https://${deploy.registry}`).replace(/\/$/, "")}/v2/${match[1]}`;
67
- const manifest = await this.json(`${base}/manifests/${match[2]}`);
93
+ const manifest = await this.json(`${base}/manifests/${match[2]}`, "Deployment image unavailable", { tooLarge: "Deployment image metadata exceeds the read limit", accept: IMAGE_ACCEPT });
68
94
  if (!/^sha256:[a-f0-9]{64}$/.test(manifest.config?.digest)) throw new Error("Serving image config unavailable");
69
- const config = (await this.json(`${base}/blobs/${manifest.config.digest}`)).config;
95
+ const config = (await this.json(`${base}/blobs/${manifest.config.digest}`, "Deployment image unavailable", { tooLarge: "Deployment image metadata exceeds the read limit", accept: IMAGE_ACCEPT })).config;
70
96
  const revision = config?.Labels?.["org.opencontainers.image.revision"];
71
97
  const baked = (config?.Env ?? []).find((v: string) => (deploy.buildShaEnv && v.startsWith(`${deploy.buildShaEnv}=`)) || v.startsWith("GIT_SHA="))?.split("=")[1];
72
98
  if (!sha.test(revision ?? baked ?? "") || (revision && baked && revision !== baked)) throw new Error("Serving source revision is unknown");
@@ -77,13 +103,14 @@ export class Deployments {
77
103
  }
78
104
  /**
79
105
  * A Cloud Run revision is immutable: its image (so its commit) never changes. Once a revision has been read ready,
80
- * its commit is reused, so a fleet read costs one `gcloud run services list` instead of one call per serving
81
- * revision as well (cpu-load REPORT.md §5: 6 gcloud calls a minute). Failures and unready revisions aren't cached.
106
+ * its commit is reused, so a fleet read costs one services list instead of one read per serving revision as well
107
+ * (cpu-load REPORT.md §5: 6 gcloud calls a minute). Failures and unready revisions aren't cached.
82
108
  */
83
109
  private revisionCommit(name: string, region: string, config: DeployConfig): Promise<string> {
84
110
  const key = `${config.gcpProject}/${region}/${name}`; const cached = this.revisions.get(key); if (cached) return cached;
85
111
  const work = (async () => {
86
- const revision = JSON.parse(await this.run("gcloud", ["run", "revisions", "describe", name, "--project", config.gcpProject, "--region", region, "--format=json(spec.containers,status.conditions)"]));
112
+ if (!/^[a-z0-9-]+$/.test(region)) throw new Error("Serving revision unavailable");
113
+ const revision = await this.json(this.runUrl(region, `namespaces/${encodeURIComponent(config.gcpProject)}/revisions/${encodeURIComponent(name)}`), "Serving revision unavailable", { tooLarge: "Serving revision exceeds the read limit" });
87
114
  if (!revision.status?.conditions?.some((c: Node) => c.type === "Ready" && c.status === "True")) throw new Error("Serving revision is not ready");
88
115
  const image = revision.spec?.containers?.find((c: Node) => c.name === "app")?.image;
89
116
  return this.imageCommit(image ?? "", config);
@@ -92,7 +119,15 @@ export class Deployments {
92
119
  this.revisions.set(key, work); void work.catch(() => this.revisions.delete(key)); return work;
93
120
  }
94
121
  private async readFleet(config: DeployConfig): Promise<Fleet> {
95
- const services: Node[] = JSON.parse(await this.run("gcloud", ["run", "services", "list", "--project", config.gcpProject, "--filter", `metadata.labels.${config.serviceLabel}`, "--format=json(metadata.name,metadata.labels,status.traffic,status.conditions)"]));
122
+ // One list (paged by `continue`), filtered by the configured label on the server, as `gcloud run services list
123
+ // --filter` was. 2026-11-13 live: that list spawned gcloud ~0.8 times a minute, ~1 s CPU and ~97 MB each.
124
+ const services: Node[] = []; let next = "";
125
+ for (let page = 0; page < 20; page++) {
126
+ const list = await this.json(this.runUrl(null, `namespaces/${encodeURIComponent(config.gcpProject)}/services?labelSelector=${encodeURIComponent(config.serviceLabel)}${next ? `&continue=${encodeURIComponent(next)}` : ""}`), "Production services unavailable", { tooLarge: "Production services exceed the read limit", limit: 4 * 1024 * 1024 });
127
+ services.push(...(Array.isArray(list.items) ? list.items : []));
128
+ next = typeof list.metadata?.continue === "string" ? list.metadata.continue : "";
129
+ if (!next) break;
130
+ }
96
131
  const named = (s: Node, role: string) => typeof s.metadata?.name === "string" && s.metadata.name.startsWith(`${config.servicePrefix}${role}-`);
97
132
  if (!Array.isArray(services) || config.roles.some(role => !services.some(s => named(s, role)))) throw new Error("Production service catalog incomplete");
98
133
  const targets = services.filter(s => config.roles.some(role => named(s, role)));
@@ -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/feeds.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { ListCache } from "./list-cache";
2
- import type { State, Workspace } from "../shared/model";
2
+ import type { State } from "../shared/model";
3
+ import type { ListEntry } from "../shared/list";
3
4
 
4
5
  /**
5
6
  * Pushes instead of client polling (Paseo 0.16 subscriptions, plan item 6). A feed is one shared serve per topic: a
@@ -53,7 +54,7 @@ export class ValueFeed<E> {
53
54
  }
54
55
  }
55
56
 
56
- export type WorkspacesEvent = { revision: number; full: boolean; workspaces: Workspace[]; removed: string[]; error: string | null };
57
+ export type WorkspacesEvent = { revision: number; full: boolean; workspaces: ListEntry[]; removed: string[]; error: string | null };
57
58
 
58
59
  /**
59
60
  * follow.list as a feed: each subscriber holds a revision, and a change sends it only the workspaces changed since,
package/server/inbox.ts CHANGED
@@ -6,9 +6,9 @@ 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);
@@ -152,7 +155,20 @@ export class InboxStore {
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: entries draft per entry; briefOrigins, read whole and replaced whole, drafts as the
160
+ * saved frozen array (2026-11-14: each turn end structuredCloned, shadow-walked and re-validated all 500 origins,
161
+ * 685 KB per turn, 68 MB per 5 min under live's turn rate).
162
+ */
163
+ const INBOX_COLLECTIONS = { entries: { kind: "record" }, briefOrigins: { kind: "frozen" } } as const;
164
+ /** A replaced briefOrigins: its cap, and the items it didn't hold before (the ones it kept were validated when saved). */
165
+ function validateOrigins(next: InboxState["briefOrigins"], before: InboxState["briefOrigins"]): void {
166
+ if (next.length > BRIEF_ORIGINS_MAX) throw new Error(`briefOrigins holds ${next.length} origins; the cap is ${BRIEF_ORIGINS_MAX}.`);
167
+ // A replacement keeps a run of the saved items (an append drops the oldest): match them by identity at their offset,
168
+ // without a lookup structure; anything else is validated.
169
+ const offset = next.length ? before.indexOf(next[0]!) : -1;
170
+ for (let i = 0; i < next.length; i++) if (offset < 0 || next[i] !== before[offset + i]) briefOriginSchema.parse(next[i]);
171
+ }
156
172
 
157
173
  /**
158
174
  * F7: whether a completed turn adds nothing. needs_you kind=done is "nothing for the developer"; and while Paseo
@@ -247,7 +263,6 @@ export function pauseSource(p: GuardPause): { note: string | null; resetsAt: str
247
263
  const at = typeof p.anchorResetsAt === "string" && Number.isFinite(Date.parse(p.anchorResetsAt)) ? new Date(p.anchorResetsAt) : null;
248
264
  return { note, resetsAt: at ? `${String(at.getHours()).padStart(2, "0")}:${String(at.getMinutes()).padStart(2, "0")}` : null };
249
265
  }
250
- const ORIGINS = 500;
251
266
  export type Root = { rootId: string; subagent: AgentInfo | null; delegated: boolean };
252
267
  const DAY = 24 * 3_600_000;
253
268
  /** A cached directory snapshot younger than this answers a list without asking Paseo again. */
@@ -306,7 +321,7 @@ export class Inbox {
306
321
  const appends: { agentId: string; brief: Brief }[] = [];
307
322
  await this.store.mutate(state => {
308
323
  for (const { agentId, event, brief } of events) {
309
- const prev = state.entries[agentId] ?? newEntry(agentId);
324
+ const prev = peek(state.entries[agentId]) ?? newEntry(agentId);
310
325
  const next = reduce(prev, event, at);
311
326
  state.entries[agentId] = next;
312
327
  const steps = [autoBrief(event, prev), brief?.(prev, next, at) ?? null].filter((s): s is BriefEvent => !!s);
@@ -325,7 +340,7 @@ export class Inbox {
325
340
  if (result.brief === e.brief) return;
326
341
  e.brief = result.brief;
327
342
  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);
343
+ if (event.type === "create" && event.flagged) state.briefOrigins = [...state.briefOrigins, { at, origin: briefOrigin(event.content.source) }].slice(-BRIEF_ORIGINS_MAX);
329
344
  }
330
345
 
331
346
  private async flush(appends: { agentId: string; brief: Brief }[]): Promise<void> {
@@ -539,14 +554,18 @@ export class Inbox {
539
554
  */
540
555
  async questionsChanged(workspaces: readonly { id: string; questions: Question[] }[]): Promise<void> {
541
556
  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);
557
+ const eventFor = (b: Brief | null | undefined) => {
558
+ const w = b?.workspaceId ? workspaces.find(w => w.id === b.workspaceId) : undefined;
559
+ return b && w ? briefQuestionsEvent(b, w.questions) : null;
560
+ };
561
+ // a-mutation-costs-what-it-changes: decide on the frozen snapshot, and draft the inbox only when a brief's questions
562
+ // moved (2026-11-14: half the turns called this, and every call changed nothing).
563
+ const due = Object.entries(snap.entries).filter(([, e]) => e?.brief?.state === "open" && e.brief.questionIds.length && e.brief.workspaceId && eventFor(e.brief));
543
564
  if (!due.length) return;
544
565
  const appends: { agentId: string; brief: Brief }[] = [];
545
566
  await this.store.mutate(state => {
546
567
  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;
568
+ const event = eventFor(state.entries[agentId]?.brief);
550
569
  if (event) this.step(state, agentId, event, this.iso(), appends);
551
570
  }
552
571
  });
@@ -889,7 +908,7 @@ export class Inbox {
889
908
  await this.store.mutate(state => {
890
909
  const each = (event: (id: string) => InboxEvent) => {
891
910
  for (const agentId of input.agentIds ?? []) {
892
- const prev = state.entries[agentId] ?? newEntry(agentId);
911
+ const prev = peek(state.entries[agentId]) ?? newEntry(agentId);
893
912
  const ev = event(agentId);
894
913
  try { state.entries[agentId] = reduce(prev, ev, at); results.push({ agentId, ok: true, cameBack: false }); }
895
914
  catch (error) { if (!(error instanceof StaleSignOff)) throw error; results.push({ agentId, ok: false, cameBack: true }); continue; }