paseo-follow-up 2.0.2-beta.1 → 2.0.2-beta.3
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/OVERVIEW.md +1 -1
- package/index.server.ts +13 -6
- package/package.json +1 -1
- package/server/agent-hook.mjs +24 -4
- package/server/agent-settings.ts +12 -16
- package/server/hook-source.ts +24 -4
- package/server/inbox.ts +69 -28
- package/server/overseer.ts +38 -9
- package/server/pr-workflow.ts +10 -14
- package/server/reviewer-config.ts +10 -15
- package/server/store.ts +29 -1
- package/server/teardown.ts +3 -0
- package/server/write-behind.ts +144 -0
- package/shared/overseer.ts +3 -1
package/OVERVIEW.md
CHANGED
|
@@ -44,7 +44,7 @@ The Needs-you inbox (beta) keeps one flag per root agent in `plugin-data/follow-
|
|
|
44
44
|
|
|
45
45
|
The brief (beta) is stored on the agent's inbox entry and appended to its timeline as a Follow-up row; re-appending replaces that row, and the restart check ignores the `updatedAt` change the append causes because it never reads `updatedAt`. To build a brief Follow-up reads only what it already has: the agent's `needs_you` call, the permission request's title, the failed turn's error message, Session Guard's note and reset time for a paused agent, and its own PR state. It does not read or quote the agent's reply. While the inbox is on, every root Paseo agent on Claude Code or Codex gets Follow-up's MCP bridge with the `needs_you` tool only (tracked main agents keep their full set), and `plugin-data/follow-up/brief.json` records whether the inbox and the nudge are on and which agents have a permission prompt showing. Clicking an option or Retry sends one message as you; it is logged in the delivery ledger as yours, so it clears the flag. The Stop hook, part of the same reversible provider hooks Follow-up already installs, now also runs for those root Claude Code sessions: if the turn ended without `needs_you`, it blocks the stop once with a one-line request to call it, records that it did in `hook-state`, and never blocks the same turn again. It reads `brief.json`, its own per-turn marker and the time of the agent's last `needs_you` call, and nothing else. Turn it off with *Ask agents to state what they need*; turning the inbox off stops it too.
|
|
46
46
|
|
|
47
|
-
The Overseer (beta) is one Claude agent in a Follow-up workspace under `plugin-data/follow-up/overseer-home`, labelled `follow-up.overseer=1` and created only when you click Start. Its id is kept in `plugin-data/follow-up/overseer.json`. Discovery, tracking, auto-send and Needs you skip its workspace. At the start of each of its turns, the provider hook adds a digest from `plugin-data/follow-up/overseer-digest.json` and records what it showed in `hook-state/overseer-seen-<agent>.json`. The worker builds that file from Paseo's workspace list (metadata only, at most once a minute) and Follow-up's own state
|
|
47
|
+
The Overseer (beta) is one Claude agent in a Follow-up workspace under `plugin-data/follow-up/overseer-home`, labelled `follow-up.overseer=1` and created only when you click Start. Its id is kept in `plugin-data/follow-up/overseer.json`. Discovery, tracking, auto-send and Needs you skip its workspace. At the start of each of its turns, the provider hook adds a digest from `plugin-data/follow-up/overseer-digest.json` and records what it showed in `hook-state/overseer-seen-<agent>.json`. The worker builds that file when the Overseer's turn starts (and every 10 minutes as a backstop), from Paseo's workspace list (metadata only, at most once a minute) and Follow-up's own state; the hook waits up to 1.5 s for that turn's build. It skips the build while the resource governor pauses background work. Its tools are `workstreams`, `agent_digest`, `route_candidates`, `send_to_agent` and `start_workspace`. For an agent that isn't loaded, `agent_digest` reads the provider's transcript on disk, read-only (Claude Code's `projects/<cwd>/<session>.jsonl`, Codex's `sessions/**/rollout-*-<thread>.jsonl`; only the last 512 KB, and never the credentials in Paseo's agent record). Without a transcript it uses Follow-up's goal and PR titles. It never reads that agent's timeline. `send_to_agent` writes your words to the delivery ledger first: as yours only when they answer that agent's open ask, otherwise as Follow-up's. It wakes a resting agent only because you asked for it. `start_workspace` runs only after your approval, through a dry run and confirm. The Overseer can't merge, archive or post anywhere.
|
|
48
48
|
The Summary keeps its overviews in `plugin-data/follow-up/about.json` (gist, overview, linked rows, when and from what; never raw history) and logs each model call's duration and cost to `ai-jobs.jsonl`. To write one it reads the root agent's latest steps from its live timeline only when Paseo already has the agent loaded; otherwise it reads the first and last part of the agent's provider transcript on disk (Claude Code's `~/.claude/projects`, Codex's `~/.codex/sessions`), read-only, and never wakes the agent. It reads subagent titles from Paseo's agent list, PR titles and bodies with `gh pr view`, and only the Linear issues and Slack threads the workspace itself links, through `mcpproxy call tool-read` (`linear:get_issue`, `slack-user:slack_read_thread`); there are no searches. The model is set under Settings → Agents (default Haiku). With Claude it runs as a headless `claude -p` with no tools, no MCP servers, no settings and no saved session. With Codex it runs as `codex exec --ephemeral` with no user config or rules, no shell tool and a read-only sandbox in an empty temporary folder. Either way it gets one turn, a 90-second timeout, and runs one call at a time; on timeout the whole process group is killed. Overviews are written ahead of time only for non-dormant workspaces in Needs you, at most 60 a day by default (Settings → Agents), and not while a Claude account is above 85% of a limit or the resource governor has paused background work; above its higher threshold, opening the section shows the cached overview and writes none.
|
|
49
49
|
|
|
50
50
|
Settings → Agents (`plugin-data/follow-up/agents.json`, its own file) chooses the provider, model, effort and mode for Summaries, the Overseer, recovery agents and the priority ranker. Missing or invalid entries use the defaults. The provider and model list comes from Paseo's provider snapshot. It is read only when that settings screen opens, and cached for ten minutes. A changed Overseer setting is never applied mid-conversation: Home offers a restart, and the new Overseer is handed the old one's last steps (read from its transcript on disk when it isn't loaded). The old agent is left as it is. A recovery agent on a different provider than the main agent keeps the main agent's system prompt, MCP servers and tool policy, and drops its provider-specific model, mode and options. `FOLLOW_UP_OVERSEER_PROVIDER` ("provider/model") overrides the Overseer's setting; it exists only for isolated test daemons.
|
package/index.server.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { stopWorker } from "./server/teardown";
|
|
2
|
+
import { WriteHealth } from "./server/write-behind";
|
|
2
3
|
import { actorBy, actorOf, type Actor } from "./shared/actor";
|
|
3
4
|
import { TICK_MS } from "./shared/poll";
|
|
4
5
|
import { PluginMove } from "./server/plugin-move";
|
|
@@ -201,6 +202,9 @@ export default function contribute(server: PluginServerContext) {
|
|
|
201
202
|
prWorkflow.onChanged = () => { void store.snapshot().then(state => store.onChanged(state)).catch(() => undefined); };
|
|
202
203
|
const browser = new BrowserBridge();
|
|
203
204
|
const reviewerStore = new ReviewerConfigStore(directory);
|
|
205
|
+
// an-ack-never-waits-on-the-disk (server/write-behind.ts): these files save behind the reply; one still failing after
|
|
206
|
+
// SURFACE_AFTER attempts shows as the worker's error line until it lands.
|
|
207
|
+
const writeHealth = new WriteHealth();
|
|
204
208
|
const reviewerSuggestions = new ReviewerSuggestions();
|
|
205
209
|
const actions = new PrActions(store, github, graphite, browser);
|
|
206
210
|
actions.savedMethod = repo => prWorkflow.current().repos[repoKey(repo)]?.mergeMethod ?? null;
|
|
@@ -311,8 +315,8 @@ export default function contribute(server: PluginServerContext) {
|
|
|
311
315
|
if (!governor.allowsExtras()) { if (!stopped) inboxTimer = setTimeout(() => void inboxLoop(), 15_000); return; }
|
|
312
316
|
try { await writeBriefState().catch(() => undefined); await inbox.tick(); await inbox.reconcilePermissions(); await inbox.observeGuard(); await inbox.observeFollowUp(await store.snapshot()); inboxError = null; }
|
|
313
317
|
catch (error) { inboxError = error instanceof Error ? error.message : "The Needs-you inbox couldn't update."; }
|
|
314
|
-
// The Overseer's digest
|
|
315
|
-
if (overseer) { await overseer.
|
|
318
|
+
// The Overseer's digest backstop (it is built when its turn starts: agent.turn_started below) and its recreation if it was archived. Never blocks the inbox.
|
|
319
|
+
if (overseer) { await overseer.backstopDigest().catch(() => undefined); if (api) await overseer.ensure(api as unknown as OverseerPaseo, { periodic: true }).catch(() => undefined); }
|
|
316
320
|
// The ranker's scheduled run (window, cadence, cap and the governor are its own checks). Never awaited: it can take minutes.
|
|
317
321
|
if (ranker) void ranker.tick().catch(() => undefined);
|
|
318
322
|
// Wake-ups, the Overseer's status and the directory's titles move with this tick; the feeds diff, so a quiet tick
|
|
@@ -414,6 +418,7 @@ export default function contribute(server: PluginServerContext) {
|
|
|
414
418
|
// Brief answers recorded before a reload that Paseo never confirmed go out again, under the same messageId.
|
|
415
419
|
await inbox.resumeAnswers(sendTo).catch(() => undefined);
|
|
416
420
|
})().catch(() => { loadError = "Follow-up could not start. Check its saved state and worker lock."; });
|
|
421
|
+
for (const file of [store, reviewerStore.persist, agentSettings.persist, prWorkflow.persist, inbox.store.persist]) file.health = writeHealth;
|
|
417
422
|
const requireReady = async () => { await ready; if (loadError || stopped) throw new Error(loadError ?? "Follow-up is stopping"); };
|
|
418
423
|
// 1.4.0-beta.2: Follow-up's tools per agent: natively through Paseo's MCP when the host serves plugin tools,
|
|
419
424
|
// otherwise the stdio bridge for this launch only. FOLLOW_UP_TOOLS tells the hooks which names the agent has.
|
|
@@ -545,8 +550,8 @@ export default function contribute(server: PluginServerContext) {
|
|
|
545
550
|
const view = browserWorkspaces(entries);
|
|
546
551
|
return { tracked: true, ...view, workspaces: view.workspaces.map(w => ({ ...w, title: w.title.slice(0, 200), agentStatus: w.agentStatus.slice(0, 40), state: w.state.slice(0, 200) })) };
|
|
547
552
|
});
|
|
548
|
-
handle(rpc.listRpc, async ({ since }) => { await ready; return { ...listCache.answer(await store.snapshot(), since), error: loadError ?? hookError ?? engine.error }; });
|
|
549
|
-
handle(rpc.getRpc, async ({ workspaceId }) => { await ready; return { workspace: (await store.snapshot()).workspaces.find(w => w.id === workspaceId && w.enable_tracking) ?? null, error: loadError ?? hookError ?? engine.error }; });
|
|
553
|
+
handle(rpc.listRpc, async ({ since }) => { await ready; return { ...listCache.answer(await store.snapshot(), since), error: loadError ?? hookError ?? writeHealth.message() ?? engine.error }; });
|
|
554
|
+
handle(rpc.getRpc, async ({ workspaceId }) => { await ready; return { workspace: (await store.snapshot()).workspaces.find(w => w.id === workspaceId && w.enable_tracking) ?? null, error: loadError ?? hookError ?? writeHealth.message() ?? engine.error }; });
|
|
550
555
|
handle(rpc.syncWorkspaceRpc, async ({ agentId, summary }, { paseo }) => {
|
|
551
556
|
await requireReady();
|
|
552
557
|
const workspaceId = await callerWorkspaceId(agentId, paseo, false);
|
|
@@ -1207,7 +1212,7 @@ export default function contribute(server: PluginServerContext) {
|
|
|
1207
1212
|
// Subscriptions (Paseo 0.16): every open client used to poll these reads (about 17 a minute for an idle Home); now
|
|
1208
1213
|
// the worker pushes from state it already holds, one shared serve per topic (server/feeds.ts, invariant
|
|
1209
1214
|
// idle-client-makes-at-most-one-rpc-a-minute). A 0.15 host serves no subscriptions, and its clients keep polling.
|
|
1210
|
-
const workspacesFeed = new WorkspacesFeed(listCache, () => store.snapshot(), () => loadError ?? hookError ?? engine.error);
|
|
1215
|
+
const workspacesFeed = new WorkspacesFeed(listCache, () => store.snapshot(), () => loadError ?? hookError ?? writeHealth.message() ?? engine.error);
|
|
1211
1216
|
const inboxFeed = new ValueFeed({ read: async () => { await requireReady(); return inboxAnswer({ ...await inbox.list(), error: inboxError }, undefined); }, key: v => v.etag ?? JSON.stringify(v) });
|
|
1212
1217
|
let usageWatch: { close(): void } | null = null;
|
|
1213
1218
|
const homeFeed = new ValueFeed({
|
|
@@ -1373,6 +1378,8 @@ export default function contribute(server: PluginServerContext) {
|
|
|
1373
1378
|
server.on("agent.turn_started", async () => updater.activity()),
|
|
1374
1379
|
server.on("agent.turn_ended", async () => { updater.activity(); void evaluateMove(); }),
|
|
1375
1380
|
server.on("agent.turn_started", async (event, { paseo }) => { seen(paseo); inboxHook(() => inbox.turnStarted(event.agent, event.turnId)); }),
|
|
1381
|
+
// a-derived-view-is-built-when-read: the Overseer's digest, built for the turn its prompt hook is about to read.
|
|
1382
|
+
server.on("agent.turn_started", async event => { await ready; if (stopped || loadError || !overseer) return; await overseer.turnStarted(event.agent.id).catch(() => undefined); }),
|
|
1376
1383
|
// A newer main-agent turn supersedes the failed turn's automatic hold (shared/status.ts holdSuperseded).
|
|
1377
1384
|
// A turn writes only the workspace it is about (server/turn-events.ts, a-send-never-clones-the-whole-state): a
|
|
1378
1385
|
// superseded hold lifts, the owned workspace's Done ends, and a dormant workspace becomes active again.
|
|
@@ -1473,6 +1480,6 @@ export default function contribute(server: PluginServerContext) {
|
|
|
1473
1480
|
// One deadline for every wait (worker-stop-never-waits-on-a-stuck-pass, server/teardown.ts): start-up and the work
|
|
1474
1481
|
// in flight may be stuck on a daemon or CLI that never answers. Work that ends inside the deadline is saved; what
|
|
1475
1482
|
// outlives it can't write, because the store closes before the lock is released.
|
|
1476
|
-
await stopWorker({ ready, hooks: hooksStarted ? () => agentHooks.stop() : undefined, actions, closeConnections, engine, store, inbox: inbox.store, unlock });
|
|
1483
|
+
await stopWorker({ files: [reviewerStore, agentSettings, prWorkflow], ready, hooks: hooksStarted ? () => agentHooks.stop() : undefined, actions, closeConnections, engine, store, inbox: inbox.store, unlock });
|
|
1477
1484
|
};
|
|
1478
1485
|
}
|
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.
|
|
4
|
+
"version": "2.0.2-beta.3",
|
|
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": [
|
package/server/agent-hook.mjs
CHANGED
|
@@ -82,6 +82,25 @@ export function overseerDigest(file, seen, now = Date.now(), { needsMax = 20, ch
|
|
|
82
82
|
for (const l of lines) { if (text.length + l.length + 1 > chars) { text += "- …truncated: use workstreams()\n"; break; } text += l + "\n"; }
|
|
83
83
|
return { text: text.trimEnd(), seen: { at: now, rows: Object.fromEntries(all.map(r => [r.id, r.hash])) } };
|
|
84
84
|
}
|
|
85
|
+
/**
|
|
86
|
+
* a-derived-view-is-built-when-read: the worker builds overseer-digest.json when the Overseer's turn starts, usually before
|
|
87
|
+
* this hook runs. The file is fresh for this turn when its builtAt is newer than the one the Overseer last saw and
|
|
88
|
+
* within windowMs of now; otherwise poll every stepMs for up to waitMs, then use what is there (the last build, at most
|
|
89
|
+
* the worker's 10-min backstop old). A worker that writes no builtAt is taken as is. Pure apart from read and sleep.
|
|
90
|
+
*/
|
|
91
|
+
export async function freshDigest(read, seen, { now = Date.now, sleep = ms => new Promise(r => setTimeout(r, ms)), waitMs = 1500, stepMs = 100, windowMs = 5000 } = {}) {
|
|
92
|
+
const fresh = file => {
|
|
93
|
+
if (!file?.builtAt) return true;
|
|
94
|
+
const built = Date.parse(file.builtAt);
|
|
95
|
+
const last = Date.parse(seen?.builtAt ?? "");
|
|
96
|
+
return (!Number.isFinite(last) || built > last) && now() - built <= windowMs;
|
|
97
|
+
};
|
|
98
|
+
let file = await read();
|
|
99
|
+
const until = now() + waitMs;
|
|
100
|
+
let waited = 0;
|
|
101
|
+
while (!fresh(file) && now() < until) { await sleep(stepMs); waited += stepMs; file = (await read()) ?? file; }
|
|
102
|
+
return { file, fresh: fresh(file), waited };
|
|
103
|
+
}
|
|
85
104
|
/**
|
|
86
105
|
* How batches are worked, for this workspace's PR workflow (from scopes.json). Graphite with /fix-pr, and agents of an
|
|
87
106
|
* older worker that wrote no workflow, keep the original text; plain GitHub never mentions Graphite, gt or /fix-pr.
|
|
@@ -196,11 +215,12 @@ async function main() {
|
|
|
196
215
|
return;
|
|
197
216
|
}
|
|
198
217
|
if (event.hook_event_name !== "UserPromptSubmit") return;
|
|
199
|
-
const file = await json(join(directory, "overseer-digest.json")).catch(() => null);
|
|
200
|
-
if (!file || file.agentId !== agentId) return;
|
|
201
218
|
const seenPath = join(directory, "hook-state", `overseer-seen-${agentId}.json`);
|
|
202
|
-
const
|
|
203
|
-
await
|
|
219
|
+
const seen = await json(seenPath).catch(() => null);
|
|
220
|
+
const { file } = await freshDigest(() => json(join(directory, "overseer-digest.json")).catch(() => null), seen);
|
|
221
|
+
if (!file || file.agentId !== agentId) return;
|
|
222
|
+
const digest = overseerDigest(file, seen);
|
|
223
|
+
await save(seenPath, { ...digest.seen, ...(file.builtAt ? { builtAt: file.builtAt } : {}) });
|
|
204
224
|
process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: digest.text } }) + "\n");
|
|
205
225
|
return;
|
|
206
226
|
}
|
package/server/agent-settings.ts
CHANGED
|
@@ -1,20 +1,25 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
2
|
import { join } from "node:path";
|
|
3
|
-
import {
|
|
3
|
+
import { WriteBehind } from "./write-behind";
|
|
4
4
|
import {
|
|
5
5
|
AGENT_ROLES, EMPTY_AGENT_SETTINGS, isJobRole, parseAgentSettings, resolveAll, resolveRole,
|
|
6
6
|
type AgentRole, type AgentSettingsFile, type Catalog, type CatalogProvider, type RoleConfig, type SavedRole,
|
|
7
7
|
} from "../shared/agent-settings";
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
|
-
* The role settings file (`agents.json`), its own small file next to state.json. Read once and cached;
|
|
11
|
-
* serialized
|
|
10
|
+
* The role settings file (`agents.json`), its own small file next to state.json. Read once and cached; changes are
|
|
11
|
+
* serialized and validated, then saved behind the reply (an-ack-never-waits-on-the-disk, server/write-behind.ts),
|
|
12
|
+
* atomic and owner-only, and only when the developer changes something.
|
|
12
13
|
*/
|
|
13
14
|
export class AgentSettingsStore {
|
|
14
15
|
private tail: Promise<unknown> = Promise.resolve();
|
|
15
16
|
private cached: { file: AgentSettingsFile; invalid: AgentRole[] } | null = null;
|
|
16
|
-
|
|
17
|
+
/** agents.json, written behind the reply. */
|
|
18
|
+
readonly persist: WriteBehind<AgentSettingsFile>;
|
|
19
|
+
constructor(readonly directory: string) { this.persist = new WriteBehind({ path: this.path, encode: file => JSON.stringify(file, null, 2) }); }
|
|
17
20
|
private get path() { return join(this.directory, "agents.json"); }
|
|
21
|
+
/** Waits for the changes in flight, then writes what is pending; the worker's stop calls it. */
|
|
22
|
+
async flush(): Promise<void> { await this.tail; await this.persist.flush(); }
|
|
18
23
|
|
|
19
24
|
async load(): Promise<{ file: AgentSettingsFile; invalid: AgentRole[] }> {
|
|
20
25
|
if (this.cached) return this.cached;
|
|
@@ -38,8 +43,8 @@ export class AgentSettingsStore {
|
|
|
38
43
|
copy.roles[role] = clean(role, parsed.file.roles[role] ?? {});
|
|
39
44
|
if (!Object.keys(copy.roles[role]!).length) delete copy.roles[role];
|
|
40
45
|
}
|
|
41
|
-
await this.write(copy);
|
|
42
46
|
this.cached = { file: copy, invalid: (this.cached?.invalid ?? []).filter(r => r !== role) };
|
|
47
|
+
this.persist.set(copy);
|
|
43
48
|
return copy;
|
|
44
49
|
});
|
|
45
50
|
this.tail = next.catch(() => undefined);
|
|
@@ -53,23 +58,14 @@ export class AgentSettingsStore {
|
|
|
53
58
|
const { file, invalid } = await this.load();
|
|
54
59
|
const copy: AgentSettingsFile = { ...structuredClone(file), enable_wait: enabled };
|
|
55
60
|
if (enabled) delete copy.enable_wait;
|
|
56
|
-
await this.write(copy);
|
|
57
61
|
this.cached = { file: copy, invalid };
|
|
62
|
+
this.persist.set(copy);
|
|
58
63
|
return copy;
|
|
59
64
|
});
|
|
60
65
|
this.tail = next.catch(() => undefined);
|
|
61
66
|
return next;
|
|
62
67
|
}
|
|
63
68
|
|
|
64
|
-
private async write(file: AgentSettingsFile): Promise<void> {
|
|
65
|
-
await mkdir(this.directory, { recursive: true, mode: 0o700 });
|
|
66
|
-
const temporary = join(this.directory, `agents.${randomUUID()}.tmp`);
|
|
67
|
-
try {
|
|
68
|
-
const handle = await open(temporary, "wx", 0o600);
|
|
69
|
-
try { await handle.writeFile(JSON.stringify(file, null, 2)); await handle.sync(); } finally { await handle.close(); }
|
|
70
|
-
await rename(temporary, this.path);
|
|
71
|
-
} finally { await unlink(temporary).catch(() => undefined); }
|
|
72
|
-
}
|
|
73
69
|
}
|
|
74
70
|
|
|
75
71
|
/** Fields a role doesn't use aren't stored. */
|
package/server/hook-source.ts
CHANGED
|
@@ -85,6 +85,25 @@ export const hookSource: string = [
|
|
|
85
85
|
" return { text: text.trimEnd(), seen: { at: now, rows: Object.fromEntries(all.map(r => [r.id, r.hash])) } };",
|
|
86
86
|
"}",
|
|
87
87
|
"/**",
|
|
88
|
+
" * a-derived-view-is-built-when-read: the worker builds overseer-digest.json when the Overseer's turn starts, usually before",
|
|
89
|
+
" * this hook runs. The file is fresh for this turn when its builtAt is newer than the one the Overseer last saw and",
|
|
90
|
+
" * within windowMs of now; otherwise poll every stepMs for up to waitMs, then use what is there (the last build, at most",
|
|
91
|
+
" * the worker's 10-min backstop old). A worker that writes no builtAt is taken as is. Pure apart from read and sleep.",
|
|
92
|
+
" */",
|
|
93
|
+
"export async function freshDigest(read, seen, { now = Date.now, sleep = ms => new Promise(r => setTimeout(r, ms)), waitMs = 1500, stepMs = 100, windowMs = 5000 } = {}) {",
|
|
94
|
+
" const fresh = file => {",
|
|
95
|
+
" if (!file?.builtAt) return true;",
|
|
96
|
+
" const built = Date.parse(file.builtAt);",
|
|
97
|
+
" const last = Date.parse(seen?.builtAt ?? \"\");",
|
|
98
|
+
" return (!Number.isFinite(last) || built > last) && now() - built <= windowMs;",
|
|
99
|
+
" };",
|
|
100
|
+
" let file = await read();",
|
|
101
|
+
" const until = now() + waitMs;",
|
|
102
|
+
" let waited = 0;",
|
|
103
|
+
" while (!fresh(file) && now() < until) { await sleep(stepMs); waited += stepMs; file = (await read()) ?? file; }",
|
|
104
|
+
" return { file, fresh: fresh(file), waited };",
|
|
105
|
+
"}",
|
|
106
|
+
"/**",
|
|
88
107
|
" * How batches are worked, for this workspace's PR workflow (from scopes.json). Graphite with /fix-pr, and agents of an",
|
|
89
108
|
" * older worker that wrote no workflow, keep the original text; plain GitHub never mentions Graphite, gt or /fix-pr.",
|
|
90
109
|
" */",
|
|
@@ -198,11 +217,12 @@ export const hookSource: string = [
|
|
|
198
217
|
" return;",
|
|
199
218
|
" }",
|
|
200
219
|
" if (event.hook_event_name !== \"UserPromptSubmit\") return;",
|
|
201
|
-
" const file = await json(join(directory, \"overseer-digest.json\")).catch(() => null);",
|
|
202
|
-
" if (!file || file.agentId !== agentId) return;",
|
|
203
220
|
" const seenPath = join(directory, \"hook-state\", `overseer-seen-${agentId}.json`);",
|
|
204
|
-
" const
|
|
205
|
-
" await
|
|
221
|
+
" const seen = await json(seenPath).catch(() => null);",
|
|
222
|
+
" const { file } = await freshDigest(() => json(join(directory, \"overseer-digest.json\")).catch(() => null), seen);",
|
|
223
|
+
" if (!file || file.agentId !== agentId) return;",
|
|
224
|
+
" const digest = overseerDigest(file, seen);",
|
|
225
|
+
" await save(seenPath, { ...digest.seen, ...(file.builtAt ? { builtAt: file.builtAt } : {}) });",
|
|
206
226
|
" process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: \"UserPromptSubmit\", additionalContext: digest.text } }) + \"\\n\");",
|
|
207
227
|
" return;",
|
|
208
228
|
" }",
|
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 {
|
|
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
|
-
/**
|
|
54
|
-
|
|
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
|
-
|
|
116
|
-
|
|
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,20 +140,61 @@ 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
|
-
|
|
144
|
-
if (this.
|
|
145
|
-
|
|
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();
|
|
146
147
|
}
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* a-mutation-costs-what-it-changes, for the write: inbox.json is JSON.stringify(state), byte for byte, written as the
|
|
151
|
+
* UTF-8 of each part in order (writev), from a cached buffer per saved (frozen) value: each entry, and each top-level
|
|
152
|
+
* field (briefOrigins is 26 KB). The saved state is deep-frozen and a frozen object never changes, so its bytes stay
|
|
153
|
+
* right for as long as the object lives, and a write encodes only what changed since the last one. Cached strings
|
|
154
|
+
* wouldn't do: joining them back into one 133 KB string per write allocated twice what JSON.stringify did. 2026-11-14
|
|
155
|
+
* (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.
|
|
156
|
+
*/
|
|
157
|
+
const frozenBytes = new WeakMap<object, Buffer>();
|
|
158
|
+
const keyBytes = new Map<string, Buffer>();
|
|
159
|
+
const OPEN = Buffer.from("{"), CLOSE = Buffer.from("}"), COMMA = Buffer.from(",");
|
|
160
|
+
function valueBytes(value: unknown): Buffer | undefined {
|
|
161
|
+
const frozen = value !== null && typeof value === "object" && Object.isFrozen(value);
|
|
162
|
+
const cached = frozen ? frozenBytes.get(value) : undefined;
|
|
163
|
+
if (cached) return cached;
|
|
164
|
+
const text = JSON.stringify(value);
|
|
165
|
+
if (text === undefined) return undefined;
|
|
166
|
+
const bytes = Buffer.from(text);
|
|
167
|
+
if (frozen) frozenBytes.set(value, bytes);
|
|
168
|
+
return bytes;
|
|
169
|
+
}
|
|
170
|
+
function memberKey(key: string): Buffer {
|
|
171
|
+
let bytes = keyBytes.get(key);
|
|
172
|
+
if (!bytes) { bytes = Buffer.from(`${JSON.stringify(key)}:`); keyBytes.set(key, bytes); }
|
|
173
|
+
return bytes;
|
|
174
|
+
}
|
|
175
|
+
/** JSON.stringify of a plain object as parts: members in insertion order, undefined, functions and symbols left out. */
|
|
176
|
+
function objectParts(value: Record<string, unknown>, out: Buffer[], member: (v: unknown, out: Buffer[]) => boolean): void {
|
|
177
|
+
out.push(OPEN); let first = true;
|
|
178
|
+
for (const key of Object.keys(value)) {
|
|
179
|
+
const at = out.length;
|
|
180
|
+
if (!first) out.push(COMMA);
|
|
181
|
+
out.push(memberKey(key));
|
|
182
|
+
if (member(value[key], out)) first = false; else out.length = at;
|
|
156
183
|
}
|
|
184
|
+
out.push(CLOSE);
|
|
185
|
+
}
|
|
186
|
+
const pushValue = (v: unknown, out: Buffer[]): boolean => { const b = valueBytes(v); if (b) out.push(b); return !!b; };
|
|
187
|
+
/** inbox.json's bytes, in parts: the same bytes as Buffer.from(JSON.stringify(state)). */
|
|
188
|
+
export function inboxJsonParts(state: InboxState): Buffer[] {
|
|
189
|
+
const out: Buffer[] = [];
|
|
190
|
+
objectParts(state as Record<string, unknown>, out, (v, o) => {
|
|
191
|
+
if (v !== state.entries) return pushValue(v, o);
|
|
192
|
+
objectParts(state.entries as Record<string, unknown>, o, pushValue);
|
|
193
|
+
return true;
|
|
194
|
+
});
|
|
195
|
+
// Agent ids come and go: keep the key cache to the keys this inbox has.
|
|
196
|
+
if (keyBytes.size > 4 * (Object.keys(state.entries).length + 32)) keyBytes.clear();
|
|
197
|
+
return out;
|
|
157
198
|
}
|
|
158
199
|
/**
|
|
159
200
|
* a-mutation-costs-what-it-changes: entries draft per entry; briefOrigins, read whole and replaced whole, drafts as the
|
package/server/overseer.ts
CHANGED
|
@@ -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
|
-
*
|
|
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)
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
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. */
|
package/server/pr-workflow.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { access, constants,
|
|
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 {
|
|
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
|
-
|
|
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
|
}
|
|
@@ -1,19 +1,24 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
2
|
import { join } from "node:path";
|
|
3
|
-
import {
|
|
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`).
|
|
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
|
-
|
|
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> {
|
package/server/teardown.ts
CHANGED
|
@@ -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
|
+
}
|
package/shared/overseer.ts
CHANGED
|
@@ -183,8 +183,10 @@ export function pageRows(rows: WorkstreamRow[], opts: { page?: number; size?: nu
|
|
|
183
183
|
/** What the daemon writes for the hook: one line per workstream and a hash per line, so the hook can diff turns. */
|
|
184
184
|
export type DigestFile = {
|
|
185
185
|
version: 1; agentId: string;
|
|
186
|
-
/** When the content last changed. The daemon rewrites the file only when `hash` moves. */
|
|
186
|
+
/** When the content last changed. The daemon rewrites the file only when `hash` moves, or for an Overseer turn. */
|
|
187
187
|
at: string; total: number; needs: number;
|
|
188
|
+
/** When the worker built it (a-derived-view-is-built-when-read): the hook waits briefly for one built for its turn. */
|
|
189
|
+
builtAt?: string;
|
|
188
190
|
/** Over the agent id and every row hash: equal hashes mean an identical digest. */
|
|
189
191
|
hash: string;
|
|
190
192
|
/** Resting rows carry `resting` and a title-only line; the hook lists them in one compact line. */
|