paseo-follow-up 2.3.0 → 2.4.0-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 (45) hide show
  1. package/client/brief.tsx +7 -5
  2. package/client/header.tsx +18 -9
  3. package/client/home-list.tsx +3 -3
  4. package/client/home.tsx +3 -2
  5. package/client/merge-button.tsx +1 -1
  6. package/client/stacks.tsx +24 -2
  7. package/index.client.tsx +1 -1
  8. package/index.server.ts +42 -7
  9. package/package.json +2 -1
  10. package/server/agent-actions.ts +4 -3
  11. package/server/agent-hook.mjs +35 -6
  12. package/server/browser-bridge.ts +20 -2
  13. package/server/check-watches.ts +145 -0
  14. package/server/engine.ts +13 -2
  15. package/server/github.ts +15 -2
  16. package/server/hook-source.ts +35 -6
  17. package/server/mcp-source.ts +8 -5
  18. package/server/mcp.mjs +8 -5
  19. package/server/obligations.ts +18 -2
  20. package/server/pr-actions.ts +17 -11
  21. package/server/pr-owner.ts +30 -13
  22. package/server/pr-stats-gate.ts +102 -0
  23. package/server/pr-stats-store.ts +196 -0
  24. package/server/pr-stats-sync.ts +228 -0
  25. package/server/questions.ts +35 -8
  26. package/server/ranker.ts +3 -2
  27. package/server/wait-for-checks.ts +108 -0
  28. package/shared/activity.ts +2 -2
  29. package/shared/attention.ts +88 -15
  30. package/shared/brief.ts +16 -0
  31. package/shared/chat.ts +1 -1
  32. package/shared/check-watch.ts +129 -0
  33. package/shared/contracts.ts +10 -3
  34. package/shared/errors.ts +34 -0
  35. package/shared/home.ts +51 -13
  36. package/shared/model.ts +17 -2
  37. package/shared/poll.ts +9 -2
  38. package/shared/pr-actions.ts +61 -3
  39. package/shared/pr-stats-records.ts +169 -0
  40. package/shared/questions.ts +75 -0
  41. package/shared/queue.ts +1 -1
  42. package/shared/ranker.ts +3 -2
  43. package/shared/scale.ts +24 -0
  44. package/shared/status-invariants.ts +39 -1
  45. package/shared/task-status.ts +9 -2
@@ -0,0 +1,145 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import { WriteBehind } from "./write-behind";
5
+ import type { MessageQueue, Resolution } from "./message-queue";
6
+ import type { State, Workspace } from "../shared/model";
7
+ import { WATCHES_PER_AGENT, checkWatchFileSchema, coveredByRepair, watchVerdict, type CheckWatch, type Verdict } from "../shared/check-watch";
8
+
9
+ export const WATCH_FILE = "check-watches.json";
10
+ export const checksItemId = (w: Pick<CheckWatch, "agentId" | "id">) => `checks:${w.agentId}:${w.id}`;
11
+
12
+ /** What the channel needs to know about the agent when the message goes: nothing here loads it. */
13
+ export type WatchAgent = { status: string; archived: boolean; workspaceId: string | null } | null;
14
+
15
+ /**
16
+ * Wait for checks (docs/wait-for-checks.md; shared/check-watch.ts holds the rules). The watches live in memory and
17
+ * save behind the reply (an-ack-never-waits-on-the-disk). `evaluate` runs after each engine pass on the state that pass
18
+ * wrote, so a watch costs no GitHub read of its own (waiting-for-checks-adds-no-github-read): its PR only counts as
19
+ * due at the running-checks cadence (`watched`). A verdict becomes one `checks` message on the queue
20
+ * (a-message-is-saved-before-sent-and-arrives-once), sent only to an agent that is neither closed nor archived
21
+ * (a-watch-never-wakes-a-closed-agent), and never beside a repair that carries the same failure
22
+ * (a-waited-for-failure-is-sent-once).
23
+ */
24
+ export class CheckWatches {
25
+ private value: CheckWatch[] | null = null;
26
+ readonly persist: WriteBehind<{ version: 1; watches: CheckWatch[] }>;
27
+ private queue: MessageQueue | null = null;
28
+ /** Fired verdicts (for tests and the docs' counts). */
29
+ readonly fired: { watch: CheckWatch; verdict: Verdict; sent: boolean; why: string }[] = [];
30
+ constructor(readonly directory: string, private deps: {
31
+ snapshot: () => Promise<State>;
32
+ /** When the PR's content last changed (or Follow-up first saw it), from the reads already made; null: unknown. */
33
+ quietSince?: (prKey: string) => number | null;
34
+ agent: (agentId: string) => Promise<WatchAgent>;
35
+ now?: () => number;
36
+ }) {
37
+ this.persist = new WriteBehind({ path: join(directory, WATCH_FILE), encode: v => JSON.stringify(v) });
38
+ }
39
+ private now(): number { return (this.deps.now ?? Date.now)(); }
40
+ async flush(): Promise<void> { await this.persist.flush(); }
41
+ private async load(): Promise<CheckWatch[]> {
42
+ if (this.value) return this.value;
43
+ let watches: CheckWatch[];
44
+ try { watches = checkWatchFileSchema.parse(JSON.parse(await readFile(join(this.directory, WATCH_FILE), "utf8"))).watches; }
45
+ catch { watches = []; } // A lost file costs the agent a call again, never a broken worker.
46
+ // A worker that stopped mid-answer left the flag on: the call it belonged to is gone, so the watch messages now.
47
+ this.value ??= watches.map(w => w.answering ? { ...w, answering: false } : w);
48
+ return this.value;
49
+ }
50
+ private save(watches: CheckWatch[]): void {
51
+ this.value = watches;
52
+ this.persist.set({ version: 1, watches });
53
+ }
54
+ async list(agentId?: string): Promise<CheckWatch[]> {
55
+ const all = await this.load();
56
+ return agentId ? all.filter(w => w.agentId === agentId) : all;
57
+ }
58
+ /** PR key → when its oldest watch began: github.ts reads it at the running-checks cadence, and once after that time. */
59
+ watched(): Map<string, number> {
60
+ const out = new Map<string, number>();
61
+ for (const w of this.value ?? []) { const at = Date.parse(w.createdAt); out.set(w.prKey, Math.min(out.get(w.prKey) ?? at, at)); }
62
+ return out;
63
+ }
64
+ /** One watch per agent and PR: asking again restarts its clock and keeps what it learned. */
65
+ async add(input: { agentId: string; workspaceId: string; prKey: string; url: string; ms: number }): Promise<CheckWatch> {
66
+ const watches = await this.load();
67
+ const at = new Date(this.now());
68
+ const existing = watches.find(w => w.agentId === input.agentId && w.prKey === input.prKey);
69
+ if (!existing && watches.filter(w => w.agentId === input.agentId).length >= WATCHES_PER_AGENT) throw new Error(`You already wait on ${WATCHES_PER_AGENT} PRs. End your turn; Follow-up messages you as each finishes.`);
70
+ const watch: CheckWatch = { id: existing?.id ?? randomUUID(), agentId: input.agentId, workspaceId: input.workspaceId, prKey: input.prKey, url: input.url,
71
+ createdAt: at.toISOString(), until: new Date(at.getTime() + input.ms).toISOString(), answering: true, runningHead: existing?.runningHead ?? null };
72
+ this.save([...watches.filter(w => w !== existing), watch]);
73
+ return watch;
74
+ }
75
+ /** Ends the tool call's hold: a verdict it reported itself ends the watch; otherwise the watch messages later. */
76
+ async answered(id: string, ended: boolean): Promise<void> {
77
+ const watches = await this.load();
78
+ const next = ended ? watches.filter(w => w.id !== id) : watches.map(w => w.id === id && w.answering ? { ...w, answering: false } : w);
79
+ if (next.length !== watches.length || next.some((w, i) => w !== watches[i])) this.save(next);
80
+ }
81
+ async cancel(agentId: string, prKey?: string): Promise<number> {
82
+ const watches = await this.load();
83
+ const next = watches.filter(w => !(w.agentId === agentId && (!prKey || w.prKey === prKey)));
84
+ if (next.length !== watches.length) this.save(next);
85
+ return watches.length - next.length;
86
+ }
87
+ /** The verdict for one watch now, from the stored PR (the tool's immediate answer). */
88
+ async check(watch: CheckWatch): Promise<{ fire: Verdict | null; next: CheckWatch }> {
89
+ const state = await this.deps.snapshot();
90
+ const w = state.workspaces.find(x => x.id === watch.workspaceId);
91
+ return watchVerdict(watch, w?.prs.find(p => p.key === watch.prKey), this.now(), this.deps.quietSince?.(watch.prKey) ?? null);
92
+ }
93
+ /**
94
+ * After an engine pass: every watch on those workspaces (all when `ids` is absent) against the state the pass left.
95
+ * Pure reads of the snapshot; a verdict saves one queue item and drops the watch. Watches whose tool call is still
96
+ * answering are left to it.
97
+ */
98
+ async evaluate(ids?: ReadonlySet<string>): Promise<void> {
99
+ const watches = await this.load();
100
+ if (!watches.length) return;
101
+ const state = await this.deps.snapshot();
102
+ const now = this.now();
103
+ let next: CheckWatch[] | null = null;
104
+ for (const watch of watches) {
105
+ if (watch.answering || ids && !ids.has(watch.workspaceId)) continue;
106
+ const w = state.workspaces.find(x => x.id === watch.workspaceId);
107
+ const pr = w && w.enable_tracking && !w.archived ? w.prs.find(p => p.key === watch.prKey) : undefined;
108
+ const { fire, next: updated } = watchVerdict(watch, pr, now, this.deps.quietSince?.(watch.prKey) ?? null);
109
+ if (!fire && updated === watch) continue;
110
+ next ??= [...watches];
111
+ const index = next.indexOf(watch);
112
+ if (!fire) { next[index] = updated; continue; }
113
+ next.splice(index, 1);
114
+ await this.deliver(watch, fire, w);
115
+ }
116
+ if (next) this.save(next);
117
+ }
118
+ private async deliver(watch: CheckWatch, verdict: Verdict, w: Workspace | undefined): Promise<void> {
119
+ if (verdict.kind === "failed" && w && coveredByRepair(w, watch.agentId, watch.prKey)) { this.fired.push({ watch, verdict, sent: false, why: "repair" }); return; }
120
+ // Closed or archived: the watch ends with nothing sent (a-watch-never-wakes-a-closed-agent). Unknown keeps the
121
+ // message; the channel checks again when it goes.
122
+ const agent = await this.deps.agent(watch.agentId).catch(() => null);
123
+ if (agent && (agent.archived || agent.status === "closed")) { this.fired.push({ watch, verdict, sent: false, why: agent.archived ? "archived" : "closed" }); return; }
124
+ if (!this.queue) { this.fired.push({ watch, verdict, sent: false, why: "no queue" }); return; }
125
+ this.queue.enqueue({ id: checksItemId(watch), kind: "checks", key: watch.workspaceId, ref: { agentId: watch.agentId, workspaceId: watch.workspaceId, prKey: watch.prKey },
126
+ messageId: `checks-${watch.id}-${Date.parse(watch.createdAt).toString(36)}`, text: verdict.text, priority: "now", state: "queued" });
127
+ this.fired.push({ watch, verdict, sent: true, why: "queued" });
128
+ }
129
+ /** The queue's `checks` channel: the agent is resolved when the message goes, never woken from closed or archived. */
130
+ attachQueue(queue: MessageQueue): void {
131
+ this.queue = queue;
132
+ queue.register("checks", {
133
+ resolve: async (item): Promise<Resolution> => {
134
+ let agent: WatchAgent;
135
+ try { agent = await this.deps.agent(item.ref.agentId!); }
136
+ catch { return { defer: "Paseo unreachable" }; }
137
+ if (!agent || agent.archived) return { cancel: "The agent was archived, so the checks result wasn't sent." };
138
+ if (agent.status === "closed") return { cancel: "The agent was closed, so the checks result wasn't sent (Follow-up never reopens it for this)." };
139
+ if (item.state === "queued" && ["running", "initializing"].includes(agent.status)) return { defer: "waits for the agent's turn to end" };
140
+ return { target: { workspaceId: agent.workspaceId, recipients: [item.ref.agentId!] } };
141
+ },
142
+ project: async () => undefined,
143
+ });
144
+ }
145
+ }
package/server/engine.ts CHANGED
@@ -14,6 +14,7 @@ import { applyDiscovery, interruptionHold, startsWithAutoSend, type DiscoveredWo
14
14
  import { ACTIVE_SCOPE_MIGRATION, followsByDefault, migrateActiveScope } from "../shared/settings";
15
15
  import { replyRecorded } from "../shared/communication";
16
16
  import { DeliveryDeferred, ConversationGone } from "./delivery";
17
+ import type { CheckWatches } from "./check-watches";
17
18
  import type { MessageQueue, Resolution, Target } from "./message-queue";
18
19
  import { PASEO_UNREACHABLE, deliveryOf, type NewQueueItem, type QueueItem, type QueueItemInput } from "../shared/queue";
19
20
  import { recordSnapshot } from "./deployment-anchor";
@@ -253,12 +254,12 @@ export class Engine {
253
254
  // sends). Before 2.0.1-beta.2 it read nothing, so a stale PR error there outlived every Refresh.
254
255
  const asleep = o.workspaceId ? current.workspaces.find(w => w.id === o.workspaceId && w.enable_tracking && !w.archived && w.dormant) : undefined;
255
256
  if (asleep) await this.refreshPrs(asleep);
256
- if (!active.length) { this.error = null; return; }
257
+ if (!active.length) { await this.afterPass(o.affected); this.error = null; return; }
257
258
  // Busy workspaces keep every-tick PR reads: their agent may push or answer review at any moment.
258
259
  const keys = (ws: Workspace[]) => new Set(ws.flatMap(w => w.prs.map(p => p.key)));
259
260
  const hot = keys(active.filter(isHot));
260
261
  const read = o.affected ? active.filter(w => o.affected!.has(w.id)) : active;
261
- const observations = await this.github.observe(read.flatMap(w => w.prs), o.background || o.workspaceId ? { background: true, hot, fresh: keys(active.filter(w => w.id === o.workspaceId)) } : {});
262
+ const observations = await this.github.observe(read.flatMap(w => w.prs), o.background || o.workspaceId ? { background: true, hot, fresh: keys(active.filter(w => w.id === o.workspaceId)), watched: this.checkWatches?.watched() } : {});
262
263
  // A nudge observes only its workspaces (a-nudge-costs-its-workspace); the timer's tick observes every active one.
263
264
  for (const original of o.affected ? read : active) {
264
265
  if (this.stopped) return;
@@ -376,8 +377,18 @@ export class Engine {
376
377
  this.observedPass.set(original.id, { w: after, runtime: runtimeKey, at: untouched ? last!.at : this.now(), dueAt: nextDue(after, this.now()) });
377
378
  await this.statusCheck(after, this.now(), runtimeKey).catch(() => undefined);
378
379
  }
380
+ await this.afterPass(o.affected);
379
381
  this.error = null;
380
382
  }
383
+ /**
384
+ * Wait for checks (server/check-watches.ts): agents waiting on a PR's checks hear from the reads this pass just made,
385
+ * never from a read of their own (waiting-for-checks-adds-no-github-read). A nudge's pass judges only its workspaces.
386
+ */
387
+ checkWatches: Pick<CheckWatches, "watched" | "evaluate"> | null = null;
388
+ private async afterPass(affected?: ReadonlySet<string>): Promise<void> {
389
+ if (!this.checkWatches || this.stopped) return;
390
+ await this.checkWatches.evaluate(affected).catch(error => console.warn(`[follow-up] couldn't check the waits for checks: ${error instanceof Error ? error.message : String(error)}`));
391
+ }
381
392
  /**
382
393
  * A nudge's discovery (a-nudge-costs-its-workspace): only the nudged workspaces and their dirty agents (the kept turn
383
394
  * read, else a read of that agent), each applied with a one-workspace mutation. 2026-11-13 (run Y, the CI live shape): every turn end's nudge ran
package/server/github.ts CHANGED
@@ -241,6 +241,17 @@ export class Github {
241
241
  this.budgets.set(owner, { remaining: rate.remaining, resetAt: Date.parse(rate.resetAt) || this.now() + 3_600_000, ...(typeof rate.limit === "number" ? { limit: rate.limit } : {}) });
242
242
  this.stats.points += Number(rate.cost) || 0;
243
243
  }
244
+ /**
245
+ * A rateLimit another reader saw for this owner's account (PR statistics, server/pr-stats-gate.ts): it moves the same
246
+ * budget this poller reads, so a burst either one sees throttles both (`stats-feed-the-shared-budget`). Its cost is
247
+ * not counted in `stats.points`, which measures the poller's own reads.
248
+ */
249
+ noteRateLimit(owner: string, rate: { remaining?: number; resetAt?: string; limit?: number }): void {
250
+ if (typeof rate.remaining !== "number") return;
251
+ this.budgets.set(owner, { remaining: rate.remaining, resetAt: Date.parse(rate.resetAt ?? "") || this.now() + 3_600_000, ...(typeof rate.limit === "number" ? { limit: rate.limit } : {}) });
252
+ }
253
+ /** GitHub refused another reader for the limit: nothing on this account is read until `resetAt`. */
254
+ noteLimited(owner: string, resetAt: number): void { this.outOfBudget(owner, { resetAt }); }
244
255
  private outOfBudget(owner: string, error: unknown): void {
245
256
  this.budgets.set(owner, { remaining: 0, resetAt: (error as { resetAt?: number }).resetAt ?? this.now() + 10 * 60_000 });
246
257
  }
@@ -257,7 +268,7 @@ export class Github {
257
268
  * per account for every such PR, and read in full only when the probe saw a change that matters (`probeVerdict`).
258
269
  * A fresh request (Refresh, opening the panel) and a foreground read (agent tools, actions) read in full.
259
270
  */
260
- async observe(prs: Pr[], o: { background?: boolean; fresh?: Set<string>; hot?: Set<string> } = {}): Promise<Map<string, Observation>> {
271
+ async observe(prs: Pr[], o: { background?: boolean; fresh?: Set<string>; hot?: Set<string>; watched?: ReadonlyMap<string, number> } = {}): Promise<Map<string, Observation>> {
261
272
  const result = new Map<string, Observation>();
262
273
  const repositories = [...new Set(prs.map(p => p.repo))];
263
274
  const modes = new Map<string, PrWorkflow>();
@@ -282,7 +293,7 @@ export class Github {
282
293
  if (tier === "reserve" && o.background && !o.fresh?.has(p.key)) return false;
283
294
  if (!o.background || !this.last.has(p.key) || o.fresh?.has(p.key) || o.hot?.has(p.key)) return true;
284
295
  const last = this.last.get(p.key)!;
285
- return dueForRead({ snapshot: last.snapshot, error: p.error || last.error, changedAt: this.changedAt.get(p.key) ?? null, readAt: this.readAt.get(p.key) ?? 0, now: this.now(), tier, repoUrgent, since: this.changedAt.get(p.key) ?? this.seenAt.get(p.key) ?? null });
296
+ return dueForRead({ snapshot: last.snapshot, error: p.error || last.error, changedAt: this.changedAt.get(p.key) ?? null, readAt: this.readAt.get(p.key) ?? 0, now: this.now(), tier, repoUrgent, since: this.changedAt.get(p.key) ?? this.seenAt.get(p.key) ?? null, watchedSince: o.watched?.get(p.key) ?? null });
286
297
  });
287
298
  const dueKeys = new Set(due.map(p => p.key));
288
299
  for (const p of targets) if (!dueKeys.has(p.key)) { this.stats.skipped++; result.set(p.key, finalMerged(p) ? { snapshot: { ...p.snapshot! }, error: null } : this.standIn(p, owner)); }
@@ -434,6 +445,8 @@ export class Github {
434
445
  * While Follow-up holds back reads on this repository's account for the budget (the reserve or less), when they
435
446
  * resume (GitHub's reset); null when reads run. Feeds the workspace's "GitHub budget low" line (Workspace.githubWait).
436
447
  */
448
+ /** When this PR's content last changed, else when this worker first read it; null before any read (wait for checks' settle rule). */
449
+ quietSince(key: string): number | null { return this.changedAt.get(key) ?? this.seenAt.get(key) ?? null; }
437
450
  waitUntil(repo: string): number | null {
438
451
  const budget = this.budgets.get(repo.split("/")[0]);
439
452
  const tier = budgetTier(budget, this.now());
@@ -15,7 +15,7 @@ export const hookSource: string = [
15
15
  "/** 1.4.0-beta.2: launched with Follow-up's tools served by Paseo's MCP (follow_<name>), or the follow-up bridge (<name>). Agents opened before the upgrade carry no flag and keep the bridge names. */",
16
16
  "let native = env(\"TOOLS\") === \"native\";",
17
17
  "// Tool names that read unambiguously in prose; kept identical to server/mcp.mjs's underscore names (a test checks it).",
18
- "export const TOOL_NAMES = [\"workspace_status\", \"sync_workspace\", \"enroll_workspace\", \"register_pr\", \"exclude_stack\", \"update_obligation\", \"acknowledge_batch\", \"ask_question\", \"record_answer\", \"withdraw_question\", \"set_spec\", \"link_item\", \"unlink_item\", \"link_items\", \"set_linked_items\", \"workspace_about\", \"agent_settings\", \"needs_you\", \"declare_done\", \"list_prs\", \"add_reviewers\", \"enable_merge_when_ready\", \"disable_merge_when_ready\", \"send_repairs\", \"set_auto_send\", \"clear_hold\", \"retry_batch\", \"inbox_list\", \"sign_off\", \"snooze_workspace\", \"set_finish_flags\", \"set_priorities\", \"agent_digest\", \"route_candidates\", \"send_to_agent\", \"start_workspace\", \"display_settings\", \"set_display\", \"follow_settings\", \"set_follow_settings\", \"project_settings\", \"set_project_tracking\", \"pr_workflow\", \"set_pr_workflow\", \"reviewer_settings\", \"reviewer_suggestions\", \"save_reviewers\", \"set_agent_setting\", \"set_wait_for_jobs\", \"onboarding_status\", \"onboarding_checks\", \"set_onboarding\", \"rank_status\", \"rerank_priorities\", \"overseer_status\", \"overseer_start\", \"overseer_restart\", \"overseer_ask\", \"inbox_brief\", \"brief_action\", \"queue_list\", \"queue_action\", \"inbox_act\", \"answer_question\", \"dismiss_question\", \"dismiss_item\", \"run_recovery\", \"set_workspace_spec\", \"set_task_trigger\", \"pr_controls\", \"browser_status\", \"trust_bypass_status\", \"release_notes\", \"updates_status\", \"check_updates\", \"set_updates\", \"install_update\", \"make_main_agent\", \"retry_move\", \"report_issue\", \"report_send\", \"ai_rename\", \"catch_up_deck\", \"context_requests\", \"ask_context\", \"context_reply\"];",
18
+ "export const TOOL_NAMES = [\"workspace_status\", \"sync_workspace\", \"enroll_workspace\", \"register_pr\", \"exclude_stack\", \"update_obligation\", \"acknowledge_batch\", \"ask_question\", \"record_answer\", \"withdraw_question\", \"set_spec\", \"link_item\", \"unlink_item\", \"link_items\", \"set_linked_items\", \"workspace_about\", \"agent_settings\", \"needs_you\", \"declare_done\", \"list_prs\", \"add_reviewers\", \"enable_merge_when_ready\", \"disable_merge_when_ready\", \"send_repairs\", \"set_auto_send\", \"clear_hold\", \"retry_batch\", \"inbox_list\", \"sign_off\", \"snooze_workspace\", \"set_finish_flags\", \"set_priorities\", \"agent_digest\", \"route_candidates\", \"send_to_agent\", \"start_workspace\", \"display_settings\", \"set_display\", \"follow_settings\", \"set_follow_settings\", \"project_settings\", \"set_project_tracking\", \"pr_workflow\", \"set_pr_workflow\", \"reviewer_settings\", \"reviewer_suggestions\", \"save_reviewers\", \"set_agent_setting\", \"set_wait_for_jobs\", \"onboarding_status\", \"onboarding_checks\", \"set_onboarding\", \"rank_status\", \"rerank_priorities\", \"overseer_status\", \"overseer_start\", \"overseer_restart\", \"overseer_ask\", \"inbox_brief\", \"brief_action\", \"queue_list\", \"queue_action\", \"inbox_act\", \"answer_question\", \"dismiss_question\", \"dismiss_item\", \"run_recovery\", \"set_workspace_spec\", \"set_task_trigger\", \"pr_controls\", \"browser_status\", \"trust_bypass_status\", \"release_notes\", \"updates_status\", \"check_updates\", \"set_updates\", \"install_update\", \"make_main_agent\", \"retry_move\", \"report_issue\", \"report_send\", \"ai_rename\", \"catch_up_deck\", \"context_requests\", \"ask_context\", \"context_reply\", \"wait_for_checks\"];",
19
19
  "const toolPattern = new RegExp(`(?<![\\\\w])(${TOOL_NAMES.join(\"|\")})(?![\\\\w])`, \"g\");",
20
20
  "/** Names Follow-up's tools the way this agent has them. */",
21
21
  "export function named(text, isNative = native) { return isNative ? text.replace(toolPattern, \"follow_$1\") : text; }",
@@ -126,6 +126,32 @@ export const hookSource: string = [
126
126
  "export const NO_REVIEW_MERGE = \"This repository has no review: merge your own PR once CI is green, without asking the developer. Archiving remains the developer's action.\";",
127
127
  "/** Who merges, closing the batch paragraph: the developer (team review, unchanged text), or the agent in a No review repository. */",
128
128
  "export const mergeLine = workflow => workflow?.noReview ? NO_REVIEW_MERGE : \"Merging and archiving remain the developer's actions.\";",
129
+ "/**",
130
+ " * Wait for checks (docs/wait-for-checks.md). One SessionStart line for root agents, and a PostToolUse nudge when a",
131
+ " * shell command polls GitHub for CI: said at most once per turn, never blocking (the-polling-nudge-never-blocks).",
132
+ " * The hook already runs on every PostToolUse (no matcher), so this costs no new process.",
133
+ " */",
134
+ "export const checksLine = \"To wait for CI, don't poll GitHub (gh pr checks --watch, gh run watch, sleep loops over gh): call wait_for_checks with the PR after pushing and end your turn; Follow-up messages you when the checks finish.\";",
135
+ "export const pollNudge = \"That command polls GitHub for CI, which spends the developer's shared GitHub budget. Stop it, call wait_for_checks with the PR (no prs = every open PR of this workspace) and end your turn: Follow-up messages you once when the checks finish, from reads it already makes. A single gh pr checks to look once is fine.\";",
136
+ "const SHELL_TOOL = /(bash|shell|exec_command|write_stdin|monitor|terminal)/i;",
137
+ "const GH_QUERY = /\\bgh\\s+(?:pr\\s+(?:checks|view|status)\\b|run\\s+(?:list|view)\\b|api\\b[^\\n;|&]*(?:graphql|\\/pulls\\b|check-runs|check-suites|\\/statuses\\b|\\/status\\b|\\/actions\\/runs))/;",
138
+ "const GH_WATCH = /\\bgh\\s+(?:pr\\s+checks\\b[^\\n;|&]*--watch\\b|run\\s+watch\\b)/;",
139
+ "// A for loop over PRs (reading each one once) isn't polling; a wait between reads is.",
140
+ "const LOOP = /(?:^|[\\s;&|({])(?:while|until)\\b[\\s\\S]*?\\bdo\\b|\\bsleep\\s+\\d|\\bwatch\\s+-n\\b|\\bsetInterval\\b|\\btime\\.sleep\\(/;",
141
+ "/** The text a tool call runs: every string in its input (Bash command, Codex cmd, Monitor's command, a script). */",
142
+ "function commandText(input) {",
143
+ " const out = [];",
144
+ " const walk = v => { if (typeof v === \"string\") out.push(v); else if (Array.isArray(v)) v.forEach(walk); else if (v && typeof v === \"object\") Object.values(v).forEach(walk); };",
145
+ " walk(input);",
146
+ " return out.join(\"\\n\").slice(0, 20_000);",
147
+ "}",
148
+ "/** Whether a shell tool call polls GitHub for CI: a watch command, or a loop or sleep around a gh status read. */",
149
+ "export function pollsGithub(tool, input) {",
150
+ " if (!SHELL_TOOL.test(String(tool ?? \"\"))) return false;",
151
+ " const text = commandText(input);",
152
+ " if (GH_WATCH.test(text)) return true;",
153
+ " return GH_QUERY.test(text) && LOOP.test(text);",
154
+ "}",
129
155
  "const quote = value => \"'\" + value.replaceAll(\"'\", \"'\\\\''\") + \"'\";",
130
156
  "async function json(path) { return JSON.parse(await readFile(path, \"utf8\")); }",
131
157
  "async function save(path, value) {",
@@ -153,7 +179,7 @@ export const hookSource: string = [
153
179
  " \"When a decision needs the developer, call ask_question with a short title, the question, lettered options with what each means, and your recommendation; mark it big only when building ahead would leave this computer, set something others rely on, or most remaining work depends on it. Follow the question mode in its reply. Ask each decision once: asking it again returns the open question, and at a turn's end you point at it (needs_you questions=[\\\"Q<n>\\\"]) instead of restating it. Answers arrive as messages starting \\\"Follow-up answer Q<n>\\\" and are already recorded; several decisions from one card arrive together in one message, one line per decision, with skipped ones marked \\\"skipped\\\" and still open. An answer of Something else — \\\"…\\\" means none of your options: the quoted words are the developer's answer. Every card already offers Something else, so don't add an Other option. If the developer answers in chat, call record_answer (choice \\\"other\\\" with words when it matches none of your options). Withdraw questions that stop mattering. \" + ENVELOPE_GUIDANCE,",
154
180
  " linkInstruction,",
155
181
  " \"If you keep a Claude artifact (or doc) summarizing this workspace's goal, decisions and status, register its link once with set_spec after the first publish. Republish to the same URL; call set_spec again only if the link changes.\",",
156
- " \"Keep actual follow-up tasks current with update_obligation: production behavior checks, migrations and decisions, with concise titles, PR dependencies and evidence. Do not add merge/approval/deploy checklist tasks. Deployment-dependent work waits for verified serving revisions and existing production permissions. A task waiting on a PR or another agent is status=waiting; blocked is only for the developer, with ask set to the question they must answer.\",",
182
+ " \"Keep actual follow-up tasks current with update_obligation: production behavior checks, migrations and decisions, with concise titles, PR dependencies and evidence. Do not add merge/approval/deploy checklist tasks. Deployment-dependent work waits for verified serving revisions and existing production permissions. A task waiting on a PR or another agent is status=waiting; blocked is only for the developer. One decision, one card: ask it once with ask_question (task set to the task), then mark the task blocked with question=\\\"Q<n>\\\"; ask= is only for a decision you haven't asked. Once it is answered, act on the answer and move the task.\",",
157
183
  " \"Stakeholder replies are follow-up too. When asked to update a requester, capture the original Slack threadUrl, recipient and explicit developer authorization in the task's communication field; referenced messages alone do not authorize posting. Use a concise progress task now and, when needed, a verify-and-reply task with purpose=verified after the relevant deployed PRs. Read existing thread replies and refresh evidence before posting; distinguish fixed, deployed and verified. Record the actual sent replyUrl and result before marking done. If posting is unavailable or its outcome is uncertain, keep the task blocked and check the thread before any retry; never claim a draft was sent. Auto authorizes delivery to you, not external messages. Communication-only requests do not authorize repairs, benchmarks, migrations or other production writes.\",",
158
184
  " \"Tasks are manual unless explicitly scheduled with trigger={event:\\\"now\\\"|\\\"merge\\\"|\\\"deploy\\\",delayDays:0}. Only set a trigger from the developer\\u2019s requested timing; never infer timing from a title or enable_follow_up alone. Merge/deploy triggers require owned afterPrs; delayDays=14 waits fourteen days after the last dependency event. Now requires no PR dependencies or delay. Deployment timing starts at the first verified fully serving observation and remains conservative when history is unknown. Preserve existing trigger fields on updates; trigger=null makes a task manual. Auto controls delivery, not timing or production permissions.\",",
159
185
  " batchParagraph(workflow) + \" For post-deploy tasks, verify the currently serving revision contains every dependency and record behavioral results separately. Acknowledge the header's batch ID with acknowledge_batch before finishing: completed with the result, or blocked with the reason (humanOnly=true when only a person can move it, such as a stale review the reviewer must re-review or dismiss). Verify the entire goal and post-merge work before declare_done; acknowledge a completion batch first. \" + mergeLine(workflow),",
@@ -249,7 +275,7 @@ export const hookSource: string = [
249
275
  " return;",
250
276
  " }",
251
277
  " const context = () => instructions(lease, contributor, workflow);",
252
- " const sessionText = async () => [workspace ? context() : null, ...await nativeExtras(brief), ...await waitExtras()].filter(Boolean).join(\"\\n\\n\");",
278
+ " const sessionText = async () => [workspace ? context() : null, ...await nativeExtras(brief), ...await waitExtras(), workspace || env(\"ROOT\") === \"1\" ? named(checksLine) : null].filter(Boolean).join(\"\\n\\n\");",
253
279
  " const name = event.hook_event_name;",
254
280
  " if (![\"SessionStart\", \"UserPromptSubmit\", \"PostToolUse\", \"Stop\"].includes(name)) return;",
255
281
  " const session = createHash(\"sha256\").update(String(event.session_id ?? agentId)).digest(\"hex\").slice(0, 24);",
@@ -274,8 +300,11 @@ export const hookSource: string = [
274
300
  " if (name === \"PostToolUse\") {",
275
301
  " // Said once per session per worker: the tools stay detached until the session reopens.",
276
302
  " const notice = detached && turn?.detachedNotice !== instance.instance;",
303
+ " // Once per turn (the turn's start, or the session's when no prompt was seen), and never a block.",
304
+ " const turnId = turn?.startedAt || 0;",
305
+ " const polling = (workspace || env(\"ROOT\") === \"1\") && turn?.pollNudged !== turnId && pollsGithub(event.tool_name, event.tool_input);",
277
306
  " if (!workspace) {",
278
- " if (notice) { await save(path, { ...turn, detachedNotice: instance.instance }); emit(detachedNotice); }",
307
+ " if (notice || polling) { await save(path, { ...turn, ...(notice ? { detachedNotice: instance.instance } : {}), ...(polling ? { pollNudged: turnId } : {}) }); emit([notice ? detachedNotice : null, polling ? named(pollNudge) : null].filter(Boolean).join(\"\\n\\n\")); }",
279
308
  " return;",
280
309
  " }",
281
310
  " const tool = String(event.tool_name ?? \"\");",
@@ -288,8 +317,8 @@ export const hookSource: string = [
288
317
  " // sync record the RPC handler wrote rather than tool names.",
289
318
  " const now = Date.now();",
290
319
  " const callStart = turn?.lastToolAt || turn?.startedAt || now;",
291
- " await save(path, { ...turn, startedAt: turn?.startedAt ?? (dirty ? callStart : 0), stopped: turn?.stopped ?? false, ...(dirty ? { dirtyAt: callStart } : {}), quietRevision, lastToolAt: now, ...(notice ? { detachedNotice: instance.instance } : {}) });",
292
- " const text = [upgrade ? quietInstruction : null, notice ? detachedNotice : null].filter(Boolean).join(\"\\n\\n\");",
320
+ " await save(path, { ...turn, startedAt: turn?.startedAt ?? (dirty ? callStart : 0), stopped: turn?.stopped ?? false, ...(dirty ? { dirtyAt: callStart } : {}), quietRevision, lastToolAt: now, ...(notice ? { detachedNotice: instance.instance } : {}), ...(polling ? { pollNudged: turnId } : {}) });",
321
+ " const text = [upgrade ? quietInstruction : null, notice ? detachedNotice : null, polling ? named(pollNudge) : null].filter(Boolean).join(\"\\n\\n\");",
293
322
  " if (text) emit(text);",
294
323
  " return;",
295
324
  " }",
@@ -26,9 +26,9 @@ export const mcpSource: string = [
26
26
  " [\"enroll_workspace\", \"Refine this developer-activated workspace's goal. Ownership is initialized by Track this workspace or the project’s default-tracking setting. This tool cannot activate another workspace. Never ask the developer to enter this. Keep the goal concise; new scope reopens completion.\", \"follow.enroll\", { goal: string }, [\"goal\"]],",
27
27
  " [\"register_pr\", \"Register a PR produced by this workspace. Call after every submission. Register parents first; repeat to update its stack or parent after restacking. Supply a disposition for a deliberately closed PR. Set agentMerges: true when you merge this PR yourself (no human review): Follow-up then never asks the developer to add reviewers or merge it, and the workspace reads as waiting on you; set it false to hand the merge back. In a repository set to No review (set_pr_workflow review \\\"none\\\") every PR counts as agentMerges unless you set it false.\", \"follow.register-pr\", { repo: string, number: integer, stack: string, parentNumber: { type: [\"integer\", \"null\"], minimum: 1 }, disposition: string, agentMerges: boolean }, [\"repo\", \"number\", \"stack\"]],",
28
28
  " [\"exclude_stack\", \"Correct an unrelated stack registration. Preserve its PRs and requirements in an exclusion audit; future registration is blocked. reason must cite the scope/ownership evidence. obligationIds may include related tasks without PR dependencies. Keep external dependencies separate from owned work.\", \"follow.exclude-stack\", { stack: string, reason: string, obligationIds: array }, [\"stack\", \"reason\"]],",
29
- " [\"update_obligation\", \"Record concrete follow-up: verification, migrations, decisions or stakeholder replies. Never add approve/merge/deploy checklist tasks. afterPrs uses owner/repo#number keys. Tasks are manual unless explicitly scheduled with trigger={event:\\\"now\\\"|\\\"merge\\\"|\\\"deploy\\\",delayDays:0}. Only set a trigger from the developer’s requested timing; never infer timing from a title or enable_follow_up alone. Merge/deploy triggers require owned afterPrs; delayDays=14 waits fourteen days after the last dependency event. Now requires no PR dependencies or delay. Deployment timing starts at the first verified fully serving observation and remains conservative when history is unknown. Preserve existing trigger fields on updates; trigger=null makes a task manual. Auto controls delivery, not timing or production permissions. For Slack replies, communication records the original threadUrl, recipient, purpose (progress or verified), explicit developer authorization and sent replyUrl. Empty authorization never queues a reply; Auto does not authorize external posts. Use a verify-and-reply task after deployment for the final update. Read the thread first; mark blocked when posting is unavailable or uncertain, never treat a draft as sent. Done requires replyUrl and evidence; preserve fields when updating. status=working records you as the agent doing it; pass workingAgentId when another agent (your subagent) is.\", \"follow.obligation\", { id: string, workingAgentId: string, title: string, status: { type: \"string\", enum: [\"pending\", \"waiting\", \"working\", \"blocked\", \"done\", \"waived\"] }, afterPrs: array, dependencyStage: { type: \"string\", enum: [\"merged\", \"deployed\"] }, evidence: string, ask: { ...string, description: \"With blocked: the question the developer must answer (waiting on a PR or agent is status=waiting).\" }, enable_follow_up: boolean, communication, trigger }, [\"title\", \"status\"]],",
29
+ " [\"update_obligation\", \"Record concrete follow-up: verification, migrations, decisions or stakeholder replies. Never add approve/merge/deploy checklist tasks. afterPrs uses owner/repo#number keys. Tasks are manual unless explicitly scheduled with trigger={event:\\\"now\\\"|\\\"merge\\\"|\\\"deploy\\\",delayDays:0}. Only set a trigger from the developer’s requested timing; never infer timing from a title or enable_follow_up alone. Merge/deploy triggers require owned afterPrs; delayDays=14 waits fourteen days after the last dependency event. Now requires no PR dependencies or delay. Deployment timing starts at the first verified fully serving observation and remains conservative when history is unknown. Preserve existing trigger fields on updates; trigger=null makes a task manual. Auto controls delivery, not timing or production permissions. For Slack replies, communication records the original threadUrl, recipient, purpose (progress or verified), explicit developer authorization and sent replyUrl. Empty authorization never queues a reply; Auto does not authorize external posts. Use a verify-and-reply task after deployment for the final update. Read the thread first; mark blocked when posting is unavailable or uncertain, never treat a draft as sent. Done requires replyUrl and evidence; preserve fields when updating. status=working records you as the agent doing it; pass workingAgentId when another agent (your subagent) is.\", \"follow.obligation\", { id: string, workingAgentId: string, title: string, status: { type: \"string\", enum: [\"pending\", \"waiting\", \"working\", \"blocked\", \"done\", \"waived\"] }, afterPrs: array, dependencyStage: { type: \"string\", enum: [\"merged\", \"deployed\"] }, evidence: string, ask: { ...string, description: \"With blocked, only for a decision you haven't asked: the question the developer must answer (waiting on a PR or agent is status=waiting). Asked already with ask_question? Pass question instead.\" }, question: { type: \"string\", pattern: \"^Q\\\\d+$\", description: \"With blocked: the question (Q<n>) this task waits on, asked with ask_question (task set to this task). No second card is made.\" }, enable_follow_up: boolean, communication, trigger }, [\"title\", \"status\"]],",
30
30
  " [\"acknowledge_batch\", \"Record a follow-up result. Complete only after verifying all tasks; blocked surfaces the reason to the developer. Blocked with humanOnly=true when nothing is left for an agent and only a person can move it (a reviewer must re-review or dismiss a stale review, access must be granted): the developer gets a PR item, not an agent failure. Always acknowledge before ending a repair turn. Keep the result within 2000 characters.\", \"follow.acknowledge\", { batchId: string, outcome: { type: \"string\", enum: [\"completed\", \"blocked\"] }, result: { ...string, maxLength: 2000 }, humanOnly: { type: \"boolean\" } }, [\"batchId\", \"outcome\", \"result\"]],",
31
- " [\"ask_question\", \"Ask the developer a decision you can't make yourself. Give a short title, the question, lettered options A, B, C… with what each means for them, and recommend the option you'd pick. Set big only when building ahead would send something off this computer, set something people or programs outside the repo rely on, or most remaining work would build on it. Link a PR (owner/repo#number) or task id when it is about one. The reply says the question mode and exactly what to do until the answer arrives. Asking something already open returns the open question (\\\"Already open as Q18\\\") instead of a second one; to change an open question's options, ask again with supersedes=\\\"Q18\\\". At the end of the turn point at it with needs_you questions=[\\\"Q18\\\"], don't restate it. URLs and owner/repo#123 in the question, background and options are clickable for the developer. Every card already ends with a built-in \\\"Something else\\\" choice where the developer writes their own answer; don't add an \\\"Other\\\" option yourself.\", \"follow.ask-question\", { title: { ...string, maxLength: 120 }, question: { ...string, maxLength: 2000 }, options: { type: \"array\", maxItems: 26, items: { type: \"object\", properties: { letter: { type: \"string\", pattern: \"^[A-Z]$\" }, label: { ...string, maxLength: 200 }, consequence: { ...string, maxLength: 600 } }, required: [\"letter\", \"label\"], additionalProperties: false } }, recommend: string, big: string, background: string, links: { type: \"array\", maxItems: 10, items: { type: \"object\", properties: { url: string, path: string, label: string }, additionalProperties: false } }, pr: string, task: string, supersedes: { type: \"string\", pattern: \"^Q\\\\d+$\" } }, [\"title\", \"question\"]],",
31
+ " [\"ask_question\", \"Ask the developer a decision you can't make yourself. Give a short title, the question, lettered options A, B, C… with what each means for them, and recommend the option you'd pick. Set big only when building ahead would send something off this computer, set something people or programs outside the repo rely on, or most remaining work would build on it. Link a PR (owner/repo#number) or task id when it is about one. When a task waits on this decision, set task, then mark it blocked with update_obligation question=\\\"Q<n>\\\" (not ask): one decision, one card. The reply says the question mode and exactly what to do until the answer arrives. Asking something already open returns the open question (\\\"Already open as Q18\\\") instead of a second one; to change an open question's options, ask again with supersedes=\\\"Q18\\\". At the end of the turn point at it with needs_you questions=[\\\"Q18\\\"], don't restate it. URLs and owner/repo#123 in the question, background and options are clickable for the developer. Every card already ends with a built-in \\\"Something else\\\" choice where the developer writes their own answer; don't add an \\\"Other\\\" option yourself.\", \"follow.ask-question\", { title: { ...string, maxLength: 120 }, question: { ...string, maxLength: 2000 }, options: { type: \"array\", maxItems: 26, items: { type: \"object\", properties: { letter: { type: \"string\", pattern: \"^[A-Z]$\" }, label: { ...string, maxLength: 200 }, consequence: { ...string, maxLength: 600 } }, required: [\"letter\", \"label\"], additionalProperties: false } }, recommend: string, big: string, background: string, links: { type: \"array\", maxItems: 10, items: { type: \"object\", properties: { url: string, path: string, label: string }, additionalProperties: false } }, pr: string, task: string, supersedes: { type: \"string\", pattern: \"^Q\\\\d+$\" } }, [\"title\", \"question\"]],",
32
32
  " [\"record_answer\", \"Record the developer's answer when they answered a question in chat instead of in Follow-up. choice is an option letter, \\\"other\\\" when they chose none of your options (words is then required: their answer), or their short answer when there were no options; words is what they said.\", \"follow.record-answer\", { id: string, choice: string, words: string }, [\"id\", \"choice\"]],",
33
33
  " [\"context_reply\", \"Answer the developer's More context ask with the requestId it gave: { requestId, text }, plain words. Only when asked.\", \"follow.context-reply\", { requestId: { ...string, maxLength: 80 }, text: { ...string, minLength: 1, maxLength: 4000 } }, [\"requestId\", \"text\"]],",
34
34
  " [\"withdraw_question\", \"Withdraw a question that no longer matters, with a short reason.\", \"follow.withdraw-question\", { id: string, reason: string }, [\"id\", \"reason\"]],",
@@ -36,6 +36,7 @@ export const mcpSource: string = [
36
36
  " [\"link_item\", \"Link what this workspace's work is about: the Linear issue, Slack thread, doc or artifact you started from or opened for it. ref is its URL or Linear key; why is one short line. Don't link things you only mention. A PR isn't a linked item: register it with register_pr. An unknown Linear key is refused.\", \"follow.link-item\", { ref: { ...string, maxLength: 2000 }, why: { ...string, maxLength: 140 }, title: { ...string, maxLength: 200 } }, [\"ref\"]],",
37
37
  " [\"unlink_item\", \"Remove a linked item that isn't this workspace's (ref: its URL or key; reason: why). It stays out: nothing adds it back unless the developer does.\", \"follow.unlink-item\", { ref: { ...string, maxLength: 2000 }, reason: { ...string, maxLength: 200 } }, [\"ref\", \"reason\"]],",
38
38
  " [\"needs_you\", \"Call once at the end of a turn, just before your final reply: what the developer has to do next. ask is one line (≤120). kind: decision (give decisions with 2–5 options, a consequence each and recommend=<option index>; with several decisions the developer answers them together and you get one message with a line per decision, skipped ones marked as skipped; a decision that is already an open question goes in questions=[\\\"Q18\\\"] instead, never restated), action (something only they can do: merge, approve, log in, run or send), review (a PR to review and merge; link it with pr), or done (\\\"Nothing needed. <what you finished>.\\\": nothing for the developer, won't flag you). context ≤400 chars: only what they need to decide. Never blocks and never changes what you should do next.\", \"follow.needs-you\", { ask: { ...string, minLength: 1, maxLength: 120 }, kind: { type: \"string\", enum: [\"decision\", \"action\", \"review\", \"done\"] }, decisions: { type: \"array\", maxItems: 3, items: { type: \"object\", properties: { question: { ...string, minLength: 1, maxLength: 200 }, options: { type: \"array\", minItems: 2, maxItems: 5, items: { type: \"object\", properties: { label: { ...string, minLength: 1, maxLength: 60 }, consequence: { ...string, maxLength: 160 } }, required: [\"label\"], additionalProperties: false } }, recommend: { type: \"integer\", minimum: 0, maximum: 4 } }, required: [\"question\"], additionalProperties: false } }, questions: { type: \"array\", maxItems: 3, items: { type: \"string\", pattern: \"^Q\\\\d+$\" } }, context: { ...string, maxLength: 400 }, links: { type: \"array\", maxItems: 4, items: { type: \"object\", properties: { label: string, url: string, path: string, pr: string }, required: [\"label\"], additionalProperties: false } } }, [\"ask\", \"kind\"]],",
39
+ " [\"wait_for_checks\", \"Wait for CI without polling GitHub. Call it after pushing, with prs (URLs, owner/repo#N or numbers; none = every open PR of this workspace), then end your turn: Follow-up messages you once when the checks on the current head finish (passed, or which failed), or the PR merges, closes or conflicts. Answers at once when they already have. cancel=true stops waiting. Never loop on gh pr checks, gh run watch or gh api.\", \"follow.wait-for-checks\", { prs: array, minutes: { type: \"integer\", minimum: 1, maximum: 720 }, cancel: boolean }, []],",
39
40
  " [\"declare_done\", \"Declare that the workspace goal is fulfilled. Live PR status and remaining obligations are checked. The reply's `next` says what is missing and whether it is yours to fix; follow it and do not repeat the call when nothing is yours to fix. A deploy Follow-up cannot confirm does not block Done; it is noted. Calling again after Done changes nothing. Done labels the workspace but never archives it.\", \"follow.done\", { summary: string }, [\"summary\"]],",
40
41
  "];",
41
42
  "",
@@ -154,8 +155,10 @@ export const mcpSource: string = [
154
155
  " // Action tools: root agents (tracked main or untracked) while Follow-up runs; never recovery or contributors.",
155
156
  " // Contributors get make_main_agent only (its claim rules apply); recovery sessions get none.",
156
157
  " const acting = !actions || recovery ? [] : contributor ? actionTools.filter(t => t[0] === \"make_main_agent\" || t[0] === \"report_issue\") : actionTools;",
157
- " if (briefOnly) return [...(brief ? tools.filter(t => t[0] === \"needs_you\") : []), ...acting];",
158
- " return [...tools.filter(t => t[0] === \"needs_you\" ? brief && !recovery && !contributor : contributor ? [\"workspace_status\", \"register_pr\", \"sync_workspace\", \"link_item\", \"unlink_item\"].includes(t[0]) : !recovery || ![\"declare_done\", \"sync_workspace\", \"ask_question\", \"record_answer\", \"withdraw_question\", \"set_spec\", \"link_item\", \"unlink_item\", \"context_reply\"].includes(t[0])), ...acting];",
158
+ " // wait_for_checks: every root agent, tracked or not (an untracked one learns where else to wait); never recovery.",
159
+ " const waiting = actions && !recovery ? tools.filter(t => t[0] === \"wait_for_checks\") : [];",
160
+ " if (briefOnly) return [...(brief ? tools.filter(t => t[0] === \"needs_you\") : []), ...waiting, ...acting];",
161
+ " return [...tools.filter(t => t[0] === \"needs_you\" ? brief && !recovery && !contributor : t[0] === \"wait_for_checks\" ? !recovery : contributor ? [\"workspace_status\", \"register_pr\", \"sync_workspace\", \"link_item\", \"unlink_item\"].includes(t[0]) : !recovery || ![\"declare_done\", \"sync_workspace\", \"ask_question\", \"record_answer\", \"withdraw_question\", \"set_spec\", \"link_item\", \"unlink_item\", \"context_reply\"].includes(t[0])), ...acting];",
159
162
  "}",
160
163
  "/** Whether this session may call needs_you: launched as a root agent (FOLLOW_UP_BRIEF) and the inbox is on. */",
161
164
  "async function briefEnabled() {",
@@ -290,7 +293,7 @@ export const mcpSource: string = [
290
293
  " const workspaceId = result.id;",
291
294
  " if (tool === \"enroll_workspace\") return { workspaceId, goal: result.goal };",
292
295
  " if (tool === \"register_pr\") { const p = result.prs.find(p => p.key === `${input.repo}#${input.number}`); return { workspaceId, pr: { key: p.key, stack: p.stack, parent: p.parent, disposition: p.disposition } }; }",
293
- " if (tool === \"update_obligation\") return { workspaceId, obligation: result.obligations.find(o => o.id === result.updatedObligationId) };",
296
+ " if (tool === \"update_obligation\") return { workspaceId, obligation: result.obligations.find(o => o.id === result.updatedObligationId), ...(result.note ? { note: result.note } : {}) };",
294
297
  " if (tool === \"acknowledge_batch\") { const b = result.batches.find(b => b.id === input.batchId); return { workspaceId, batch: { id: b.id, state: b.state, result: b.result } }; }",
295
298
  " if (tool === \"exclude_stack\") { const s = result.excludedStacks.find(s => s.name === input.stack); return { workspaceId, excludedStack: { name: s.name, reason: s.reason, prs: s.prs.map(p => p.key) } }; }",
296
299
  " return result;",
package/server/mcp.mjs CHANGED
@@ -24,9 +24,9 @@ const tools = [
24
24
  ["enroll_workspace", "Refine this developer-activated workspace's goal. Ownership is initialized by Track this workspace or the project’s default-tracking setting. This tool cannot activate another workspace. Never ask the developer to enter this. Keep the goal concise; new scope reopens completion.", "follow.enroll", { goal: string }, ["goal"]],
25
25
  ["register_pr", "Register a PR produced by this workspace. Call after every submission. Register parents first; repeat to update its stack or parent after restacking. Supply a disposition for a deliberately closed PR. Set agentMerges: true when you merge this PR yourself (no human review): Follow-up then never asks the developer to add reviewers or merge it, and the workspace reads as waiting on you; set it false to hand the merge back. In a repository set to No review (set_pr_workflow review \"none\") every PR counts as agentMerges unless you set it false.", "follow.register-pr", { repo: string, number: integer, stack: string, parentNumber: { type: ["integer", "null"], minimum: 1 }, disposition: string, agentMerges: boolean }, ["repo", "number", "stack"]],
26
26
  ["exclude_stack", "Correct an unrelated stack registration. Preserve its PRs and requirements in an exclusion audit; future registration is blocked. reason must cite the scope/ownership evidence. obligationIds may include related tasks without PR dependencies. Keep external dependencies separate from owned work.", "follow.exclude-stack", { stack: string, reason: string, obligationIds: array }, ["stack", "reason"]],
27
- ["update_obligation", "Record concrete follow-up: verification, migrations, decisions or stakeholder replies. Never add approve/merge/deploy checklist tasks. afterPrs uses owner/repo#number keys. Tasks are manual unless explicitly scheduled with trigger={event:\"now\"|\"merge\"|\"deploy\",delayDays:0}. Only set a trigger from the developer’s requested timing; never infer timing from a title or enable_follow_up alone. Merge/deploy triggers require owned afterPrs; delayDays=14 waits fourteen days after the last dependency event. Now requires no PR dependencies or delay. Deployment timing starts at the first verified fully serving observation and remains conservative when history is unknown. Preserve existing trigger fields on updates; trigger=null makes a task manual. Auto controls delivery, not timing or production permissions. For Slack replies, communication records the original threadUrl, recipient, purpose (progress or verified), explicit developer authorization and sent replyUrl. Empty authorization never queues a reply; Auto does not authorize external posts. Use a verify-and-reply task after deployment for the final update. Read the thread first; mark blocked when posting is unavailable or uncertain, never treat a draft as sent. Done requires replyUrl and evidence; preserve fields when updating. status=working records you as the agent doing it; pass workingAgentId when another agent (your subagent) is.", "follow.obligation", { id: string, workingAgentId: string, title: string, status: { type: "string", enum: ["pending", "waiting", "working", "blocked", "done", "waived"] }, afterPrs: array, dependencyStage: { type: "string", enum: ["merged", "deployed"] }, evidence: string, ask: { ...string, description: "With blocked: the question the developer must answer (waiting on a PR or agent is status=waiting)." }, enable_follow_up: boolean, communication, trigger }, ["title", "status"]],
27
+ ["update_obligation", "Record concrete follow-up: verification, migrations, decisions or stakeholder replies. Never add approve/merge/deploy checklist tasks. afterPrs uses owner/repo#number keys. Tasks are manual unless explicitly scheduled with trigger={event:\"now\"|\"merge\"|\"deploy\",delayDays:0}. Only set a trigger from the developer’s requested timing; never infer timing from a title or enable_follow_up alone. Merge/deploy triggers require owned afterPrs; delayDays=14 waits fourteen days after the last dependency event. Now requires no PR dependencies or delay. Deployment timing starts at the first verified fully serving observation and remains conservative when history is unknown. Preserve existing trigger fields on updates; trigger=null makes a task manual. Auto controls delivery, not timing or production permissions. For Slack replies, communication records the original threadUrl, recipient, purpose (progress or verified), explicit developer authorization and sent replyUrl. Empty authorization never queues a reply; Auto does not authorize external posts. Use a verify-and-reply task after deployment for the final update. Read the thread first; mark blocked when posting is unavailable or uncertain, never treat a draft as sent. Done requires replyUrl and evidence; preserve fields when updating. status=working records you as the agent doing it; pass workingAgentId when another agent (your subagent) is.", "follow.obligation", { id: string, workingAgentId: string, title: string, status: { type: "string", enum: ["pending", "waiting", "working", "blocked", "done", "waived"] }, afterPrs: array, dependencyStage: { type: "string", enum: ["merged", "deployed"] }, evidence: string, ask: { ...string, description: "With blocked, only for a decision you haven't asked: the question the developer must answer (waiting on a PR or agent is status=waiting). Asked already with ask_question? Pass question instead." }, question: { type: "string", pattern: "^Q\\d+$", description: "With blocked: the question (Q<n>) this task waits on, asked with ask_question (task set to this task). No second card is made." }, enable_follow_up: boolean, communication, trigger }, ["title", "status"]],
28
28
  ["acknowledge_batch", "Record a follow-up result. Complete only after verifying all tasks; blocked surfaces the reason to the developer. Blocked with humanOnly=true when nothing is left for an agent and only a person can move it (a reviewer must re-review or dismiss a stale review, access must be granted): the developer gets a PR item, not an agent failure. Always acknowledge before ending a repair turn. Keep the result within 2000 characters.", "follow.acknowledge", { batchId: string, outcome: { type: "string", enum: ["completed", "blocked"] }, result: { ...string, maxLength: 2000 }, humanOnly: { type: "boolean" } }, ["batchId", "outcome", "result"]],
29
- ["ask_question", "Ask the developer a decision you can't make yourself. Give a short title, the question, lettered options A, B, C… with what each means for them, and recommend the option you'd pick. Set big only when building ahead would send something off this computer, set something people or programs outside the repo rely on, or most remaining work would build on it. Link a PR (owner/repo#number) or task id when it is about one. The reply says the question mode and exactly what to do until the answer arrives. Asking something already open returns the open question (\"Already open as Q18\") instead of a second one; to change an open question's options, ask again with supersedes=\"Q18\". At the end of the turn point at it with needs_you questions=[\"Q18\"], don't restate it. URLs and owner/repo#123 in the question, background and options are clickable for the developer. Every card already ends with a built-in \"Something else\" choice where the developer writes their own answer; don't add an \"Other\" option yourself.", "follow.ask-question", { title: { ...string, maxLength: 120 }, question: { ...string, maxLength: 2000 }, options: { type: "array", maxItems: 26, items: { type: "object", properties: { letter: { type: "string", pattern: "^[A-Z]$" }, label: { ...string, maxLength: 200 }, consequence: { ...string, maxLength: 600 } }, required: ["letter", "label"], additionalProperties: false } }, recommend: string, big: string, background: string, links: { type: "array", maxItems: 10, items: { type: "object", properties: { url: string, path: string, label: string }, additionalProperties: false } }, pr: string, task: string, supersedes: { type: "string", pattern: "^Q\\d+$" } }, ["title", "question"]],
29
+ ["ask_question", "Ask the developer a decision you can't make yourself. Give a short title, the question, lettered options A, B, C… with what each means for them, and recommend the option you'd pick. Set big only when building ahead would send something off this computer, set something people or programs outside the repo rely on, or most remaining work would build on it. Link a PR (owner/repo#number) or task id when it is about one. When a task waits on this decision, set task, then mark it blocked with update_obligation question=\"Q<n>\" (not ask): one decision, one card. The reply says the question mode and exactly what to do until the answer arrives. Asking something already open returns the open question (\"Already open as Q18\") instead of a second one; to change an open question's options, ask again with supersedes=\"Q18\". At the end of the turn point at it with needs_you questions=[\"Q18\"], don't restate it. URLs and owner/repo#123 in the question, background and options are clickable for the developer. Every card already ends with a built-in \"Something else\" choice where the developer writes their own answer; don't add an \"Other\" option yourself.", "follow.ask-question", { title: { ...string, maxLength: 120 }, question: { ...string, maxLength: 2000 }, options: { type: "array", maxItems: 26, items: { type: "object", properties: { letter: { type: "string", pattern: "^[A-Z]$" }, label: { ...string, maxLength: 200 }, consequence: { ...string, maxLength: 600 } }, required: ["letter", "label"], additionalProperties: false } }, recommend: string, big: string, background: string, links: { type: "array", maxItems: 10, items: { type: "object", properties: { url: string, path: string, label: string }, additionalProperties: false } }, pr: string, task: string, supersedes: { type: "string", pattern: "^Q\\d+$" } }, ["title", "question"]],
30
30
  ["record_answer", "Record the developer's answer when they answered a question in chat instead of in Follow-up. choice is an option letter, \"other\" when they chose none of your options (words is then required: their answer), or their short answer when there were no options; words is what they said.", "follow.record-answer", { id: string, choice: string, words: string }, ["id", "choice"]],
31
31
  ["context_reply", "Answer the developer's More context ask with the requestId it gave: { requestId, text }, plain words. Only when asked.", "follow.context-reply", { requestId: { ...string, maxLength: 80 }, text: { ...string, minLength: 1, maxLength: 4000 } }, ["requestId", "text"]],
32
32
  ["withdraw_question", "Withdraw a question that no longer matters, with a short reason.", "follow.withdraw-question", { id: string, reason: string }, ["id", "reason"]],
@@ -34,6 +34,7 @@ const tools = [
34
34
  ["link_item", "Link what this workspace's work is about: the Linear issue, Slack thread, doc or artifact you started from or opened for it. ref is its URL or Linear key; why is one short line. Don't link things you only mention. A PR isn't a linked item: register it with register_pr. An unknown Linear key is refused.", "follow.link-item", { ref: { ...string, maxLength: 2000 }, why: { ...string, maxLength: 140 }, title: { ...string, maxLength: 200 } }, ["ref"]],
35
35
  ["unlink_item", "Remove a linked item that isn't this workspace's (ref: its URL or key; reason: why). It stays out: nothing adds it back unless the developer does.", "follow.unlink-item", { ref: { ...string, maxLength: 2000 }, reason: { ...string, maxLength: 200 } }, ["ref", "reason"]],
36
36
  ["needs_you", "Call once at the end of a turn, just before your final reply: what the developer has to do next. ask is one line (≤120). kind: decision (give decisions with 2–5 options, a consequence each and recommend=<option index>; with several decisions the developer answers them together and you get one message with a line per decision, skipped ones marked as skipped; a decision that is already an open question goes in questions=[\"Q18\"] instead, never restated), action (something only they can do: merge, approve, log in, run or send), review (a PR to review and merge; link it with pr), or done (\"Nothing needed. <what you finished>.\": nothing for the developer, won't flag you). context ≤400 chars: only what they need to decide. Never blocks and never changes what you should do next.", "follow.needs-you", { ask: { ...string, minLength: 1, maxLength: 120 }, kind: { type: "string", enum: ["decision", "action", "review", "done"] }, decisions: { type: "array", maxItems: 3, items: { type: "object", properties: { question: { ...string, minLength: 1, maxLength: 200 }, options: { type: "array", minItems: 2, maxItems: 5, items: { type: "object", properties: { label: { ...string, minLength: 1, maxLength: 60 }, consequence: { ...string, maxLength: 160 } }, required: ["label"], additionalProperties: false } }, recommend: { type: "integer", minimum: 0, maximum: 4 } }, required: ["question"], additionalProperties: false } }, questions: { type: "array", maxItems: 3, items: { type: "string", pattern: "^Q\\d+$" } }, context: { ...string, maxLength: 400 }, links: { type: "array", maxItems: 4, items: { type: "object", properties: { label: string, url: string, path: string, pr: string }, required: ["label"], additionalProperties: false } } }, ["ask", "kind"]],
37
+ ["wait_for_checks", "Wait for CI without polling GitHub. Call it after pushing, with prs (URLs, owner/repo#N or numbers; none = every open PR of this workspace), then end your turn: Follow-up messages you once when the checks on the current head finish (passed, or which failed), or the PR merges, closes or conflicts. Answers at once when they already have. cancel=true stops waiting. Never loop on gh pr checks, gh run watch or gh api.", "follow.wait-for-checks", { prs: array, minutes: { type: "integer", minimum: 1, maximum: 720 }, cancel: boolean }, []],
37
38
  ["declare_done", "Declare that the workspace goal is fulfilled. Live PR status and remaining obligations are checked. The reply's `next` says what is missing and whether it is yours to fix; follow it and do not repeat the call when nothing is yours to fix. A deploy Follow-up cannot confirm does not block Done; it is noted. Calling again after Done changes nothing. Done labels the workspace but never archives it.", "follow.done", { summary: string }, ["summary"]],
38
39
  ];
39
40
 
@@ -152,8 +153,10 @@ function toolList(recovery = env("RECOVERY") === "1", contributor = false, brief
152
153
  // Action tools: root agents (tracked main or untracked) while Follow-up runs; never recovery or contributors.
153
154
  // Contributors get make_main_agent only (its claim rules apply); recovery sessions get none.
154
155
  const acting = !actions || recovery ? [] : contributor ? actionTools.filter(t => t[0] === "make_main_agent" || t[0] === "report_issue") : actionTools;
155
- if (briefOnly) return [...(brief ? tools.filter(t => t[0] === "needs_you") : []), ...acting];
156
- return [...tools.filter(t => t[0] === "needs_you" ? brief && !recovery && !contributor : contributor ? ["workspace_status", "register_pr", "sync_workspace", "link_item", "unlink_item"].includes(t[0]) : !recovery || !["declare_done", "sync_workspace", "ask_question", "record_answer", "withdraw_question", "set_spec", "link_item", "unlink_item", "context_reply"].includes(t[0])), ...acting];
156
+ // wait_for_checks: every root agent, tracked or not (an untracked one learns where else to wait); never recovery.
157
+ const waiting = actions && !recovery ? tools.filter(t => t[0] === "wait_for_checks") : [];
158
+ if (briefOnly) return [...(brief ? tools.filter(t => t[0] === "needs_you") : []), ...waiting, ...acting];
159
+ return [...tools.filter(t => t[0] === "needs_you" ? brief && !recovery && !contributor : t[0] === "wait_for_checks" ? !recovery : contributor ? ["workspace_status", "register_pr", "sync_workspace", "link_item", "unlink_item"].includes(t[0]) : !recovery || !["declare_done", "sync_workspace", "ask_question", "record_answer", "withdraw_question", "set_spec", "link_item", "unlink_item", "context_reply"].includes(t[0])), ...acting];
157
160
  }
158
161
  /** Whether this session may call needs_you: launched as a root agent (FOLLOW_UP_BRIEF) and the inbox is on. */
159
162
  async function briefEnabled() {
@@ -288,7 +291,7 @@ function compact(tool, input, result) {
288
291
  const workspaceId = result.id;
289
292
  if (tool === "enroll_workspace") return { workspaceId, goal: result.goal };
290
293
  if (tool === "register_pr") { const p = result.prs.find(p => p.key === `${input.repo}#${input.number}`); return { workspaceId, pr: { key: p.key, stack: p.stack, parent: p.parent, disposition: p.disposition } }; }
291
- if (tool === "update_obligation") return { workspaceId, obligation: result.obligations.find(o => o.id === result.updatedObligationId) };
294
+ if (tool === "update_obligation") return { workspaceId, obligation: result.obligations.find(o => o.id === result.updatedObligationId), ...(result.note ? { note: result.note } : {}) };
292
295
  if (tool === "acknowledge_batch") { const b = result.batches.find(b => b.id === input.batchId); return { workspaceId, batch: { id: b.id, state: b.state, result: b.result } }; }
293
296
  if (tool === "exclude_stack") { const s = result.excludedStacks.find(s => s.name === input.stack); return { workspaceId, excludedStack: { name: s.name, reason: s.reason, prs: s.prs.map(p => p.key) } }; }
294
297
  return result;
@@ -3,11 +3,14 @@ import type { Obligation, Workspace } from "../shared/model";
3
3
  import { lifecycleOnly } from "../shared/follow-up";
4
4
  import { communicationKey, communicationSchema, replyRecorded, type Communication } from "../shared/communication";
5
5
  import type { TaskTrigger } from "../shared/task-trigger";
6
+ import { currentQuestion } from "../shared/questions";
6
7
 
7
8
  type Update = {
8
9
  id?: string; title: string; status: Obligation["status"]; afterPrs?: string[]; evidence?: string;
9
10
  /** While blocked: the developer's question. Kept across blocked updates that omit it; dropped when the task leaves blocked. */
10
11
  ask?: string;
12
+ /** While blocked: the question (Q7) the task waits on, instead of an ask. Its words become the ask, and it covers the task. */
13
+ question?: string;
11
14
  dependencyStage?: "merged" | "deployed"; enable_follow_up?: boolean; communication?: Pick<Communication, "threadUrl" | "recipient"> & Partial<Communication>;
12
15
  trigger?: TaskTrigger | null;
13
16
  /** The calling agent (from the daemon, never an argument). */
@@ -21,7 +24,17 @@ export function updateObligation(w: Workspace, input: Update): Obligation {
21
24
  if (id && !existing) throw new Error("Obligation does not exist. Omit id to add one.");
22
25
  const afterPrs = input.afterPrs ?? existing?.afterPrs ?? [];
23
26
  const evidence = input.evidence ?? existing?.evidence ?? "";
24
- const ask = status === "blocked" ? (input.ask ?? (existing?.status === "blocked" ? existing.ask : undefined))?.trim() || undefined : undefined;
27
+ // question="Q7": blocked on an open (or answered) question; its words become the ask and it covers the task, so the
28
+ // task makes no second card (one-decision-one-card).
29
+ const pointed = input.question ? currentQuestion(w.questions, input.question) : null;
30
+ if (input.question) {
31
+ if (status !== "blocked") throw new Error("question goes with status=blocked: the task waits on that question.");
32
+ if (input.ask) throw new Error("Pass question or ask, not both: question points at a question you already asked.");
33
+ if (!pointed) throw new Error(`No question ${input.question} in this workspace that still asks something. Ask it with ask_question (task set to this task) first.`);
34
+ if (pointed.taskRevision !== null) throw new Error(`${pointed.id} is a blocked task's own card. Point at a question you asked with ask_question.`);
35
+ }
36
+ const asked = pointed ? `${pointed.id}: ${pointed.question}`.slice(0, 1000) : input.ask;
37
+ const ask = status === "blocked" ? (asked ?? (existing?.status === "blocked" ? existing.ask : undefined))?.trim() || undefined : undefined;
25
38
  if (["done", "waived"].includes(status) && !(existing?.status === status ? evidence.trim() : input.evidence?.trim())) throw new Error("Completed or waived work requires result evidence.");
26
39
  if (afterPrs.some(key => !w.prs.some(p => p.key === key))) throw new Error("Register dependency PRs before referencing them.");
27
40
  if (lifecycleOnly({ title, afterPrs })) throw new Error("PR approval, merging and deployment belong in Pull requests. Record a concrete follow-up action such as verifying behavior after deployment, with afterPrs and dependencyStage=deployed.");
@@ -40,10 +53,13 @@ export function updateObligation(w: Workspace, input: Update): Obligation {
40
53
  if (existing) {
41
54
  const reopened = ["done", "waived", "blocked"].includes(existing.status) && ["pending", "waiting"].includes(status);
42
55
  if (reopened || existing.title !== title || JSON.stringify(existing.afterPrs) !== JSON.stringify(afterPrs) || existing.dependencyStage !== stage || JSON.stringify(existing.communication) !== JSON.stringify(destination) || JSON.stringify(existing.trigger) !== JSON.stringify(trigger) || existing.enable_follow_up !== followUp || (existing.ask ?? "") !== (ask ?? "")) existing.revision++;
56
+ // A changed ask is a new decision: what covered the old one doesn't cover it (syncTaskQuestions looks again).
57
+ if ((existing.ask ?? "") !== (ask ?? "")) delete existing.coveredBy;
43
58
  Object.assign(existing, record);
44
59
  if (ask) existing.ask = ask; else delete existing.ask;
60
+ if (pointed && ask) existing.coveredBy = pointed.id;
45
61
  return existing;
46
62
  }
47
- const added = { ...record, ...(ask ? { ask } : {}), id: randomUUID(), revision: 0 };
63
+ const added = { ...record, ...(ask ? { ask } : {}), ...(pointed && ask ? { coveredBy: pointed.id } : {}), id: randomUUID(), revision: 0 };
48
64
  w.obligations.push(added); return added;
49
65
  }