paseo-follow-up 1.4.0-beta.21 → 1.4.0-beta.22

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/README.md CHANGED
@@ -205,7 +205,7 @@ The choices live in `agents.json` in Follow-up's data folder. Anything missing o
205
205
  Install the beta:
206
206
 
207
207
  ```sh
208
- paseo plugin update follow-through --version 1.4.0-beta.21
208
+ paseo plugin update follow-through --version 1.4.0-beta.22
209
209
  # or, for a fresh install:
210
210
  paseo plugin install npm:paseo-follow-up@beta
211
211
  ```
package/client/panel.tsx CHANGED
@@ -9,6 +9,7 @@ import { BriefCard, type BriefDeps } from "./brief";
9
9
  import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
10
10
  import { controlRpc, refreshRpc, browserStatusRpc, recoverRpc, sendRpc, inboxBriefRpc } from "../shared/contracts";
11
11
  import { summary, type Workspace } from "../shared/model";
12
+ import { recentMainChange } from "../shared/home";
12
13
  import { followUpObligations, recoveryBatch } from "../shared/follow-up";
13
14
  import { settledForDisplay } from "../shared/presentation";
14
15
  import { ago, sendBlocker, shortRefs } from "../shared/attention";
@@ -221,6 +222,7 @@ function WorkspaceCard({ workspace: w, theme, compact, open, toggle, openAgent,
221
222
  </View>
222
223
  {openAgent && <Button theme={theme} compact={compact} icon="MessageSquare" title="Open" accessibilityLabel="Open main agent" onPress={() => openAgent(w.mainAgentId)} />}
223
224
  </View>
225
+ <MainChangeNotice workspace={w} theme={theme} compact={compact} />
224
226
  {(w.contributorAgentIds ?? []).map(id => <OtherRootAgent key={id} agentId={id} workspace={w} theme={theme} compact={compact} openAgent={openAgent} mainAgentId={w.mainAgentId} />)}
225
227
  </CardRow>
226
228
  <CardRow theme={theme} compact={compact}>
@@ -259,6 +261,33 @@ function useAgentTitle(agentId: string): string {
259
261
  return useAgent(agentId, a => a.title) || `Agent ${agentId.slice(0, 8)}`;
260
262
  }
261
263
 
264
+ /**
265
+ * "Took over from A · 5m ago · reason · Undo" under B's name, for a day after an agent or Follow-up moved the role
266
+ * (main-agent claim rule 5). Quiet: a meta line in this card, never a Needs-you item. Undo makes A main again
267
+ * through the same developer action as Make main agent, which no cooldown blocks.
268
+ */
269
+ function MainChangeNotice({ workspace: w, theme, compact }: { workspace: Workspace; theme: Theme; compact: boolean }) {
270
+ const c = theme.colors; const t = text(c);
271
+ const now = useNow(60_000);
272
+ const change = recentMainChange(w, now);
273
+ const from = useAgentTitle(change?.from ?? ""); const to = useAgentTitle(change?.to ?? "");
274
+ const control = useRpc(controlRpc); const cache = useQueryClient(); const toast = useToast();
275
+ const undo = useMutation({
276
+ mutationFn: () => control({ workspaceId: w.id, mainAgentId: change!.from }),
277
+ onSuccess: () => { void cache.invalidateQueries({ queryKey: workspaceKey(w.id) }); void cache.invalidateQueries({ queryKey: overviewKey }); toast.show(`${from} is the main agent again`, { variant: "success" }); },
278
+ onError: (e: Error) => toast.error(errorText(e)),
279
+ });
280
+ if (!change) return null;
281
+ const canUndo = w.enable_tracking && !w.archived && (w.contributorAgentIds ?? []).includes(change.from);
282
+ return <View style={{ flexDirection: "row", alignItems: "center", gap: 8, flexWrap: "wrap", marginTop: 10 }}>
283
+ {/* The new main's name is the card's title right above, so the line names only who it took over from. */}
284
+ <Text numberOfLines={3} accessibilityLabel={`${to} took over from ${from} ${ago(change.at, now)}${change.reason ? `. ${change.reason}` : ""}`} style={[t.meta, { flex: 1, minWidth: 200 }]}>
285
+ <Text style={{ color: c.foreground }}>Took over from {from}</Text> · {ago(change.at, now)}{change.reason ? ` · ${change.reason}` : ""}
286
+ </Text>
287
+ {canUndo && <Button theme={theme} compact={compact} kind="ghost" title="Undo" accessibilityLabel={`Undo: make ${from} the main agent again`} accessibilityHint={`Repairs, questions and Done move back to ${from}.`} loading={undo.isPending} disabled={undo.isPending} onPress={() => undo.mutate()} />}
288
+ </View>;
289
+ }
290
+
262
291
  function MainAgentName({ agentId, theme }: { agentId: string; theme: Theme }) {
263
292
  const t = text(theme.colors);
264
293
  return <Text numberOfLines={1} style={[t.meta, { color: theme.colors.foreground }]}>{useAgentTitle(agentId)}</Text>;
package/index.server.ts CHANGED
@@ -25,7 +25,7 @@ import { AgentActions, AGENT_TOOLS, controlWorkspace, type AgentTool } from "./s
25
25
  import { PaseoGateway, paseoHome, clientEntry, closeConnections, sessionGuardOwnsInterruption } from "./server/daemon";
26
26
  import { mcpSource } from "./server/mcp-source";
27
27
  import { excludeStack } from "./server/exclusions";
28
- import { applyHistory, applyDiscovery, extractHistory, markMainWork } from "./server/discovery";
28
+ import { applyHistory, applyDiscovery, extractHistory, mainWorkDue, markMainWork } from "./server/discovery";
29
29
  import { lifecycleOnly, recoveryBatch } from "./shared/follow-up";
30
30
  import { Deployments } from "./server/deployments";
31
31
  import { AgentHooks } from "./server/agent-hooks";
@@ -97,7 +97,7 @@ export default function contribute(server: PluginServerContext) {
97
97
  };
98
98
  const noteMainWork = async (agentId: string) => {
99
99
  // A cheap check on the snapshot first: almost every call has no open handover, so nothing is written.
100
- if (!(await store.snapshot()).workspaces.some(w => w.mainAgentId === agentId && w.handover && !w.handover.worked)) return;
100
+ if (!(await store.snapshot()).workspaces.some(w => mainWorkDue(w, agentId, Date.now()))) return;
101
101
  await store.mutate(state => { markMainWork(state, agentId); });
102
102
  };
103
103
  const store = new Store(directory, 1_000);
@@ -779,7 +779,9 @@ export default function contribute(server: PluginServerContext) {
779
779
  return result;
780
780
  },
781
781
  };
782
- const agentActions = new AgentActions({ store, prActions: actions, engine, inbox, priorities: priorityStore, about, agentSettings, prWorkflows: () => prWorkflowView(), rpc: rpcBridge, display: displayBridge });
782
+ const agentActions = new AgentActions({ store, prActions: actions, engine, inbox, priorities: priorityStore, about, agentSettings, prWorkflows: () => prWorkflowView(), rpc: rpcBridge, display: displayBridge,
783
+ // The directory's agent list (metadata only): a claim never loads or refreshes the main agent.
784
+ agentInfo: async agentId => { const row = gateway.directory.cached(agentId) ?? (await gateway.directory.read()).agents.find(r => r.agent.id === agentId)?.agent; return row ? { status: row.status, activeTurn: row.activeTurn, pendingPermissions: row.pendingPermissions, archivedAt: row.archivedAt } : null; } });
783
785
  handle(rpc.prioritiesRpc, async () => ({ items: await priorityStore.read() }));
784
786
  // Provider limits are non-essential: at critical memory only the VM meter is served.
785
787
  handle(rpc.usageRpc, async () => ({ ...(governor.allowsExtras() ? await usage.read() : NO_USAGE), resources: governor.current() }));
@@ -791,7 +793,8 @@ export default function contribute(server: PluginServerContext) {
791
793
  const agent = (await paseo.agents.ref(agentId).refresh())?.agent;
792
794
  if (!agent?.workspaceId || agent.archivedAt) throw new Error("Cannot locate the caller's workspace.");
793
795
  if (agent.labels["follow-through.recovery"]) throw new Error("Recovery sessions can't act for the developer. Acknowledge your batch instead.");
794
- if ((await store.snapshot()).workspaces.some(w => w.enable_tracking && !w.archived && w.contributorAgentIds?.includes(agentId))) throw new Error("Contributor sessions can't act for the developer. Report to the main agent.");
796
+ // Contributors (the workspace's other root agents) get one tool: make_main_agent, with its claim rules.
797
+ if (tool !== "make_main_agent" && (await store.snapshot()).workspaces.some(w => w.enable_tracking && !w.archived && w.contributorAgentIds?.includes(agentId))) throw new Error("Contributor sessions can't act for the developer. Report to the main agent.");
795
798
  if (!await isWorkspaceRoot(agent, async id => (await paseo.agents.ref(id).refresh())?.agent)) throw new Error("Follow-up's action tools are for root agents. Ask your parent agent.");
796
799
  const result = await agentActions.run(agentId, tool as AgentTool, args);
797
800
  void engine.tick();
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "paseo-follow-up",
3
3
  "private": false,
4
- "version": "1.4.0-beta.21",
4
+ "version": "1.4.0-beta.22",
5
5
  "description": "Follow every workspace PR stack in Paseo, answer agent questions, batch repairs for the main agent, and see what needs you.",
6
6
  "type": "module",
7
7
  "files": [
@@ -8,7 +8,7 @@ import type { InboxRow } from "../shared/inbox";
8
8
  import type { Pr, State, Workspace } from "../shared/model";
9
9
  import { configuredReviewers, reviewerLoginSchema, noReviewers, resolveReviewers, reviewerConfig, reviewerLabel, withoutAuthor, type ReviewerEntry } from "../shared/reviewers";
10
10
  import { findWorkspace } from "./engine";
11
- import { setMainAgent } from "./discovery";
11
+ import { checkMainClaim, lastMainChange, setMainAgent, type MainAgentInfo } from "./discovery";
12
12
  import type { InboxAction } from "./inbox";
13
13
  import { priorityInputSchema, type Priority } from "../shared/priorities";
14
14
  import type { AboutView } from "../shared/about";
@@ -23,14 +23,14 @@ import { DISPLAY_TOOLS, RPC_TOOLS, type RpcTool } from "./agent-parity";
23
23
  * return a dry-run plan first; `confirm: true` with that plan's id runs it. Every agent write is recorded in
24
24
  * the inbox ledger as `by: "agent:<id>"`, which never counts as the developer writing to the agent.
25
25
  */
26
- export const AGENT_TOOLS = ["list_prs", "add_reviewers", "merge", "enable_merge_when_ready", "disable_merge_when_ready", "send_repairs", "set_auto_send", "clear_hold", "retry_batch", "track", "inbox_list", "sign_off", "snooze", "set_finish_flags", "set_priorities", "workspace_about", "agent_settings", "follow_settings", "set_follow_settings", "project_settings", "set_project_tracking", "pr_workflow", "set_pr_workflow", "reviewer_settings", "reviewer_suggestions", "save_reviewers", "set_agent_setting", "onboarding_status", "onboarding_checks", "set_onboarding", "priorities", "rank_status", "rerank_priorities", "usage", "overseer_status", "overseer_start", "overseer_restart", "overseer_ask", "inbox_brief", "brief_action", "inbox_act", "answer_question", "run_recovery", "refresh", "set_workspace_spec", "set_task_trigger", "pr_controls", "browser_status", "trust_bypass_status", "display_settings", "set_display"] as const;
26
+ export const AGENT_TOOLS = ["make_main_agent", "list_prs", "add_reviewers", "merge", "enable_merge_when_ready", "disable_merge_when_ready", "send_repairs", "set_auto_send", "clear_hold", "retry_batch", "track", "inbox_list", "sign_off", "snooze", "set_finish_flags", "set_priorities", "workspace_about", "agent_settings", "follow_settings", "set_follow_settings", "project_settings", "set_project_tracking", "pr_workflow", "set_pr_workflow", "reviewer_settings", "reviewer_suggestions", "save_reviewers", "set_agent_setting", "onboarding_status", "onboarding_checks", "set_onboarding", "priorities", "rank_status", "rerank_priorities", "usage", "overseer_status", "overseer_start", "overseer_restart", "overseer_ask", "inbox_brief", "brief_action", "inbox_act", "answer_question", "run_recovery", "refresh", "set_workspace_spec", "set_task_trigger", "pr_controls", "browser_status", "trust_bypass_status", "display_settings", "set_display"] as const;
27
27
  export type AgentTool = typeof AGENT_TOOLS[number];
28
28
  /** Tools that only read. */
29
29
  export const READ_ONLY_TOOLS: readonly AgentTool[] = ["list_prs", "inbox_list", "workspace_about", "agent_settings", "display_settings", ...RPC_TOOLS.filter(t => t.kind === "read").map(t => t.name as AgentTool)];
30
30
  /** Tools that can't be undone from Follow-up. */
31
31
  export const DESTRUCTIVE_TOOLS: readonly AgentTool[] = ["merge"];
32
32
  /** Tools that plan first and run only with `confirm: true` and the plan's id. */
33
- export const PLANNED_TOOLS: readonly AgentTool[] = ["add_reviewers", "merge", "enable_merge_when_ready", "disable_merge_when_ready", "sign_off", "snooze", "set_finish_flags", "set_priorities", "set_display", ...RPC_TOOLS.filter(t => t.kind === "planned").map(t => t.name as AgentTool)];
33
+ export const PLANNED_TOOLS: readonly AgentTool[] = ["make_main_agent", "add_reviewers", "merge", "enable_merge_when_ready", "disable_merge_when_ready", "sign_off", "snooze", "set_finish_flags", "set_priorities", "set_display", ...RPC_TOOLS.filter(t => t.kind === "planned").map(t => t.name as AgentTool)];
34
34
  const RPC_TOOL = new Map<string, RpcTool>(RPC_TOOLS.map(t => [t.name, t]));
35
35
  void DISPLAY_TOOLS;
36
36
 
@@ -81,6 +81,8 @@ export type AgentActionDeps = {
81
81
  prWorkflows?: () => Promise<{ default: string; repos: { repo: string; effective: string; setting: string; reason: string; reviewFix: unknown }[]; reviewFix: unknown }>;
82
82
  /** Runs a developer RPC's own handler (the button's path), and checks an input against its contract. */
83
83
  rpc?: { call(method: string, input: unknown): Promise<unknown>; validate(method: string, input: unknown): Promise<unknown> };
84
+ /** One agent's list entry for a main-agent claim (metadata; never loads it). Null when it's gone. */
85
+ agentInfo?: (agentId: string) => Promise<MainAgentInfo>;
84
86
  /** Settings → Display (host-scoped preferences, trust bypass among them). */
85
87
  display?: { read(): Promise<{ revision: string; values: Record<string, unknown> }>; write(revision: string, values: Record<string, unknown>): Promise<unknown> };
86
88
  now?: () => number;
@@ -110,6 +112,7 @@ export const TOOL_INPUT = {
110
112
  set_finish_flags: z.strictObject({ agentIds: agentIds.optional(), value: z.boolean().optional(), ...confirm }),
111
113
  set_priorities: z.strictObject({ priorities: z.array(priorityInputSchema).max(200).optional(), replace: z.boolean().optional(), ...confirm }),
112
114
  display_settings: z.strictObject({}),
115
+ make_main_agent: z.strictObject({ agentId: id.optional(), reason: z.string().trim().min(1).max(200).optional(), requested: z.enum(["developer", "self"]).optional(), ...confirm }),
113
116
  set_display: z.strictObject({ values: z.record(z.string(), z.boolean()).optional(), ...confirm }),
114
117
  ...Object.fromEntries(RPC_TOOLS.map(t => [t.name, t.input])),
115
118
  } as unknown as Record<AgentTool, z.ZodType>;
@@ -149,6 +152,7 @@ export class AgentActions {
149
152
  const rpcTool = RPC_TOOL.get(tool);
150
153
  if (rpcTool) return this.runRpc(caller, rpcTool, args);
151
154
  if (tool === "display_settings" || tool === "set_display") return this.displayTool(caller, tool, args);
155
+ if (tool === "make_main_agent") return this.planMakeMain(caller, args);
152
156
  switch (tool) {
153
157
  case "list_prs": return this.listPrs(args);
154
158
  case "inbox_list": return this.inboxList(caller, args);
@@ -218,6 +222,37 @@ export class AgentActions {
218
222
  next: `Only when the developer asked for this: call ${t.name} with confirm=true and planId=${planId} within 5 minutes.` };
219
223
  }
220
224
 
225
+ /**
226
+ * make_main_agent: a root agent makes itself or another root agent of its workspace the main agent
227
+ * (~/paseo-harness/main-agent-claim.md). The current main can hand its role on; anyone else follows checkMainClaim:
228
+ * the developer's ask is refused only mid-turn, a self-claim needs the main archived, gone, long closed or idle.
229
+ * The rules are checked again at confirm. The old main hears on its next turn through the hook, never by a message.
230
+ */
231
+ private async planMakeMain(caller: string, args: Record<string, any>) {
232
+ if (!args.reason) throw new Error("make_main_agent: give reason, one line the developer sees (\"Tom asked me to take over the release\").");
233
+ if (!args.requested) throw new Error("make_main_agent: give requested: developer (the developer asked for it) or self (your own claim).");
234
+ if (!this.d.agentInfo) throw new Error("make_main_agent isn't available in this Follow-up.");
235
+ const find = (state: State) => this.tracked(state).find(w => w.mainAgentId === caller || w.contributorAgentIds?.includes(caller));
236
+ const w = find(await this.d.store.snapshot());
237
+ if (!w) throw new Error("Only a root agent of a tracked workspace can change its main agent.");
238
+ const target = args.agentId ?? caller; const from = w.mainAgentId;
239
+ const requested = caller === from ? "developer" : args.requested as "developer" | "self";
240
+ const check = async (current: Workspace) => checkMainClaim(current, target, requested, caller === from ? null : await this.d.agentInfo!(current.mainAgentId), this.now());
241
+ const { blockers, rule } = await check(w);
242
+ const reason = `${args.reason}${args.requested === "developer" && caller !== from ? " (the developer asked)" : ""}`;
243
+ const planId = blockers.length ? null : this.plan(caller, "make_main_agent", async () => {
244
+ const fresh = find(await this.d.store.snapshot());
245
+ if (!fresh || fresh.id !== w.id || fresh.mainAgentId !== from) throw new Error("The main agent changed since the dry run. Run make_main_agent again.");
246
+ const again = await check(fresh);
247
+ if (again.blockers.length) throw new Error(again.blockers.join(" "));
248
+ await this.d.store.mutate(state => { const current = findWorkspace(state, w.id); if (current.mainAgentId !== from) throw new Error("The main agent changed since the dry run."); setMainAgent(current, target, "claim", this.now(), { by: `agent:${caller}`, reason }); });
249
+ await this.note(caller, from, "make_main_agent");
250
+ return { workspaceId: w.id, mainAgentId: target, previous: from, reason, undo: "The developer can undo it from the workspace panel; the previous main can't take it back on its own for 2 hours." };
251
+ }, 2 * 60_000);
252
+ return { dryRun: true, planId, workspaceId: w.id, workspace: w.title, from, to: target, requested, rule, blockers, lastChange: lastMainChange(w) ?? null,
253
+ next: planId ? `Call make_main_agent with confirm=true and planId=${planId} within 2 minutes. The developer sees "Main agent changed" with Undo.` : "Blocked. Ask the developer, who can use Make main agent in the workspace panel." };
254
+ }
255
+
221
256
  /** Settings → Display: the host-scoped preferences the Display screen writes, trust bypass among them. */
222
257
  private async displayTool(caller: string, tool: "display_settings" | "set_display", args: Record<string, any>) {
223
258
  if (!this.d.display) throw new Error(`${tool} isn't available in this Follow-up.`);
@@ -8,7 +8,7 @@ const directory = dirname(fileURLToPath(import.meta.url));
8
8
  /** 1.4.0-beta.2: launched with Follow-up's tools served by Paseo's MCP (follow_<name>), or the follow-through bridge (<name>). Agents opened before the upgrade carry no flag and keep the bridge names. */
9
9
  let native = process.env.FOLLOW_THROUGH_TOOLS === "native";
10
10
  // Tool names that read unambiguously in prose; kept identical to server/mcp.mjs's underscore names (a test checks it).
11
- 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", "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", "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", "onboarding_status", "onboarding_checks", "set_onboarding", "rank_status", "rerank_priorities", "overseer_status", "overseer_start", "overseer_restart", "overseer_ask", "inbox_brief", "brief_action", "inbox_act", "answer_question", "run_recovery", "set_workspace_spec", "set_task_trigger", "pr_controls", "browser_status", "trust_bypass_status"];
11
+ 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", "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", "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", "onboarding_status", "onboarding_checks", "set_onboarding", "rank_status", "rerank_priorities", "overseer_status", "overseer_start", "overseer_restart", "overseer_ask", "inbox_brief", "brief_action", "inbox_act", "answer_question", "run_recovery", "set_workspace_spec", "set_task_trigger", "pr_controls", "browser_status", "trust_bypass_status", "make_main_agent"];
12
12
  const toolPattern = new RegExp(`(?<![\\w])(${TOOL_NAMES.join("|")})(?![\\w])`, "g");
13
13
  /** Names Follow-up's tools the way this agent has them. */
14
14
  export function named(text, isNative = native) { return isNative ? text.replace(toolPattern, "follow_$1") : text; }
@@ -122,6 +122,14 @@ function paragraphs(lease, contributor, workflow) {
122
122
  `Prefer the native follow-through MCP tools. For a full historical record, use workspace_status with detail=full. CLI compatibility fallback: FOLLOW_THROUGH_CLIENT_ENTRY=${quote(lease.clientEntry)} node ${quote(join(directory, "mcp.mjs"))} call <tool> '<json>' --compact. Omit --compact only when an existing script needs the full response. Never ask the developer to maintain the sidebar or run this bridge.`,
123
123
  ];
124
124
  }
125
+ /** The old main's notice, within a day of losing the role: who took over, why, and what to do. Null otherwise. */
126
+ export function demotedNotice(demoted, now = Date.now()) {
127
+ if (!demoted?.at || now - Date.parse(demoted.at) > 24 * 60 * 60_000) return null;
128
+ const time = new Date(demoted.at).toISOString().slice(11, 16);
129
+ const who = demoted.by === "developer" ? "the developer moved it" : demoted.by === "auto" ? "Follow-up moved it" : "it was claimed";
130
+ return { at: demoted.at, text: `You're no longer this workspace's main agent: ${demoted.to} took over at ${time} UTC (${who}${demoted.reason ? `: ${demoted.reason}` : ""}). Report to it instead of asking the developer or calling Done. If that's wrong, ask the developer to make you main again; you can't take it back on your own for 2 hours.` };
131
+ }
132
+
125
133
  /** With native tools there's no MCP initialize reply, so the role text it carried comes from the hook instead. */
126
134
  async function nativeExtras(brief) {
127
135
  if (!native) return [];
@@ -171,8 +179,8 @@ async function main() {
171
179
  }
172
180
  // scopes.json is a few KB; this hook runs on every tool call. Older workers don't write it: read state.json.
173
181
  const scopes = await json(join(directory, "scopes.json")).catch(() => null);
174
- let workspace = null; let contributor = false; let workflow;
175
- if (scopes?.agents) { const entry = scopes.agents[agentId]; if (entry && entry.role !== "recovery") { workspace = { id: entry.workspaceId }; contributor = entry.role === "contributor"; workflow = entry.workflow; } }
182
+ let workspace = null; let contributor = false; let workflow; let demoted = null;
183
+ if (scopes?.agents) { const entry = scopes.agents[agentId]; if (entry && entry.role !== "recovery") { workspace = { id: entry.workspaceId }; contributor = entry.role === "contributor"; workflow = entry.workflow; demoted = contributor ? demotedNotice(entry.demoted) : null; } }
176
184
  else {
177
185
  const state = await json(join(directory, "state.json")).catch(() => ({ workspaces: [] }));
178
186
  workspace = state.workspaces.find(w => (w.mainAgentId === agentId || w.contributorAgentIds?.includes(agentId)) && w.enable_tracking && !w.archived) ?? null;
@@ -198,8 +206,11 @@ async function main() {
198
206
  if (name === "UserPromptSubmit") {
199
207
  if (turn?.stopped && String(event.prompt ?? "").startsWith(stopReason)) return;
200
208
  const text = await sessionText(); const hash = text ? digest(text) : null;
201
- await save(path, { startedAt: Date.now(), dirtyAt: null, lastToolAt: null, stopped: false, quietRevision, contextHash: hash, ...(turn?.detachedNotice ? { detachedNotice: turn.detachedNotice } : {}) });
202
- if (text && shouldRepeat(process.env.FOLLOW_THROUGH_PROVIDER, turn, hash)) emit(text);
209
+ // Lost the main role (make_main_agent, Make main agent, or a handover): said once, on the next turn.
210
+ const tellDemoted = demoted && turn?.demotedNotice !== demoted.at;
211
+ await save(path, { startedAt: Date.now(), dirtyAt: null, lastToolAt: null, stopped: false, quietRevision, contextHash: hash, ...(turn?.detachedNotice ? { detachedNotice: turn.detachedNotice } : {}), ...(tellDemoted || turn?.demotedNotice ? { demotedNotice: tellDemoted ? demoted.at : turn.demotedNotice } : {}) });
212
+ const out = [text && shouldRepeat(process.env.FOLLOW_THROUGH_PROVIDER, turn, hash) ? text : null, tellDemoted ? demoted.text : null].filter(Boolean);
213
+ if (out.length) emit(out.join("\n\n"));
203
214
  return;
204
215
  }
205
216
  if (name === "PostToolUse") {
@@ -103,8 +103,7 @@ export const DISPLAY_TOOLS = ["display_settings", "set_display"] as const;
103
103
  export const PARITY: Record<string, { tools: readonly string[]; note?: string } | { exempt: string } | { pending: string }> = {
104
104
  "follow.list": { tools: ["list_prs", "workspace_status"] },
105
105
  "follow.get": { tools: ["list_prs", "workspace_status"] },
106
- "follow.control": { tools: ["set_auto_send", "clear_hold", "retry_batch"], note: "mainAgentId (Make main agent) is pending; see follow.control#mainAgentId." },
107
- "follow.control#mainAgentId": { pending: "make_main_agent waits for the claim rules (~/paseo-harness/main-agent-claim.md) to be approved by Tom." },
106
+ "follow.control": { tools: ["set_auto_send", "clear_hold", "retry_batch", "make_main_agent"] },
108
107
  "follow.send": { tools: ["send_repairs"] },
109
108
  "follow.recover": { tools: ["run_recovery"] },
110
109
  "follow.refresh": { tools: ["refresh"] },
package/server/daemon.ts CHANGED
@@ -12,7 +12,7 @@ import { applyRecoveryRole, recoveryConfig, type RecoveryRole } from "./recovery
12
12
  import { submittedPrs, type Submission } from "./submissions";
13
13
  import { publishedArtifacts } from "./spec";
14
14
  import type { Artifact } from "../shared/spec";
15
- import { extractHistory, type History, type DiscoveredWorkspace } from "./discovery";
15
+ import { extractHistory, inMainCooldown, type History, type DiscoveredWorkspace } from "./discovery";
16
16
  import type { PluginBeforeRequests } from "@getpaseo/plugin/server";
17
17
  import { isWorkspaceRoot, type WorkspaceAgent } from "./workspace-agent";
18
18
  import { SessionGuard } from "./session-guard";
@@ -214,7 +214,8 @@ export class PaseoGateway implements Gateway {
214
214
  for (const agent of candidates) if (await isWorkspaceRoot(agent, findParent)) roots.push(agent);
215
215
  const recorded = existing ? roots.find(a => a.id === existing.mainAgentId) : undefined;
216
216
  const handBack = existing ? handBackMainAgent(roots, existing) : undefined;
217
- const successor = handBack ?? successorMainAgent(roots, existing?.mainAgentId, existing?.mainClosedSince, now);
217
+ // Rule 4: no automatic handover within 30 minutes of a change, unless the main is gone (hand-back is exempt).
218
+ const successor = handBack ?? (existing && recorded && inMainCooldown(existing, now) ? undefined : successorMainAgent(roots, existing?.mainAgentId, existing?.mainClosedSince, now));
218
219
  const main = successor ?? chooseMainAgent(roots, existing?.mainAgentId);
219
220
  if (!main && !existing) continue;
220
221
  const owner = successor?.id ?? existing?.mainAgentId ?? main!.id;
@@ -14,9 +14,30 @@ export const interruptionHold = (kind: "canceled" | "failed") => kind === "cance
14
14
  * A stop hold raised by another agent's turn doesn't carry over to the new main (a hold from before 1.4.0-beta.16
15
15
  * names no agent, so only the developer's explicit choice clears it).
16
16
  */
17
- export function setMainAgent(w: Workspace, to: string, kind: "handover" | "handBack" | "developer", now: number): void {
17
+ /** Main-agent claim rules (~/paseo-harness/main-agent-claim.md, approved 2026-11-10). */
18
+ export const MAIN_CHANGE_COOLDOWN_MS = 30 * 60_000;
19
+ export const MAIN_RECLAIM_MS = 2 * 60 * 60_000;
20
+ export const MAIN_IDLE_MS = 24 * 60 * 60_000;
21
+ export const MAIN_NOTICE_MS = 24 * 60 * 60_000;
22
+ export type MainChange = NonNullable<Workspace["mainHistory"]>[number];
23
+
24
+ /** The newest change of main agent, if any. */
25
+ export const lastMainChange = (w: Pick<Workspace, "mainHistory">): MainChange | undefined => w.mainHistory?.at(-1);
26
+ /** Within the cooldown after any change: no self-claim and no automatic handover (the developer is exempt). */
27
+ export const inMainCooldown = (w: Pick<Workspace, "mainHistory">, now: number) => { const last = lastMainChange(w); return !!last && now - Date.parse(last.at) < MAIN_CHANGE_COOLDOWN_MS; };
28
+
29
+ /**
30
+ * Moves the workspace to another main agent: automatic handover or hand-back, the developer's "Make main agent",
31
+ * or an agent's claim (make_main_agent). Recorded in mainHistory. A stop hold raised by another agent's turn
32
+ * doesn't carry over (a hold from before 1.4.0-beta.16 names no agent, so only the developer's choice clears it).
33
+ */
34
+ export function setMainAgent(w: Workspace, to: string, kind: "handover" | "handBack" | "developer" | "claim", now: number, meta: { by?: string; reason?: string | null } = {}): void {
18
35
  const from = w.mainAgentId;
19
36
  if (from === to) return;
37
+ const by = meta.by ?? (kind === "developer" ? "developer" : "auto");
38
+ const reason = meta.reason ?? (kind === "handover" ? "The main agent was closed for 30 minutes" : kind === "handBack" ? "The original main agent is back" : null);
39
+ w.mainHistory = [...(w.mainHistory ?? []), { from, to, by, reason, at: new Date(now).toISOString() }].slice(-20);
40
+ delete w.mainWorkAt;
20
41
  w.mainAgentId = to; w.runtimeReason = null; delete w.mainClosedSince;
21
42
  w.contributorAgentIds = [...new Set([...(w.contributorAgentIds ?? []).filter(id => id !== to), from])];
22
43
  for (const b of w.batches) if (b.state === "pending" && b.recipientAgentId === from) b.recipientAgentId = null;
@@ -26,13 +47,51 @@ export function setMainAgent(w: Workspace, to: string, kind: "handover" | "handB
26
47
  w.updatedAt = new Date(now).toISOString();
27
48
  }
28
49
 
29
- /** A successor's main-agent call: its handover is in use and no longer goes back. True when something changed. */
30
- export function markMainWork(state: State, agentId: string): boolean {
50
+ const MAIN_WORK_MARK_MS = 60 * 60_000;
51
+ /** Whether a main-agent call by `agentId` has something to record: an open handover, or an hour-old mainWorkAt. */
52
+ export function mainWorkDue(w: Workspace, agentId: string, now: number): boolean {
53
+ return w.mainAgentId === agentId && (!!w.handover && !w.handover.worked || !w.mainWorkAt || now - Date.parse(w.mainWorkAt) >= MAIN_WORK_MARK_MS);
54
+ }
55
+ /**
56
+ * A main agent's main-agent call: a successor's handover is in use and no longer goes back, and mainWorkAt (hourly
57
+ * at most, so a sync per turn doesn't write state every time) feeds the 24-hour idle rule of a claim.
58
+ */
59
+ export function markMainWork(state: State, agentId: string, now = Date.now()): boolean {
31
60
  let changed = false;
32
- for (const w of state.workspaces) if (w.mainAgentId === agentId && w.handover && !w.handover.worked) { w.handover.worked = true; changed = true; }
61
+ for (const w of state.workspaces) {
62
+ if (!mainWorkDue(w, agentId, now)) continue;
63
+ if (w.handover && !w.handover.worked) w.handover.worked = true;
64
+ w.mainWorkAt = new Date(now).toISOString(); changed = true;
65
+ }
33
66
  return changed;
34
67
  }
35
68
 
69
+ /** What a claim needs to know about the current main, from the agent list (metadata; never loads an agent). Null: gone. */
70
+ export type MainAgentInfo = { status: string; activeTurn?: unknown; pendingPermissions?: unknown[] | null; archivedAt?: string | null } | null;
71
+
72
+ /**
73
+ * Rules 1-4 of a main-agent claim. Who may claim (the workspace's root agents) is checked by the caller. A claim the
74
+ * developer asked for is refused only while the main is mid-turn; a self-claim also needs the main archived, gone or
75
+ * closed 30 minutes, or every open PR registered by the claimant while the main has been idle 24 hours, and respects
76
+ * the cooldown and the 2-hour reclaim limit.
77
+ */
78
+ export function checkMainClaim(w: Workspace, target: string, requested: "developer" | "self", main: MainAgentInfo, now: number): { blockers: string[]; rule: string | null } {
79
+ const blockers: string[] = [];
80
+ if (target === w.mainAgentId) return { blockers: ["Already the main agent."], rule: null };
81
+ if (!(w.contributorAgentIds ?? []).includes(target)) return { blockers: ["Not one of this workspace's root agents."], rule: null };
82
+ if (main && !main.archivedAt && (["running", "initializing"].includes(main.status) || !!main.activeTurn || !!main.pendingPermissions?.length)) blockers.push("The main agent is mid-turn. Try again after its turn ends.");
83
+ if (requested === "developer") return { blockers, rule: blockers.length ? null : "asked by the developer" };
84
+ if (inMainCooldown(w, now)) blockers.push("The main agent changed less than 30 minutes ago. Ask the developer if it should change again.");
85
+ if (w.mainHistory?.some(c => c.from === target && now - Date.parse(c.at) < MAIN_RECLAIM_MS)) blockers.push("This agent lost the main role less than 2 hours ago and can't take it back on its own. Ask the developer.");
86
+ const open = w.prs.filter(p => !p.disposition && !["MERGED", "CLOSED"].includes(p.snapshot?.state ?? "OPEN"));
87
+ const rule = !main || main.archivedAt ? "the main agent is archived or gone"
88
+ : main.status === "closed" && w.mainClosedSince && now - Date.parse(w.mainClosedSince) >= MAIN_CHANGE_COOLDOWN_MS ? "the main agent has been closed for 30 minutes"
89
+ : open.length && open.every(p => p.registeredAgentId === target) && !!w.mainWorkAt && now - Date.parse(w.mainWorkAt) >= MAIN_IDLE_MS ? "it registered every open PR and the main agent has been idle for 24 hours"
90
+ : null;
91
+ if (!rule) blockers.push("An agent can claim the main role on its own only when the main agent is archived, gone or closed for 30 minutes, or when it registered every open PR and the main has been idle for 24 hours. Otherwise ask the developer.");
92
+ return { blockers, rule: blockers.length ? null : rule };
93
+ }
94
+
36
95
  export function extractHistory(items: readonly unknown[], complete = true, error: string | null = null): History {
37
96
  const candidates = new Set<string>();
38
97
  let goal: string | null = null;
@@ -1,2 +1,2 @@
1
1
  // Generated by scripts/build.mjs.
2
- export const hookSource = "#!/usr/bin/env node\nimport { readFile, writeFile, mkdir, rename } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { createHash, randomUUID } from \"node:crypto\";\n\nconst directory = dirname(fileURLToPath(import.meta.url));\n/** 1.4.0-beta.2: launched with Follow-up's tools served by Paseo's MCP (follow_<name>), or the follow-through bridge (<name>). Agents opened before the upgrade carry no flag and keep the bridge names. */\nlet native = process.env.FOLLOW_THROUGH_TOOLS === \"native\";\n// Tool names that read unambiguously in prose; kept identical to server/mcp.mjs's underscore names (a test checks it).\nexport 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\", \"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\", \"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\", \"onboarding_status\", \"onboarding_checks\", \"set_onboarding\", \"rank_status\", \"rerank_priorities\", \"overseer_status\", \"overseer_start\", \"overseer_restart\", \"overseer_ask\", \"inbox_brief\", \"brief_action\", \"inbox_act\", \"answer_question\", \"run_recovery\", \"set_workspace_spec\", \"set_task_trigger\", \"pr_controls\", \"browser_status\", \"trust_bypass_status\"];\nconst toolPattern = new RegExp(`(?<![\\\\w])(${TOOL_NAMES.join(\"|\")})(?![\\\\w])`, \"g\");\n/** Names Follow-up's tools the way this agent has them. */\nexport function named(text, isNative = native) { return isNative ? text.replace(toolPattern, \"follow_$1\") : text; }\n/** Whether a tool call is Follow-up's own, under either name set (mcp__follow-through__x, follow-through.x, mcp__paseo__follow_x, paseo.follow_x). */\nexport function isFollowTool(tool) { return /follow[\\s_-]*through/i.test(tool) || /^(?:mcp__paseo__|paseo[.:/])follow_[a-z_]+$/.test(tool); }\n/** Whether a shell call runs the bridge, however it names it ($FOLLOW_THROUGH_CLI, as the skill says, or the path). */\nexport function isBridgeCall(args, bridgePath) { return args.includes(bridgePath) || /\\$\\{?FOLLOW_THROUGH_CLI\\b/.test(args) || /mcp\\.mjs[\"']?\\s+call\\b/.test(args); }\n/**\n * Native tools are attached by one worker; a plugin reload or update drops them from open sessions until each reopens\n * (Paseo 0.15.2 reopens a session before that agent's next prompt). The worker records its instance and the instance\n * that attached each session's tools; a mismatch means this session's follow_ tools are gone. Pure, so it's testable.\n */\nexport function toolsDetached(isNative, current, mine) { return isNative && !!current?.instance && mine?.instance !== current.instance; }\nexport const detachedNotice = \"Follow-up was updated while this session was open, so its follow_* tools are detached and fail with \\\"Tool not found\\\" until this session reopens (Paseo reopens it before your next prompt). Until then use the bridge, which runs the same tools with their unprefixed names: node \\\"$FOLLOW_THROUGH_CLI\\\" call <tool> '<json>' --compact (for example sync_workspace or needs_you). Do not mention this to the developer.\";\nconst quietRevision = 1;\nconst quietInstruction = \"Do routine bookkeeping silently. Do not announce tracker calls, say you updated/synced the sidebar, recap panel state, or add plugin-status commentary/final paragraphs. Put receipts and evidence in the tools. User-facing messages should cover the actual work outcome, or a decision/blocker requiring the developer; answer sidebar status only when explicitly asked. If this continuation is bookkeeping only, use the tools and finish without another recap or repeating your previous answer.\";\nconst stopReason = \"Silently complete this workspace's sidebar bookkeeping before finishing.\";\n// Kept identical to NEEDS_YOU_NUDGE in shared/brief.ts (a test checks it).\nconst nudgeReason = \"Before you stop, call needs_you once with what the developer has to do next: a decision with options, an action only they can take, or kind=done (\\\"Nothing needed\\\" plus what you finished), which means nothing for the developer and won't flag you. Then stop; don't repeat your reply.\";\n\n/**\n * R2: whether to nudge a Claude Code root agent that ended its turn without needs_you. Pure, so every skip is testable.\n * At most once per turn: Claude's stop_hook_active and our own per-turn `stopped` marker both end it.\n */\nexport function shouldNudge({ provider, brief, agentId, contributor, recovery, subagent, stopHookActive, turn, called }) {\n if (provider !== \"claude\" || recovery || subagent || contributor || stopHookActive) return false;\n if (!brief || brief.enable_inbox !== true || brief.enable_brief_nudge !== true) return false;\n if (Array.isArray(brief.pending) && brief.pending.includes(agentId)) return false;\n if (!turn || turn.stopped || !turn.startedAt) return false;\n return !(called && called.at >= turn.startedAt);\n}\n/**\n * The Overseer's per-turn digest (1.4.0-beta.0). The daemon rewrites overseer-digest.json only when it changes (one line and a hash\n * per workspace); this diffs it against what the Overseer saw last turn. Pure, so size and paging are testable.\n * Kept to about 3k tokens: at most 20 needs lines and 30 changes, then a pointer to the workstreams tool.\n */\nexport function overseerDigest(file, seen, now = Date.now(), { needsMax = 20, changedMax = 30, restingMax = 40, chars = 12_000 } = {}) {\n const all = Array.isArray(file?.rows) ? file.rows : [];\n const rows = all.filter(r => !r.resting);\n const resting = all.filter(r => r.resting);\n const prior = seen && typeof seen.rows === \"object\" && seen.rows ? seen.rows : null;\n const age = Math.max(0, Math.round((now - Date.parse(file?.at ?? \"\")) / 1000));\n const lines = [`Follow-up digest (last change ${Number.isFinite(age) ? `${age}s` : \"?\"} ago): ${file?.total ?? all.length} workspaces, ${file?.needs ?? 0} need Tom. Paging: workstreams(page, group, query).`];\n const needs = rows.filter(r => r.group === \"needs\");\n if (needs.length) {\n lines.push(`Needs Tom (${needs.length}):`);\n for (const r of needs.slice(0, needsMax)) lines.push(`- ${r.line}`);\n if (needs.length > needsMax) lines.push(`- …${needs.length - needsMax} more: workstreams(group=\"needs\")`);\n } else lines.push(\"Nothing needs Tom right now.\");\n if (!prior) {\n const active = rows.filter(r => r.group === \"running\" || r.group === \"fixing\");\n lines.push(`First turn. Running now (${active.length}):`);\n for (const r of active.slice(0, changedMax)) lines.push(`- ${r.line}`);\n if (active.length > changedMax) lines.push(`- …${active.length - changedMax} more: workstreams(group=\"running\")`);\n } else {\n const current = new Set(all.map(r => r.id));\n const changed = rows.filter(r => prior[r.id] !== r.hash && r.group !== \"needs\");\n const gone = Object.keys(prior).filter(id => !current.has(id));\n lines.push(changed.length || gone.length ? `Changed since your last turn (${changed.length + gone.length}):` : \"No other changes since your last turn.\");\n for (const r of changed.slice(0, changedMax)) lines.push(`- [${r.group}] ${r.line}`);\n if (changed.length > changedMax) lines.push(`- …${changed.length - changedMax} more changed: workstreams()`);\n if (gone.length) lines.push(`- ${gone.length} workspace${gone.length === 1 ? \"\" : \"s\"} archived or removed: ${gone.slice(0, 5).join(\", \")}`);\n }\n if (resting.length) lines.push(`Resting (${resting.length}; agents likely unloaded, sending wakes them): ${resting.slice(0, restingMax).map(r => r.line).join(\"; \")}${resting.length > restingMax ? `; …${resting.length - restingMax} more: workstreams()` : \"\"}`);\n let text = \"\";\n for (const l of lines) { if (text.length + l.length + 1 > chars) { text += \"- …truncated: use workstreams()\\n\"; break; } text += l + \"\\n\"; }\n return { text: text.trimEnd(), seen: { at: now, rows: Object.fromEntries(all.map(r => [r.id, r.hash])) } };\n}\n/**\n * How batches are worked, for this workspace's PR workflow (from scopes.json). Graphite with /fix-pr, and agents of an\n * older worker that wrote no workflow, keep the original text; plain GitHub never mentions Graphite, gt or /fix-pr.\n */\nexport function batchParagraph(workflow) {\n const mode = workflow?.mode ?? \"graphite\";\n const fix = workflow === undefined || workflow === null ? \"/fix-pr\" : workflow.reviewFix ?? null;\n const steps = \"Follow-through batches contain a batch ID and task list. Read workspace_status and refresh live conditions before acting; skip resolved tasks. Process dependent PRs bottom to top, one PR fully before the next.\";\n const review = fix ? `Use the repository's ${fix} workflow, validate feedback, verify changes,` : \"For review comments, read the PR's unresolved threads with gh, validate the feedback, fix it and verify the change,\";\n const submit = mode === \"graphite\" ? \"submit through Graphite with --publish\" : \"push the branch (gh pr create for a new PR, gh pr ready when it leaves draft)\";\n const reply = fix ? \"reply/resolve addressed threads\" : \"reply to each addressed thread and resolve it\";\n const restack = mode === \"graphite\" ? \"Follow the repository's safe reparent procedure for merged parents\" : \"Keep stacked PRs as a chain of base branches: restack with git rebase --update-refs and push with --force-with-lease, and when a parent merges retarget its child with gh pr edit --base if GitHub didn't already\";\n return `${steps} ${review} ${submit}, and ${reply}. ${restack} and preserve uncommitted work.`;\n}\nconst quote = value => \"'\" + value.replaceAll(\"'\", \"'\\\\''\") + \"'\";\nasync function json(path) { return JSON.parse(await readFile(path, \"utf8\")); }\nasync function save(path, value) {\n await mkdir(dirname(path), { recursive: true, mode: 0o700 });\n const temporary = path + \".\" + randomUUID();\n await writeFile(temporary, JSON.stringify(value), { mode: 0o600 });\n await rename(temporary, path);\n}\nfunction instructions(lease, contributor = false, workflow) {\n return named(paragraphs(lease, contributor, workflow).filter(p => !(native && /^Prefer (?:the )?native/i.test(p))).join(\"\\n\\n\"));\n}\nfunction paragraphs(lease, contributor, workflow) {\n if (contributor) return [\n \"Maintain PR tracking for this session in its tracked workspace. Read workspace_status now and after compaction. Register every PR you submit, including from secondary git worktrees, with register_pr; register parents before children. References and external dependencies are not owned PRs. Call sync_workspace before finishing. The designated main agent retains goal, task, scope and completion authority.\",\n quietInstruction,\n `Prefer native Follow-through tools. CLI fallback: FOLLOW_THROUGH_CLIENT_ENTRY=${quote(lease.clientEntry)} node ${quote(join(directory, \"mcp.mjs\"))} call <tool> '<json>' --compact. Do not ask the developer to maintain the sidebar.`,\n ];\n return [\n \"Maintain this tracked workspace's Follow-through sidebar as part of your normal work; do not wait for a developer reminder.\",\n quietInstruction,\n \"Read workspace_status now and after compaction. Refine the goal with enroll_workspace when scope changes. Register every PR you produce after submitting it, parents before children, and update stack/parent relationships after restacking. Historical mentions and external dependencies are not owned PRs; preserve exclusions and existing records.\",\n \"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. 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; if the developer answers in chat, call record_answer. Withdraw questions that stop mattering.\",\n \"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.\",\n \"Keep actual follow-through 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.\",\n \"Stakeholder replies are follow-through 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.\",\n \"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.\",\n 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. Verify the entire goal and post-merge work before declare_done; acknowledge a completion batch first. Merging and archiving remain the developer's actions.\",\n \"Before ending this turn, reconcile the sidebar with what you actually did and call sync_workspace with a short summary, including when no changes are needed. Acknowledge any assigned batch. When the entire goal is fulfilled, use declare_done; otherwise preserve remaining work. Do not launch recovery, start queued repairs, merge, toggle merge-when-ready, or archive as part of this bookkeeping. Auto still governs separate follow-up sends. Subagents report to the main agent instead of claiming workspace ownership.\",\n `Prefer the native follow-through MCP tools. For a full historical record, use workspace_status with detail=full. CLI compatibility fallback: FOLLOW_THROUGH_CLIENT_ENTRY=${quote(lease.clientEntry)} node ${quote(join(directory, \"mcp.mjs\"))} call <tool> '<json>' --compact. Omit --compact only when an existing script needs the full response. Never ask the developer to maintain the sidebar or run this bridge.`,\n ];\n}\n/** With native tools there's no MCP initialize reply, so the role text it carried comes from the hook instead. */\nasync function nativeExtras(brief) {\n if (!native) return [];\n const bridge = await import(pathToFileURL(join(directory, \"mcp.mjs\")).href).catch(() => null);\n if (!bridge) return [];\n return [\n brief?.enable_inbox && process.env.FOLLOW_THROUGH_BRIEF ? bridge.needsYouInstruction : null,\n process.env.FOLLOW_THROUGH_ROOT === \"1\" ? bridge.actionInstruction : null,\n process.env.FOLLOW_THROUGH_OVERSEER === \"1\" ? bridge.overseerInstruction : null,\n ].filter(Boolean).map(text => named(text));\n}\n/**\n * Claude Code keeps hook context for the whole session and re-runs SessionStart after compaction, so the same text\n * on every prompt only costs tokens (~1.3k per turn for a tracked main agent): send it once per session and again\n * only when it changes. Other providers keep the per-prompt text.\n */\nexport function shouldRepeat(provider, turn, hash) { return provider !== \"claude\" || turn?.contextHash !== hash; }\nconst digest = text => createHash(\"sha256\").update(text).digest(\"hex\").slice(0, 16);\nasync function main() {\n const agentId = process.env.PASEO_AGENT_ID;\n if (!agentId || !/^[\\w-]+$/.test(agentId) || process.env.FOLLOW_THROUGH_RECOVERY === \"1\") return;\n let input = \"\";\n for await (const chunk of process.stdin) { input += chunk; if (input.length > 2_000_000) return; }\n const event = JSON.parse(input);\n if (event.agent_id || event.hook_event_name === \"SubagentStop\") return;\n const lease = await json(join(directory, \"hooks-enabled.json\"));\n if (lease.expiresAt < Date.now() || !lease.clientEntry) return;\n const instance = native ? await json(join(directory, \"tools-instance.json\")).catch(() => null) : null;\n const detached = toolsDetached(native, instance, native ? await json(join(directory, \"hook-state\", `native-${agentId}.json`)).catch(() => null) : null);\n // Detached: name the bridge's tools everywhere below, and include the bridge paragraph.\n if (detached) native = false;\n // The Overseer: a fresh digest at the start of every turn; no sidebar bookkeeping and no Stop-hook nudge.\n if (process.env.FOLLOW_THROUGH_OVERSEER === \"1\") {\n if (event.hook_event_name === \"SessionStart\") {\n const extras = await nativeExtras(await json(join(directory, \"brief.json\")).catch(() => null));\n if (extras.length) process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: \"SessionStart\", additionalContext: extras.join(\"\\n\\n\") } }) + \"\\n\");\n return;\n }\n if (event.hook_event_name !== \"UserPromptSubmit\") return;\n const file = await json(join(directory, \"overseer-digest.json\")).catch(() => null);\n if (!file || file.agentId !== agentId) return;\n const seenPath = join(directory, \"hook-state\", `overseer-seen-${agentId}.json`);\n const digest = overseerDigest(file, await json(seenPath).catch(() => null));\n await save(seenPath, digest.seen);\n process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: \"UserPromptSubmit\", additionalContext: digest.text } }) + \"\\n\");\n return;\n }\n // scopes.json is a few KB; this hook runs on every tool call. Older workers don't write it: read state.json.\n const scopes = await json(join(directory, \"scopes.json\")).catch(() => null);\n let workspace = null; let contributor = false; let workflow;\n if (scopes?.agents) { const entry = scopes.agents[agentId]; if (entry && entry.role !== \"recovery\") { workspace = { id: entry.workspaceId }; contributor = entry.role === \"contributor\"; workflow = entry.workflow; } }\n else {\n const state = await json(join(directory, \"state.json\")).catch(() => ({ workspaces: [] }));\n workspace = state.workspaces.find(w => (w.mainAgentId === agentId || w.contributorAgentIds?.includes(agentId)) && w.enable_tracking && !w.archived) ?? null;\n contributor = !!workspace && workspace.mainAgentId !== agentId;\n }\n // The brief nudge applies to root agents launched with FOLLOW_THROUGH_BRIEF, tracked or not.\n const provider = process.env.FOLLOW_THROUGH_BRIEF || null;\n const brief = provider ? await json(join(directory, \"brief.json\")).catch(() => null) : null;\n if (!workspace && !(brief?.enable_inbox && brief?.enable_brief_nudge) && !(native && process.env.FOLLOW_THROUGH_ROOT === \"1\")) return;\n const context = () => instructions(lease, contributor, workflow);\n const sessionText = async () => [workspace ? context() : null, ...await nativeExtras(brief)].filter(Boolean).join(\"\\n\\n\");\n const name = event.hook_event_name;\n if (![\"SessionStart\", \"UserPromptSubmit\", \"PostToolUse\", \"Stop\"].includes(name)) return;\n const session = createHash(\"sha256\").update(String(event.session_id ?? agentId)).digest(\"hex\").slice(0, 24);\n const path = join(directory, \"hook-state\", `${agentId}-${session}.json`);\n const turn = await json(path).catch(() => null);\n const emit = text => process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: name, additionalContext: text } }) + \"\\n\");\n if (name === \"SessionStart\") {\n const text = await sessionText();\n if (text) { emit(text); await save(path, { ...turn, contextHash: digest(text) }); }\n return;\n }\n if (name === \"UserPromptSubmit\") {\n if (turn?.stopped && String(event.prompt ?? \"\").startsWith(stopReason)) return;\n const text = await sessionText(); const hash = text ? digest(text) : null;\n await save(path, { startedAt: Date.now(), dirtyAt: null, lastToolAt: null, stopped: false, quietRevision, contextHash: hash, ...(turn?.detachedNotice ? { detachedNotice: turn.detachedNotice } : {}) });\n if (text && shouldRepeat(process.env.FOLLOW_THROUGH_PROVIDER, turn, hash)) emit(text);\n return;\n }\n if (name === \"PostToolUse\") {\n // Said once per session per worker: the tools stay detached until the session reopens.\n const notice = detached && turn?.detachedNotice !== instance.instance;\n if (!workspace) {\n if (notice) { await save(path, { ...turn, detachedNotice: instance.instance }); emit(detachedNotice); }\n return;\n }\n const tool = String(event.tool_name ?? \"\");\n const args = JSON.stringify(event.tool_input ?? {});\n const trackedTool = isFollowTool(tool) || isBridgeCall(args, join(directory, \"mcp.mjs\"));\n const dirty = !trackedTool && /(bash|shell|exec_command|write_stdin|edit|write|apply_patch|notebook)/i.test(tool);\n const upgrade = turn?.quietRevision !== quietRevision;\n // A dirty call is dated from when it could have started (the previous tool's end), not when it ended: a call that\n // itself confirms sync, through any bridge spelling, then still satisfies the Stop check, which reads the\n // sync record the RPC handler wrote rather than tool names.\n const now = Date.now();\n const callStart = turn?.lastToolAt || turn?.startedAt || now;\n await save(path, { ...turn, startedAt: turn?.startedAt ?? (dirty ? callStart : 0), stopped: turn?.stopped ?? false, ...(dirty ? { dirtyAt: callStart } : {}), quietRevision, lastToolAt: now, ...(notice ? { detachedNotice: instance.instance } : {}) });\n const text = [upgrade ? quietInstruction : null, notice ? detachedNotice : null].filter(Boolean).join(\"\\n\\n\");\n if (text) emit(text);\n return;\n }\n if (event.stop_hook_active || turn?.stopped || event.background_tasks?.length) return;\n let sync = false;\n if (workspace) {\n const confirmed = await json(join(directory, \"hook-state\", `sync-${agentId}.json`)).catch(() => null);\n sync = !(turn && confirmed?.workspaceId === workspace.id && confirmed.at >= Math.max(turn.startedAt, turn.dirtyAt ?? 0));\n }\n const called = await json(join(directory, \"hook-state\", `needs-you-${agentId}.json`)).catch(() => null);\n const nudge = shouldNudge({ provider, brief, agentId, contributor, recovery: false, subagent: false, stopHookActive: !!event.stop_hook_active, turn, called });\n if (!sync && !nudge) return;\n await save(path, { ...turn, startedAt: turn?.startedAt ?? Date.now(), stopped: true, ...(nudge ? { nudgedAt: Date.now() } : {}) });\n const reasons = [detached ? detachedNotice : null, sync ? stopReason + \" This is metadata bookkeeping only; do not start queued repairs or recovery.\\n\\n\" + context() : null, nudge ? named(nudgeReason) : null].filter(Boolean);\n process.stdout.write(JSON.stringify({ decision: \"block\", reason: reasons.join(\"\\n\\n\") }) + \"\\n\");\n}\n// Tests import shouldNudge without running the hook.\nif (process.env.FOLLOW_THROUGH_HOOK_IMPORT !== \"1\") main().catch(() => {});\n";
2
+ export const hookSource = "#!/usr/bin/env node\nimport { readFile, writeFile, mkdir, rename } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { createHash, randomUUID } from \"node:crypto\";\n\nconst directory = dirname(fileURLToPath(import.meta.url));\n/** 1.4.0-beta.2: launched with Follow-up's tools served by Paseo's MCP (follow_<name>), or the follow-through bridge (<name>). Agents opened before the upgrade carry no flag and keep the bridge names. */\nlet native = process.env.FOLLOW_THROUGH_TOOLS === \"native\";\n// Tool names that read unambiguously in prose; kept identical to server/mcp.mjs's underscore names (a test checks it).\nexport 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\", \"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\", \"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\", \"onboarding_status\", \"onboarding_checks\", \"set_onboarding\", \"rank_status\", \"rerank_priorities\", \"overseer_status\", \"overseer_start\", \"overseer_restart\", \"overseer_ask\", \"inbox_brief\", \"brief_action\", \"inbox_act\", \"answer_question\", \"run_recovery\", \"set_workspace_spec\", \"set_task_trigger\", \"pr_controls\", \"browser_status\", \"trust_bypass_status\", \"make_main_agent\"];\nconst toolPattern = new RegExp(`(?<![\\\\w])(${TOOL_NAMES.join(\"|\")})(?![\\\\w])`, \"g\");\n/** Names Follow-up's tools the way this agent has them. */\nexport function named(text, isNative = native) { return isNative ? text.replace(toolPattern, \"follow_$1\") : text; }\n/** Whether a tool call is Follow-up's own, under either name set (mcp__follow-through__x, follow-through.x, mcp__paseo__follow_x, paseo.follow_x). */\nexport function isFollowTool(tool) { return /follow[\\s_-]*through/i.test(tool) || /^(?:mcp__paseo__|paseo[.:/])follow_[a-z_]+$/.test(tool); }\n/** Whether a shell call runs the bridge, however it names it ($FOLLOW_THROUGH_CLI, as the skill says, or the path). */\nexport function isBridgeCall(args, bridgePath) { return args.includes(bridgePath) || /\\$\\{?FOLLOW_THROUGH_CLI\\b/.test(args) || /mcp\\.mjs[\"']?\\s+call\\b/.test(args); }\n/**\n * Native tools are attached by one worker; a plugin reload or update drops them from open sessions until each reopens\n * (Paseo 0.15.2 reopens a session before that agent's next prompt). The worker records its instance and the instance\n * that attached each session's tools; a mismatch means this session's follow_ tools are gone. Pure, so it's testable.\n */\nexport function toolsDetached(isNative, current, mine) { return isNative && !!current?.instance && mine?.instance !== current.instance; }\nexport const detachedNotice = \"Follow-up was updated while this session was open, so its follow_* tools are detached and fail with \\\"Tool not found\\\" until this session reopens (Paseo reopens it before your next prompt). Until then use the bridge, which runs the same tools with their unprefixed names: node \\\"$FOLLOW_THROUGH_CLI\\\" call <tool> '<json>' --compact (for example sync_workspace or needs_you). Do not mention this to the developer.\";\nconst quietRevision = 1;\nconst quietInstruction = \"Do routine bookkeeping silently. Do not announce tracker calls, say you updated/synced the sidebar, recap panel state, or add plugin-status commentary/final paragraphs. Put receipts and evidence in the tools. User-facing messages should cover the actual work outcome, or a decision/blocker requiring the developer; answer sidebar status only when explicitly asked. If this continuation is bookkeeping only, use the tools and finish without another recap or repeating your previous answer.\";\nconst stopReason = \"Silently complete this workspace's sidebar bookkeeping before finishing.\";\n// Kept identical to NEEDS_YOU_NUDGE in shared/brief.ts (a test checks it).\nconst nudgeReason = \"Before you stop, call needs_you once with what the developer has to do next: a decision with options, an action only they can take, or kind=done (\\\"Nothing needed\\\" plus what you finished), which means nothing for the developer and won't flag you. Then stop; don't repeat your reply.\";\n\n/**\n * R2: whether to nudge a Claude Code root agent that ended its turn without needs_you. Pure, so every skip is testable.\n * At most once per turn: Claude's stop_hook_active and our own per-turn `stopped` marker both end it.\n */\nexport function shouldNudge({ provider, brief, agentId, contributor, recovery, subagent, stopHookActive, turn, called }) {\n if (provider !== \"claude\" || recovery || subagent || contributor || stopHookActive) return false;\n if (!brief || brief.enable_inbox !== true || brief.enable_brief_nudge !== true) return false;\n if (Array.isArray(brief.pending) && brief.pending.includes(agentId)) return false;\n if (!turn || turn.stopped || !turn.startedAt) return false;\n return !(called && called.at >= turn.startedAt);\n}\n/**\n * The Overseer's per-turn digest (1.4.0-beta.0). The daemon rewrites overseer-digest.json only when it changes (one line and a hash\n * per workspace); this diffs it against what the Overseer saw last turn. Pure, so size and paging are testable.\n * Kept to about 3k tokens: at most 20 needs lines and 30 changes, then a pointer to the workstreams tool.\n */\nexport function overseerDigest(file, seen, now = Date.now(), { needsMax = 20, changedMax = 30, restingMax = 40, chars = 12_000 } = {}) {\n const all = Array.isArray(file?.rows) ? file.rows : [];\n const rows = all.filter(r => !r.resting);\n const resting = all.filter(r => r.resting);\n const prior = seen && typeof seen.rows === \"object\" && seen.rows ? seen.rows : null;\n const age = Math.max(0, Math.round((now - Date.parse(file?.at ?? \"\")) / 1000));\n const lines = [`Follow-up digest (last change ${Number.isFinite(age) ? `${age}s` : \"?\"} ago): ${file?.total ?? all.length} workspaces, ${file?.needs ?? 0} need Tom. Paging: workstreams(page, group, query).`];\n const needs = rows.filter(r => r.group === \"needs\");\n if (needs.length) {\n lines.push(`Needs Tom (${needs.length}):`);\n for (const r of needs.slice(0, needsMax)) lines.push(`- ${r.line}`);\n if (needs.length > needsMax) lines.push(`- …${needs.length - needsMax} more: workstreams(group=\"needs\")`);\n } else lines.push(\"Nothing needs Tom right now.\");\n if (!prior) {\n const active = rows.filter(r => r.group === \"running\" || r.group === \"fixing\");\n lines.push(`First turn. Running now (${active.length}):`);\n for (const r of active.slice(0, changedMax)) lines.push(`- ${r.line}`);\n if (active.length > changedMax) lines.push(`- …${active.length - changedMax} more: workstreams(group=\"running\")`);\n } else {\n const current = new Set(all.map(r => r.id));\n const changed = rows.filter(r => prior[r.id] !== r.hash && r.group !== \"needs\");\n const gone = Object.keys(prior).filter(id => !current.has(id));\n lines.push(changed.length || gone.length ? `Changed since your last turn (${changed.length + gone.length}):` : \"No other changes since your last turn.\");\n for (const r of changed.slice(0, changedMax)) lines.push(`- [${r.group}] ${r.line}`);\n if (changed.length > changedMax) lines.push(`- …${changed.length - changedMax} more changed: workstreams()`);\n if (gone.length) lines.push(`- ${gone.length} workspace${gone.length === 1 ? \"\" : \"s\"} archived or removed: ${gone.slice(0, 5).join(\", \")}`);\n }\n if (resting.length) lines.push(`Resting (${resting.length}; agents likely unloaded, sending wakes them): ${resting.slice(0, restingMax).map(r => r.line).join(\"; \")}${resting.length > restingMax ? `; …${resting.length - restingMax} more: workstreams()` : \"\"}`);\n let text = \"\";\n for (const l of lines) { if (text.length + l.length + 1 > chars) { text += \"- …truncated: use workstreams()\\n\"; break; } text += l + \"\\n\"; }\n return { text: text.trimEnd(), seen: { at: now, rows: Object.fromEntries(all.map(r => [r.id, r.hash])) } };\n}\n/**\n * How batches are worked, for this workspace's PR workflow (from scopes.json). Graphite with /fix-pr, and agents of an\n * older worker that wrote no workflow, keep the original text; plain GitHub never mentions Graphite, gt or /fix-pr.\n */\nexport function batchParagraph(workflow) {\n const mode = workflow?.mode ?? \"graphite\";\n const fix = workflow === undefined || workflow === null ? \"/fix-pr\" : workflow.reviewFix ?? null;\n const steps = \"Follow-through batches contain a batch ID and task list. Read workspace_status and refresh live conditions before acting; skip resolved tasks. Process dependent PRs bottom to top, one PR fully before the next.\";\n const review = fix ? `Use the repository's ${fix} workflow, validate feedback, verify changes,` : \"For review comments, read the PR's unresolved threads with gh, validate the feedback, fix it and verify the change,\";\n const submit = mode === \"graphite\" ? \"submit through Graphite with --publish\" : \"push the branch (gh pr create for a new PR, gh pr ready when it leaves draft)\";\n const reply = fix ? \"reply/resolve addressed threads\" : \"reply to each addressed thread and resolve it\";\n const restack = mode === \"graphite\" ? \"Follow the repository's safe reparent procedure for merged parents\" : \"Keep stacked PRs as a chain of base branches: restack with git rebase --update-refs and push with --force-with-lease, and when a parent merges retarget its child with gh pr edit --base if GitHub didn't already\";\n return `${steps} ${review} ${submit}, and ${reply}. ${restack} and preserve uncommitted work.`;\n}\nconst quote = value => \"'\" + value.replaceAll(\"'\", \"'\\\\''\") + \"'\";\nasync function json(path) { return JSON.parse(await readFile(path, \"utf8\")); }\nasync function save(path, value) {\n await mkdir(dirname(path), { recursive: true, mode: 0o700 });\n const temporary = path + \".\" + randomUUID();\n await writeFile(temporary, JSON.stringify(value), { mode: 0o600 });\n await rename(temporary, path);\n}\nfunction instructions(lease, contributor = false, workflow) {\n return named(paragraphs(lease, contributor, workflow).filter(p => !(native && /^Prefer (?:the )?native/i.test(p))).join(\"\\n\\n\"));\n}\nfunction paragraphs(lease, contributor, workflow) {\n if (contributor) return [\n \"Maintain PR tracking for this session in its tracked workspace. Read workspace_status now and after compaction. Register every PR you submit, including from secondary git worktrees, with register_pr; register parents before children. References and external dependencies are not owned PRs. Call sync_workspace before finishing. The designated main agent retains goal, task, scope and completion authority.\",\n quietInstruction,\n `Prefer native Follow-through tools. CLI fallback: FOLLOW_THROUGH_CLIENT_ENTRY=${quote(lease.clientEntry)} node ${quote(join(directory, \"mcp.mjs\"))} call <tool> '<json>' --compact. Do not ask the developer to maintain the sidebar.`,\n ];\n return [\n \"Maintain this tracked workspace's Follow-through sidebar as part of your normal work; do not wait for a developer reminder.\",\n quietInstruction,\n \"Read workspace_status now and after compaction. Refine the goal with enroll_workspace when scope changes. Register every PR you produce after submitting it, parents before children, and update stack/parent relationships after restacking. Historical mentions and external dependencies are not owned PRs; preserve exclusions and existing records.\",\n \"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. 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; if the developer answers in chat, call record_answer. Withdraw questions that stop mattering.\",\n \"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.\",\n \"Keep actual follow-through 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.\",\n \"Stakeholder replies are follow-through 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.\",\n \"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.\",\n 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. Verify the entire goal and post-merge work before declare_done; acknowledge a completion batch first. Merging and archiving remain the developer's actions.\",\n \"Before ending this turn, reconcile the sidebar with what you actually did and call sync_workspace with a short summary, including when no changes are needed. Acknowledge any assigned batch. When the entire goal is fulfilled, use declare_done; otherwise preserve remaining work. Do not launch recovery, start queued repairs, merge, toggle merge-when-ready, or archive as part of this bookkeeping. Auto still governs separate follow-up sends. Subagents report to the main agent instead of claiming workspace ownership.\",\n `Prefer the native follow-through MCP tools. For a full historical record, use workspace_status with detail=full. CLI compatibility fallback: FOLLOW_THROUGH_CLIENT_ENTRY=${quote(lease.clientEntry)} node ${quote(join(directory, \"mcp.mjs\"))} call <tool> '<json>' --compact. Omit --compact only when an existing script needs the full response. Never ask the developer to maintain the sidebar or run this bridge.`,\n ];\n}\n/** The old main's notice, within a day of losing the role: who took over, why, and what to do. Null otherwise. */\nexport function demotedNotice(demoted, now = Date.now()) {\n if (!demoted?.at || now - Date.parse(demoted.at) > 24 * 60 * 60_000) return null;\n const time = new Date(demoted.at).toISOString().slice(11, 16);\n const who = demoted.by === \"developer\" ? \"the developer moved it\" : demoted.by === \"auto\" ? \"Follow-up moved it\" : \"it was claimed\";\n return { at: demoted.at, text: `You're no longer this workspace's main agent: ${demoted.to} took over at ${time} UTC (${who}${demoted.reason ? `: ${demoted.reason}` : \"\"}). Report to it instead of asking the developer or calling Done. If that's wrong, ask the developer to make you main again; you can't take it back on your own for 2 hours.` };\n}\n\n/** With native tools there's no MCP initialize reply, so the role text it carried comes from the hook instead. */\nasync function nativeExtras(brief) {\n if (!native) return [];\n const bridge = await import(pathToFileURL(join(directory, \"mcp.mjs\")).href).catch(() => null);\n if (!bridge) return [];\n return [\n brief?.enable_inbox && process.env.FOLLOW_THROUGH_BRIEF ? bridge.needsYouInstruction : null,\n process.env.FOLLOW_THROUGH_ROOT === \"1\" ? bridge.actionInstruction : null,\n process.env.FOLLOW_THROUGH_OVERSEER === \"1\" ? bridge.overseerInstruction : null,\n ].filter(Boolean).map(text => named(text));\n}\n/**\n * Claude Code keeps hook context for the whole session and re-runs SessionStart after compaction, so the same text\n * on every prompt only costs tokens (~1.3k per turn for a tracked main agent): send it once per session and again\n * only when it changes. Other providers keep the per-prompt text.\n */\nexport function shouldRepeat(provider, turn, hash) { return provider !== \"claude\" || turn?.contextHash !== hash; }\nconst digest = text => createHash(\"sha256\").update(text).digest(\"hex\").slice(0, 16);\nasync function main() {\n const agentId = process.env.PASEO_AGENT_ID;\n if (!agentId || !/^[\\w-]+$/.test(agentId) || process.env.FOLLOW_THROUGH_RECOVERY === \"1\") return;\n let input = \"\";\n for await (const chunk of process.stdin) { input += chunk; if (input.length > 2_000_000) return; }\n const event = JSON.parse(input);\n if (event.agent_id || event.hook_event_name === \"SubagentStop\") return;\n const lease = await json(join(directory, \"hooks-enabled.json\"));\n if (lease.expiresAt < Date.now() || !lease.clientEntry) return;\n const instance = native ? await json(join(directory, \"tools-instance.json\")).catch(() => null) : null;\n const detached = toolsDetached(native, instance, native ? await json(join(directory, \"hook-state\", `native-${agentId}.json`)).catch(() => null) : null);\n // Detached: name the bridge's tools everywhere below, and include the bridge paragraph.\n if (detached) native = false;\n // The Overseer: a fresh digest at the start of every turn; no sidebar bookkeeping and no Stop-hook nudge.\n if (process.env.FOLLOW_THROUGH_OVERSEER === \"1\") {\n if (event.hook_event_name === \"SessionStart\") {\n const extras = await nativeExtras(await json(join(directory, \"brief.json\")).catch(() => null));\n if (extras.length) process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: \"SessionStart\", additionalContext: extras.join(\"\\n\\n\") } }) + \"\\n\");\n return;\n }\n if (event.hook_event_name !== \"UserPromptSubmit\") return;\n const file = await json(join(directory, \"overseer-digest.json\")).catch(() => null);\n if (!file || file.agentId !== agentId) return;\n const seenPath = join(directory, \"hook-state\", `overseer-seen-${agentId}.json`);\n const digest = overseerDigest(file, await json(seenPath).catch(() => null));\n await save(seenPath, digest.seen);\n process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: \"UserPromptSubmit\", additionalContext: digest.text } }) + \"\\n\");\n return;\n }\n // scopes.json is a few KB; this hook runs on every tool call. Older workers don't write it: read state.json.\n const scopes = await json(join(directory, \"scopes.json\")).catch(() => null);\n let workspace = null; let contributor = false; let workflow; let demoted = null;\n if (scopes?.agents) { const entry = scopes.agents[agentId]; if (entry && entry.role !== \"recovery\") { workspace = { id: entry.workspaceId }; contributor = entry.role === \"contributor\"; workflow = entry.workflow; demoted = contributor ? demotedNotice(entry.demoted) : null; } }\n else {\n const state = await json(join(directory, \"state.json\")).catch(() => ({ workspaces: [] }));\n workspace = state.workspaces.find(w => (w.mainAgentId === agentId || w.contributorAgentIds?.includes(agentId)) && w.enable_tracking && !w.archived) ?? null;\n contributor = !!workspace && workspace.mainAgentId !== agentId;\n }\n // The brief nudge applies to root agents launched with FOLLOW_THROUGH_BRIEF, tracked or not.\n const provider = process.env.FOLLOW_THROUGH_BRIEF || null;\n const brief = provider ? await json(join(directory, \"brief.json\")).catch(() => null) : null;\n if (!workspace && !(brief?.enable_inbox && brief?.enable_brief_nudge) && !(native && process.env.FOLLOW_THROUGH_ROOT === \"1\")) return;\n const context = () => instructions(lease, contributor, workflow);\n const sessionText = async () => [workspace ? context() : null, ...await nativeExtras(brief)].filter(Boolean).join(\"\\n\\n\");\n const name = event.hook_event_name;\n if (![\"SessionStart\", \"UserPromptSubmit\", \"PostToolUse\", \"Stop\"].includes(name)) return;\n const session = createHash(\"sha256\").update(String(event.session_id ?? agentId)).digest(\"hex\").slice(0, 24);\n const path = join(directory, \"hook-state\", `${agentId}-${session}.json`);\n const turn = await json(path).catch(() => null);\n const emit = text => process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: name, additionalContext: text } }) + \"\\n\");\n if (name === \"SessionStart\") {\n const text = await sessionText();\n if (text) { emit(text); await save(path, { ...turn, contextHash: digest(text) }); }\n return;\n }\n if (name === \"UserPromptSubmit\") {\n if (turn?.stopped && String(event.prompt ?? \"\").startsWith(stopReason)) return;\n const text = await sessionText(); const hash = text ? digest(text) : null;\n // Lost the main role (make_main_agent, Make main agent, or a handover): said once, on the next turn.\n const tellDemoted = demoted && turn?.demotedNotice !== demoted.at;\n await save(path, { startedAt: Date.now(), dirtyAt: null, lastToolAt: null, stopped: false, quietRevision, contextHash: hash, ...(turn?.detachedNotice ? { detachedNotice: turn.detachedNotice } : {}), ...(tellDemoted || turn?.demotedNotice ? { demotedNotice: tellDemoted ? demoted.at : turn.demotedNotice } : {}) });\n const out = [text && shouldRepeat(process.env.FOLLOW_THROUGH_PROVIDER, turn, hash) ? text : null, tellDemoted ? demoted.text : null].filter(Boolean);\n if (out.length) emit(out.join(\"\\n\\n\"));\n return;\n }\n if (name === \"PostToolUse\") {\n // Said once per session per worker: the tools stay detached until the session reopens.\n const notice = detached && turn?.detachedNotice !== instance.instance;\n if (!workspace) {\n if (notice) { await save(path, { ...turn, detachedNotice: instance.instance }); emit(detachedNotice); }\n return;\n }\n const tool = String(event.tool_name ?? \"\");\n const args = JSON.stringify(event.tool_input ?? {});\n const trackedTool = isFollowTool(tool) || isBridgeCall(args, join(directory, \"mcp.mjs\"));\n const dirty = !trackedTool && /(bash|shell|exec_command|write_stdin|edit|write|apply_patch|notebook)/i.test(tool);\n const upgrade = turn?.quietRevision !== quietRevision;\n // A dirty call is dated from when it could have started (the previous tool's end), not when it ended: a call that\n // itself confirms sync, through any bridge spelling, then still satisfies the Stop check, which reads the\n // sync record the RPC handler wrote rather than tool names.\n const now = Date.now();\n const callStart = turn?.lastToolAt || turn?.startedAt || now;\n await save(path, { ...turn, startedAt: turn?.startedAt ?? (dirty ? callStart : 0), stopped: turn?.stopped ?? false, ...(dirty ? { dirtyAt: callStart } : {}), quietRevision, lastToolAt: now, ...(notice ? { detachedNotice: instance.instance } : {}) });\n const text = [upgrade ? quietInstruction : null, notice ? detachedNotice : null].filter(Boolean).join(\"\\n\\n\");\n if (text) emit(text);\n return;\n }\n if (event.stop_hook_active || turn?.stopped || event.background_tasks?.length) return;\n let sync = false;\n if (workspace) {\n const confirmed = await json(join(directory, \"hook-state\", `sync-${agentId}.json`)).catch(() => null);\n sync = !(turn && confirmed?.workspaceId === workspace.id && confirmed.at >= Math.max(turn.startedAt, turn.dirtyAt ?? 0));\n }\n const called = await json(join(directory, \"hook-state\", `needs-you-${agentId}.json`)).catch(() => null);\n const nudge = shouldNudge({ provider, brief, agentId, contributor, recovery: false, subagent: false, stopHookActive: !!event.stop_hook_active, turn, called });\n if (!sync && !nudge) return;\n await save(path, { ...turn, startedAt: turn?.startedAt ?? Date.now(), stopped: true, ...(nudge ? { nudgedAt: Date.now() } : {}) });\n const reasons = [detached ? detachedNotice : null, sync ? stopReason + \" This is metadata bookkeeping only; do not start queued repairs or recovery.\\n\\n\" + context() : null, nudge ? named(nudgeReason) : null].filter(Boolean);\n process.stdout.write(JSON.stringify({ decision: \"block\", reason: reasons.join(\"\\n\\n\") }) + \"\\n\");\n}\n// Tests import shouldNudge without running the hook.\nif (process.env.FOLLOW_THROUGH_HOOK_IMPORT !== \"1\") main().catch(() => {});\n";
@@ -1,2 +1,2 @@
1
1
  // Generated by scripts/build.mjs.
2
- export const mcpSource = "#!/usr/bin/env node\nimport { createInterface } from \"node:readline\";\nimport { createRequire } from \"node:module\";\nimport { pathToFileURL } from \"node:url\";\nimport { readFile, stat } from \"node:fs/promises\";\nimport { existsSync, realpathSync } from \"node:fs\";\nimport { join, delimiter } from \"node:path\";\nimport { homedir } from \"node:os\";\n\nconst string = { type: \"string\" };\nconst boolean = { type: \"boolean\" };\nconst integer = { type: \"integer\", minimum: 1 };\nconst array = { type: \"array\", items: string };\nconst communication = { type: \"object\", properties: { threadUrl: string, recipient: string, purpose: { type: \"string\", enum: [\"progress\", \"verified\"] }, authorization: string, replyUrl: { type: [\"string\", \"null\"] } }, required: [\"threadUrl\", \"recipient\"], additionalProperties: false };\nconst trigger = { type: [\"object\", \"null\"], properties: { event: { type: \"string\", enum: [\"now\", \"merge\", \"deploy\"] }, delayDays: { type: \"integer\", minimum: 0, maximum: 3650 } }, required: [\"event\"], additionalProperties: false };\nconst tools = [\n [\"workspace_status\", \"Read the tracked workspace's durable goal, PRs, tasks, work queue and optional recovery history. Read after compaction. Returns current work by default; detail=full includes complete evidence/history. Normal follow-through does not require recovery.\", \"follow.agent-status\", { detail: { type: \"string\", enum: [\"summary\", \"full\"] } }, []],\n [\"sync_workspace\", \"Silently confirm the sidebar matches your work before finishing, after registering owned PRs and substantive tasks. Call even when no changes are needed. Keep the summary in this tool; never announce sync or recap sidebar/plugin status to the developer. Does not declare Done, run recovery, or start repairs. Tracked root agents only.\", \"follow.sync\", { summary: { ...string, minLength: 1, maxLength: 1000 } }, [\"summary\"]],\n [\"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\"]],\n [\"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.\", \"follow.register-pr\", { repo: string, number: integer, stack: string, parentNumber: { type: [\"integer\", \"null\"], minimum: 1 }, disposition: string }, [\"repo\", \"number\", \"stack\"]],\n [\"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\"]],\n [\"update_obligation\", \"Record concrete follow-through: 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.\", \"follow.obligation\", { id: string, title: string, status: { type: \"string\", enum: [\"pending\", \"waiting\", \"working\", \"blocked\", \"done\", \"waived\"] }, afterPrs: array, dependencyStage: { type: \"string\", enum: [\"merged\", \"deployed\"] }, evidence: string, enable_follow_up: boolean, communication, trigger }, [\"title\", \"status\"]],\n [\"acknowledge_batch\", \"Record a follow-up result. Complete only after verifying all tasks; blocked surfaces the reason to the developer. 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 } }, [\"batchId\", \"outcome\", \"result\"]],\n [\"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.\", \"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 }, [\"title\", \"question\"]],\n [\"record_answer\", \"Record the developer's answer when they answered a question in chat instead of in Follow-up. choice is an option letter, 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\"]],\n [\"withdraw_question\", \"Withdraw a question that no longer matters, with a short reason.\", \"follow.withdraw-question\", { id: string, reason: string }, [\"id\", \"reason\"]],\n [\"set_spec\", \"Register the link to this workspace's spec: the Claude artifact (or doc) you keep summarizing the goal, decisions and status. Call it once after the first publish, with the URL from the publish result, and again only if the link changes. Follow-up shows it in the workspace header.\", \"follow.set-spec\", { url: { ...string, maxLength: 2000 }, title: { ...string, maxLength: 120 } }, [\"url\"]],\n [\"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), 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 } }, 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\"]],\n [\"declare_done\", \"Declare that the workspace goal is fulfilled. Live PR status and remaining obligations are checked; returned blockers must be resolved first. Done labels the workspace but never archives it.\", \"follow.done\", { summary: string }, [\"summary\"]],\n];\n\n// Agent parity: every action the developer can click in Follow-up, through the same server path (follow.agent-act).\n// Planned tools return a dry run; confirm=true with its planId runs it. Use them only when the developer asked.\nconst planned = { planId: string, confirm: boolean };\nconst prKey = { ...string, description: \"owner/repo#number, from list_prs\" };\nconst ask = \" Only when the developer asked for it. Returns a dry-run plan first; run it with confirm=true and the planId.\";\nconst read = \" Read-only.\";\nconst actionTools = [\n [\"list_prs\", \"List tracked PRs across all workspaces with state, draft, checks, open threads, requested reviewers and merge blockers. Filters: needs_reviewers, ready_to_merge, workspace (id or title). This is how you act \\\"on all\\\".\", \"follow.agent-act\", { workspace: string, needs_reviewers: boolean, ready_to_merge: boolean, include_closed: boolean }, []],\n [\"add_reviewers\", \"Request reviewers on one or many PRs, the same as the Add reviewers button. Without reviewers, asks the developer's saved reviewers for that repository (each PR row in list_prs shows them as configuredReviewers, with source repo, default or none); otherwise the GitHub logins or org/team slugs you give.\" + ask, \"follow.agent-act\", { prs: { type: \"array\", items: prKey }, reviewers: array, ...planned }, []],\n [\"merge\", \"Merge a PR (and its downstack with scope=downstack) through Graphite, using Follow-up's merge plan and blockers. Can't be undone.\" + ask, \"follow.agent-act\", { pr: prKey, scope: { type: \"string\", enum: [\"target\", \"downstack\"] }, ...planned }, []],\n [\"enable_merge_when_ready\", \"Turn on Graphite merge-when-ready for a PR, as the PR sheet does.\" + ask, \"follow.agent-act\", { pr: prKey, scope: { type: \"string\", enum: [\"target\", \"downstack\"] }, ...planned }, []],\n [\"disable_merge_when_ready\", \"Turn off Graphite merge-when-ready for a PR.\" + ask, \"follow.agent-act\", { pr: prKey, scope: { type: \"string\", enum: [\"target\", \"downstack\"] }, ...planned }, []],\n [\"send_repairs\", \"Send a workspace's waiting repairs (review threads, failed checks) to its main agent, like the Send button. Only when the developer asked. batchId defaults to the waiting batch.\", \"follow.agent-act\", { workspace: string, batchId: string }, [\"workspace\"]],\n [\"set_auto_send\", \"Turn Auto-send on or off for a workspace, like its switch. Only when the developer asked.\", \"follow.agent-act\", { workspace: string, value: boolean }, [\"workspace\", \"value\"]],\n [\"clear_hold\", \"Resume Follow-up on a held workspace, like the Resume button. Only when the developer asked.\", \"follow.agent-act\", { workspace: string }, [\"workspace\"]],\n [\"retry_batch\", \"Queue a blocked or uncertain repair batch again, like the Retry button. Only when the developer asked.\", \"follow.agent-act\", { workspace: string, batchId: string }, [\"workspace\", \"batchId\"]],\n [\"track\", \"Follow a workspace again after the developer opted it out in Settings. Follow-up follows every workspace by default. Only when the developer asked.\", \"follow.agent-act\", { workspace: string }, [\"workspace\"]],\n [\"workspace_about\", \"Read what a workspace is about: a short AI overview (goal, where it stands, what's left), a one-line gist, and its linked Linear issues, PRs, Slack threads and docs. Read-only; writes the overview first when none is cached (up to ~90 s). workspaceId is a workspace id or exact title from list_prs.\", \"follow.agent-act\", { workspaceId: string }, [\"workspaceId\"]],\n [\"agent_settings\", \"Read which agent each of Follow-up's special roles uses (What's this about?, Overseer, Recovery, Priority ranker): provider, model, effort, mode and limits. Read-only; Tom changes them in Follow-up settings → Agents.\", \"follow.agent-act\", {}, []],\n [\"inbox_list\", \"Read the developer's Needs-you inbox: each root agent, whether it is flagged and why, snoozes and finish flags. Your own row has self=true.\", \"follow.agent-act\", { flagged_only: boolean }, []],\n [\"sign_off\", \"Sign off other agents' Needs-you flags on the developer's behalf, like Sign off. Never your own.\" + ask, \"follow.agent-act\", { agentIds: array, ...planned }, []],\n [\"snooze\", \"Snooze other agents' flags (until: next-event, 1h, tomorrow or an ISO time), like Later.\" + ask, \"follow.agent-act\", { agentIds: array, until: string, ...planned }, []],\n [\"set_finish_flags\", \"Turn finish flags on or off for other agents, like Don't flag finishes.\" + ask, \"follow.agent-act\", { agentIds: array, value: boolean, ...planned }, []],\n [\"set_priorities\", \"Rank workspaces for Home's Priority sort: per workspace (id or exact title) a score 0-100, a one-line reason the developer sees, and its sources [{kind: linear|slack|planning|github|paseo, label, url}]. replace=true drops workspaces you leave out. Used for 6 hours. Returns a dry run; store it with confirm=true and the planId.\", \"follow.agent-act\", { priorities: { type: \"array\", items: { type: \"object\", properties: { workspace: string, score: { type: \"integer\", minimum: 0, maximum: 100 }, reason: { ...string, maxLength: 140 }, sources: { type: \"array\", items: { type: \"object\", properties: { kind: { type: \"string\", enum: [\"linear\", \"slack\", \"planning\", \"github\", \"paseo\"] }, label: string, url: string }, required: [\"kind\", \"label\"] } } }, required: [\"workspace\", \"score\", \"reason\"] } }, replace: boolean, ...planned }, [\"priorities\"]],\n // Settings, onboarding, Home and the panel, one developer RPC each (server/agent-parity.ts). Writes plan first.\n [\"display_settings\", \"Read Settings → Display: the header button, sidebar item, composer pill, Needs-you inbox, closed-PR flags, brief nudge, Overseer, ranker and trust bypass switches.\" + read, \"follow.agent-act\", {}, []],\n [\"set_display\", \"Change Settings → Display switches, e.g. { values: { enable_trust_bypass: false } }. Keys from display_settings.\" + ask, \"follow.agent-act\", { values: { type: \"object\", additionalProperties: boolean }, ...planned }, []],\n [\"follow_settings\", \"Read Settings → Following: follow every workspace, the Auto-send default, the active window, and per-workspace exceptions.\" + read, \"follow.agent-act\", {}, []],\n [\"set_follow_settings\", \"Change Settings → Following: enable_follow_every, enable_auto_sends_default, activeWindowDays (1-60), or one workspace's exception { workspaceId, follow, enable_auto_sends }.\" + ask, \"follow.agent-act\", { enable_follow_every: boolean, enable_auto_sends_default: boolean, activeWindowDays: { type: \"integer\", minimum: 1, maximum: 60 }, workspace: { type: \"object\" }, ...planned }, []],\n [\"project_settings\", \"Read each project and whether Follow-up follows its new workspaces by default.\" + read, \"follow.agent-act\", {}, []],\n [\"set_project_tracking\", \"Follow a project's new workspaces by default, or stop: { projectId, enable_default_tracking }.\" + ask, \"follow.agent-act\", { projectId: string, enable_default_tracking: boolean, ...planned }, []],\n [\"pr_workflow\", \"Read Settings → Following → Shipping PRs: each repository's PR workflow (graphite or github), merge method and review-fix setting, and the default. refresh=true re-detects.\" + read, \"follow.agent-act\", { refresh: boolean }, []],\n [\"set_pr_workflow\", \"Change Shipping PRs: per repository (repo owner/name) its setting, mergeMethod or reviewFix (null clears back to the default), or the default.\" + ask, \"follow.agent-act\", { repo: string, setting: { type: [\"string\", \"null\"] }, default: string, mergeMethod: { type: [\"string\", \"null\"] }, reviewFix: { type: [\"object\", \"null\"] }, ...planned }, []],\n [\"reviewer_settings\", \"Read Settings → Reviewers: the default reviewers and each repository's own list.\" + read, \"follow.agent-act\", {}, []],\n [\"reviewer_suggestions\", \"Suggest reviewers for a repository (owner/name) from its recent history.\" + read, \"follow.agent-act\", { repo: string }, [\"repo\"]],\n [\"save_reviewers\", \"Save the reviewers Add reviewers asks: repo owner/name, or null for the default; reviewers [{ login, name?, kind? }].\" + ask, \"follow.agent-act\", { repo: { type: [\"string\", \"null\"] }, reviewers: { type: \"array\", items: { type: \"object\" } }, ...planned }, []],\n [\"set_agent_setting\", \"Change which agent a special role uses (Settings → Agents): role about|overseer|recovery|ranker, entry { provider, model, ... } or null for the default. agent_settings shows the current ones.\" + ask, \"follow.agent-act\", { role: string, entry: { type: [\"object\", \"null\"] }, ...planned }, []],\n [\"onboarding_status\", \"Read the setup guide's state: whether it was finished or skipped, and the current step.\" + read, \"follow.agent-act\", {}, []],\n [\"onboarding_checks\", \"Run the setup checks (GitHub login, providers, ...) and return each result with its fix. fresh=true re-runs them.\" + read, \"follow.agent-act\", { fresh: boolean }, []],\n [\"set_onboarding\", \"Move the setup guide: action start|step|finish|skip|restart|dismiss-offer, step for action=step.\" + ask, \"follow.agent-act\", { action: string, step: string, ...planned }, []],\n [\"priorities\", \"Read the stored priorities behind Home's Priority sort.\" + read, \"follow.agent-act\", {}, []],\n [\"rank_status\", \"Read the priority ranker's state: last run, whether it's running, and errors.\" + read, \"follow.agent-act\", {}, []],\n [\"rerank_priorities\", \"Re-rank Home's Priority sort now, like Re-rank. force=true re-runs even when nothing changed.\" + ask, \"follow.agent-act\", { force: boolean, ...planned }, []],\n [\"usage\", \"Read provider usage limits and the VM's memory meter, as Home shows them.\" + read, \"follow.agent-act\", {}, []],\n [\"overseer_status\", \"Read the Overseer's state: running, its agent and model, and what a restart would use.\" + read, \"follow.agent-act\", {}, []],\n [\"overseer_start\", \"Start the Overseer, like Start on Home.\" + ask, \"follow.agent-act\", { ...planned }, []],\n [\"overseer_restart\", \"Restart the Overseer (with the model Settings → Agents names now).\" + ask, \"follow.agent-act\", { ...planned }, []],\n [\"overseer_ask\", \"Send the developer's words to the Overseer, as its box on Home does: { text }.\" + ask, \"follow.agent-act\", { text: string, ...planned }, []],\n [\"inbox_brief\", \"Read another agent's full Needs-you brief (decisions, options, links): { agentId }.\" + read, \"follow.agent-act\", { agentId: string }, [\"agentId\"]],\n [\"brief_action\", \"Answer another agent's brief for the developer, like its card: { agentId, briefId, decisionId + choice, or choices [{ decisionId, choice }], or move: retry }. Never your own brief.\" + ask, \"follow.agent-act\", { agentId: string, briefId: string, decisionId: string, choice: string, move: string, choices: { type: \"array\", items: { type: \"object\" } }, ...planned }, []],\n [\"inbox_act\", \"The inbox's other actions on other agents' rows: action undo|mute_turn|unsorted_flag|unsorted_sign_off|batch_undo, agentIds.\" + ask, \"follow.agent-act\", { action: string, agentIds: array, muteTurn: boolean, ...planned }, []],\n [\"answer_question\", \"Send the developer's answer to another agent's question (Q1…), like its card: { workspaceId, questionId, choice, words }. For a question you asked, use record_answer.\" + ask, \"follow.agent-act\", { workspaceId: string, questionId: string, choice: string, words: string, ...planned }, []],\n [\"run_recovery\", \"Run recovery on a workspace, like Run recovery: a separate agent reads its history for missed PRs and tasks. { workspaceId }.\" + ask, \"follow.agent-act\", { workspaceId: string, ...planned }, []],\n [\"refresh\", \"Refresh PR status now, like Refresh. Cheap; use when status looks stale.\", \"follow.agent-act\", { workspaceId: string }, []],\n [\"set_workspace_spec\", \"Set, remove or reset any workspace's spec link: { workspaceId, action set|remove|reset, url, title }.\" + ask, \"follow.agent-act\", { workspaceId: string, action: string, url: string, title: { type: [\"string\", \"null\"] }, ...planned }, []],\n [\"set_task_trigger\", \"Schedule a task to run now, on merge or on deploy (trigger { event, delayDays } or null), with afterPrs: { workspaceId, obligationId, expectedRevision, trigger, afterPrs }.\" + ask, \"follow.agent-act\", { workspaceId: string, obligationId: string, expectedRevision: { type: \"integer\", minimum: 0 }, trigger, afterPrs: array, ...planned }, []],\n [\"pr_controls\", \"Read a PR's merge controls as the PR sheet shows them (Send to Paseo pairing, Graphite in Chrome): { workspaceId, prKey }.\" + read, \"follow.agent-act\", { workspaceId: string, prKey }, [\"workspaceId\", \"prKey\"]],\n [\"browser_status\", \"Read whether Send to Paseo is paired and which repositories it may control.\" + read, \"follow.agent-act\", {}, []],\n [\"trust_bypass_status\", \"Read how many permission prompts trust bypass approved today, and the latest ones.\" + read, \"follow.agent-act\", {}, []],\n];\n// The Overseer's routing tools (1.4.0-beta.0): only in the session Follow-up started as its Overseer.\nconst overseerTools = [\n [\"workstreams\", \"Every workspace Tom has, as Home groups them (needs, fixing, running, waiting, later, quiet): title, branch, PRs with checks, main agent and status, current ask, last activity, priority and reason, Linear keys. Paged (page, size ≤100); filter by group or query (name, branch, key, #PR).\", \"follow.overseer-act\", { page: integer, size: integer, group: { type: \"string\", enum: [\"needs\", \"fixing\", \"running\", \"waiting\", \"later\", \"quiet\"] }, query: string }, []],\n [\"agent_digest\", \"One agent's last steps (default 10) summarised, its status and its open asks to Tom (flag, decisions, questions). Use before routing when the digest isn't enough.\", \"follow.overseer-act\", { agentId: string, steps: integer }, [\"agentId\"]],\n [\"route_candidates\", \"Score every workspace for Tom's ask by Linear key, PR number, branch, workspace name, open asks and recent activity. Returns the top 3 and whether one is a confident match.\", \"follow.overseer-act\", { ask: string }, [\"ask\"]],\n [\"send_to_agent\", \"Forward Tom's words to the agent that owns the work, prefixed \\\"From Tom via Overseer:\\\". reply_to_ask=true only when Tom is answering that agent's open ask (it then clears its Needs-you flag). Then tell Tom where it went in one line.\", \"follow.overseer-act\", { agentId: string, text: string, reply_to_ask: boolean }, [\"agentId\", \"text\"]],\n [\"start_workspace\", \"Start a new workspace with an agent for a task, branched off main with the default model. Only when Tom asked for a new workspace or picked it. Returns a dry run (title from the task and Linear key, branch, project); run it with confirm=true and the planId.\", \"follow.overseer-act\", { task: string, title: string, project: string, linear_key: string, base: string, planId: string, confirm: boolean }, []],\n [\"rerank\", \"Re-rank Home's Priority sort now from Linear, Slack, GitHub review requests and the weekly plan, when Tom asks for it. Returns the top 10 with their reasons. Skips the model when nothing changed.\", \"follow.overseer-act\", {}, []],\n];\nconst overseerNames = new Set(overseerTools.map(t => t[0]));\nconst overseerInstruction = \"You are Follow-up's Overseer. Route Tom's asks with route_candidates and send_to_agent; ask with needs_you kind=decision when unsure; start_workspace only when Tom asked or approved. Never merge, post to people or archive.\";\nconst actionNames = new Set(actionTools.map(t => t[0]));\nconst readOnlyTools = new Set([\"workspace_status\", \"list_prs\", \"inbox_list\", \"workstreams\", \"agent_digest\", \"route_candidates\", \"workspace_about\", \"agent_settings\", \"display_settings\", \"follow_settings\", \"project_settings\", \"pr_workflow\", \"reviewer_settings\", \"reviewer_suggestions\", \"onboarding_status\", \"onboarding_checks\", \"priorities\", \"rank_status\", \"usage\", \"overseer_status\", \"inbox_brief\", \"pr_controls\", \"browser_status\", \"trust_bypass_status\"]);\nconst destructiveTools = new Set([\"merge\"]);\nconst actionInstruction = \"Follow-up's action tools let you do anything the developer can click, across every tracked workspace and every Settings tab. Read freely: list_prs, inbox_list, inbox_brief, workspace_about, agent_settings, display_settings, follow_settings, project_settings, pr_workflow, reviewer_settings, onboarding_status, priorities, rank_status, usage, overseer_status, pr_controls. Act only when the developer asks (\\\"the PRs look good, assign reviewers on all\\\": list_prs needs_reviewers=true, add_reviewers with those keys, then confirm the plan): add_reviewers, merge, enable/disable_merge_when_ready, send_repairs, set_auto_send, clear_hold, retry_batch, track, run_recovery, set_priorities, rerank_priorities; settings with set_display (trust bypass too), set_follow_settings, set_project_tracking, set_pr_workflow, save_reviewers, set_agent_setting, set_onboarding; and sign_off/snooze/set_finish_flags/inbox_act/brief_action/answer_question for other agents. Planned tools return a dry run showing what changes; run it with confirm=true and its planId. Never sign yourself off or answer your own brief.\";\n\n// The brief's tool: every root agent while the Needs-you inbox is on; never contributors, recovery or subagents.\n// Kept identical to NEEDS_YOU_INSTRUCTION in shared/brief.ts (a test checks it).\nconst needsYouInstruction = \"When you end a turn, call `needs_you` once, just before your final reply, with what the developer has to do next: a decision (give 2–3 options, what each means for them, and the one you recommend), an action only they can take (merge, approve, log in, run or send something), or kind=done (\\\"Nothing needed\\\" plus what you finished, in one line), which means there is nothing for the developer and won't flag you in their inbox. Keep `ask` to one line and `context` to what they need to decide. Don't repeat your report there; still write your normal reply. Don't call it while a permission prompt is waiting or while you're still working.\";\nfunction toolList(recovery = process.env.FOLLOW_THROUGH_RECOVERY === \"1\", contributor = false, brief = false, briefOnly = false, actions = false) {\n // Action tools: root agents (tracked main or untracked) while Follow-up runs; never recovery or contributors.\n const acting = actions && !recovery && !contributor ? actionTools : [];\n if (briefOnly) return [...(brief ? tools.filter(t => t[0] === \"needs_you\") : []), ...acting];\n return [...tools.filter(t => t[0] === \"needs_you\" ? brief && !recovery && !contributor : contributor ? [\"workspace_status\", \"register_pr\", \"sync_workspace\"].includes(t[0]) : !recovery || ![\"declare_done\", \"sync_workspace\", \"ask_question\", \"record_answer\", \"withdraw_question\", \"set_spec\"].includes(t[0])), ...acting];\n}\n/** Whether this session may call needs_you: launched as a root agent (FOLLOW_THROUGH_BRIEF) and the inbox is on. */\nasync function briefEnabled() {\n if (!process.env.FOLLOW_THROUGH_BRIEF || process.env.FOLLOW_THROUGH_RECOVERY === \"1\") return false;\n try {\n const directory = join(process.env.PASEO_HOME ?? join(homedir(), \".paseo\"), \"plugin-data/follow-through\");\n const lease = JSON.parse(await readFile(join(directory, \"hooks-enabled.json\"), \"utf8\"));\n if (!(lease.expiresAt > Date.now())) return false;\n const brief = JSON.parse(await readFile(join(directory, \"brief.json\"), \"utf8\"));\n return brief?.enable_inbox === true;\n } catch { return false; }\n}\n/**\n * Merge and merge-when-ready say how they run. \"github\": every known repository ships plain GitHub, so Graphite is\n * never named; \"mixed\": either, per list_prs prWorkflow; anything else keeps the Graphite wording it always had.\n */\nfunction describeAction(name, description, workflows) {\n if (workflows !== \"github\" && workflows !== \"mixed\") return description;\n const how = workflows === \"github\"\n ? { merge: \"through GitHub (gh pr merge, with the repository's merge method)\", on: \"Turn on GitHub auto-merge\", off: \"Turn off GitHub auto-merge\" }\n : { merge: \"the way its repository ships (Graphite, or GitHub's gh pr merge; list_prs shows prWorkflow)\", on: \"Turn on merge-when-ready (Graphite) or auto-merge (GitHub)\", off: \"Turn off merge-when-ready (Graphite) or auto-merge (GitHub)\" };\n if (name === \"merge\") return description.replace(\"through Graphite\", how.merge);\n if (name === \"enable_merge_when_ready\") return description.replace(\"Turn on Graphite merge-when-ready\", how.on);\n if (name === \"disable_merge_when_ready\") return description.replace(\"Turn off Graphite merge-when-ready\", how.off);\n return description;\n}\nconst schemas = (list, workflows = null) => list.map(([name, description, , properties, required]) => ({ name, description: describeAction(name, description, workflows), inputSchema: { type: \"object\", properties, required, additionalProperties: false }, annotations: { readOnlyHint: readOnlyTools.has(name), destructiveHint: destructiveTools.has(name) } }));\n/** Action tools: a session Paseo launched as a root agent (FOLLOW_THROUGH_ROOT) while Follow-up runs (fresh hook lease). */\nasync function actionsEnabled() {\n if (!process.env.PASEO_AGENT_ID || process.env.FOLLOW_THROUGH_ROOT !== \"1\" || process.env.FOLLOW_THROUGH_RECOVERY === \"1\") return false;\n try {\n const lease = JSON.parse(await readFile(join(process.env.PASEO_HOME ?? join(homedir(), \".paseo\"), \"plugin-data/follow-through/hooks-enabled.json\"), \"utf8\"));\n return lease.expiresAt > Date.now();\n } catch { return false; }\n}\n/** The bridge input for a tool: action tools travel as { tool, args } through follow.agent-act. */\nconst callInput = (tool, input) => actionNames.has(tool[0]) || overseerNames.has(tool[0]) ? { tool: tool[0], args: input } : input;\n/** The Overseer's routing tools: the session Follow-up launched as its Overseer, while Follow-up runs. */\nasync function overseerEnabled() {\n if (process.env.FOLLOW_THROUGH_OVERSEER !== \"1\" || !process.env.PASEO_AGENT_ID) return false;\n try {\n const lease = JSON.parse(await readFile(join(process.env.PASEO_HOME ?? join(homedir(), \".paseo\"), \"plugin-data/follow-through/hooks-enabled.json\"), \"utf8\"));\n return lease.expiresAt > Date.now();\n } catch { return false; }\n}\nlet scopeCache = null;\nasync function scopeOf(directory, agentId) {\n try {\n const path = join(directory, \"scopes.json\");\n const { mtimeMs } = await stat(path);\n if (scopeCache?.mtimeMs !== mtimeMs) { const file = JSON.parse(await readFile(path, \"utf8\")); scopeCache = { mtimeMs, agents: file.agents ?? {}, workflows: file.workflows ?? null }; }\n return scopeCache.agents[agentId]?.role ?? null;\n } catch (error) {\n if (error?.code !== \"ENOENT\") throw error;\n const state = JSON.parse(await readFile(join(directory, \"state.json\"), \"utf8\"));\n for (const w of state.workspaces) {\n if (!w.enable_tracking || w.archived) continue;\n if (w.mainAgentId === agentId) return \"main\";\n if (w.batches.some(b => b.recipientAgentId === agentId && !b.settledAt && [\"sending\", \"sent\", \"blocked\", \"uncertain\"].includes(b.state) && b.tasks.every(t => t.kind === \"inventory\"))) return \"recovery\";\n if (w.contributorAgentIds?.includes(agentId)) return \"contributor\";\n }\n return null;\n }\n}\n/** This agent's PR workflow from scopes.json (undefined: an older worker, which meant Graphite with /fix-pr). */\nconst workflowOf = agentId => scopeCache ? scopeCache.agents[agentId]?.workflow : undefined;\n/** Whether the repositories Follow-up knows ship through Graphite, GitHub or both (\"mixed\"); null: unknown, as before. */\nconst workflowsOf = () => scopeCache?.workflows ?? null;\nasync function scope(resolveRecovery = false) {\n const agentId = process.env.PASEO_AGENT_ID;\n if (!agentId) return null;\n try {\n const home = process.env.PASEO_HOME ?? join(homedir(), \".paseo\");\n const directory = join(home, \"plugin-data/follow-through\");\n const lease = JSON.parse(await readFile(join(directory, \"hooks-enabled.json\"), \"utf8\"));\n if (!(lease.expiresAt > Date.now())) return null;\n // scopes.json (a few KB, rewritten only when a role changes) instead of the whole state.json; re-read only\n // when its mtime changes. Older workers don't write it, so fall back to state.json.\n const known = await scopeOf(directory, agentId);\n if (known === \"main\") return process.env.FOLLOW_THROUGH_RECOVERY === \"1\" ? \"recovery\" : \"main\";\n if (known) return known;\n if (resolveRecovery && process.env.FOLLOW_THROUGH_RECOVERY === \"1\") {\n const w = await call(\"follow.agent-status\", {});\n if (w.enable_tracking && !w.archived && w.mainAgentId !== agentId && w.batches.some(b => b.recipientAgentId === agentId && !b.settledAt && [\"sending\", \"sent\", \"blocked\", \"uncertain\"].includes(b.state) && b.tasks.every(t => t.kind === \"inventory\"))) return \"recovery\";\n }\n } catch {}\n return null;\n}\nfunction validate(value, schema, path = \"arguments\") {\n const types = Array.isArray(schema.type) ? schema.type : [schema.type];\n const type = value === null ? \"null\" : Array.isArray(value) ? \"array\" : typeof value;\n if (!types.includes(type) && !(type === \"number\" && types.includes(\"integer\") && Number.isInteger(value))) throw new Error(`${path}: expected ${types.join(\" or \")}.`);\n if (schema.enum && !schema.enum.includes(value)) throw new Error(`${path}: choose ${schema.enum.join(\", \")}.`);\n if (type === \"object\") {\n const extra = Object.keys(value).filter(k => !Object.hasOwn(schema.properties ?? {}, k));\n if (extra.length && schema.additionalProperties === false) throw new Error(`Unknown argument ${path}.${extra.join(\", \")}. ${extra.includes(\"dependsOnPrs\") ? \"Use afterPrs with owner/repo#number keys.\" : \"Check this tool's input schema with list.\"}`);\n for (const key of schema.required ?? []) if (!(key in value)) throw new Error(`${path}.${key} is required. Check this tool's input schema with list.`);\n for (const [key, nested] of Object.entries(value)) if (schema.properties?.[key]) validate(nested, schema.properties[key], `${path}.${key}`);\n }\n if (type === \"array\") for (let i = 0; i < value.length; i++) validate(value[i], schema.items, `${path}[${i}]`);\n if (type === \"number\" && (schema.minimum !== undefined && value < schema.minimum || schema.maximum !== undefined && value > schema.maximum)) throw new Error(`${path}: outside the allowed range.`);\n if (type === \"string\" && (schema.minLength !== undefined && value.length < schema.minLength || schema.maxLength !== undefined && value.length > schema.maxLength)) throw new Error(`${path}: outside the allowed length.`);\n}\nfunction currentWork(w) {\n return { id: w.id, title: w.title, goal: w.goal, mainAgentId: w.mainAgentId, enable_tracking: w.enable_tracking, enable_auto_sends: w.enable_auto_sends, hold: w.hold, archived: w.archived, runtimeBusy: w.runtimeBusy, runtimeReason: w.runtimeReason, backgroundBusy: w.backgroundBusy, completion: w.completion,\n prs: w.prs.map(p => ({ key: p.key, stack: p.stack, parent: p.parent, disposition: p.disposition, error: p.error, ...(p.snapshot ? { title: p.snapshot.title, state: p.snapshot.state, head: p.snapshot.head, draft: p.snapshot.draft, reviewDecision: p.snapshot.reviewDecision, conflict: p.snapshot.conflict, openThreads: p.snapshot.threads.length, failedChecks: p.snapshot.failedChecks, otherFailedChecks: p.snapshot.otherFailedChecks ?? [], deployment: p.snapshot.deployment } : {}) })),\n obligations: w.obligations.filter(o => ![\"done\", \"waived\"].includes(o.status)), completedObligations: w.obligations.filter(o => [\"done\", \"waived\"].includes(o.status)).length,\n openQuestions: (w.questions ?? []).filter(q => !q.answer && !q.closed).map(q => ({ id: q.id, title: q.title, question: q.question, options: q.options, recommend: q.recommend, big: q.big, mode: q.mode, askedBy: q.askedBy, taskId: q.taskId })),\n spec: w.spec?.url ? { url: w.spec.url, title: w.spec.title, source: w.spec.source } : null,\n recentAnswers: (w.questions ?? []).filter(q => q.answer).slice(-5).map(q => ({ id: q.id, title: q.title, choice: q.answer.choice, words: q.answer.words, delivery: q.answer.delivery.state })),\n batches: w.batches.filter(b => ![\"completed\", \"cancelled\"].includes(b.state)).map(b => ({ id: b.id, state: b.state, tasks: b.tasks, result: b.result, recipientAgentId: b.recipientAgentId, contextPath: b.contextPath })),\n excludedStacks: w.excludedStacks.map(s => ({ name: s.name, reason: s.reason, prs: s.prs.map(p => p.key) })), ...(w.prWorkflow ? { prWorkflow: w.prWorkflow } : {}), detail: \"summary\" };\n}\nfunction compact(tool, input, result) {\n if (actionNames.has(tool)) return result;\n if (tool === \"workspace_status\") return currentWork(result);\n if (tool === \"needs_you\") return { ok: result.ok, briefId: result.briefId };\n if (tool === \"declare_done\") return { workspaceId: result.workspace.id, completion: result.workspace.completion, blockers: result.blockers };\n if (tool === \"ask_question\") return { workspaceId: result.workspaceId, question: { id: result.question.id, title: result.question.title, recommend: result.question.recommend, big: result.question.big }, mode: result.mode, instruction: result.instruction };\n if (tool === \"record_answer\" || tool === \"withdraw_question\") return { workspaceId: result.workspaceId, question: { id: result.question.id, answer: result.question.answer, closed: result.question.closed } };\n if (tool === \"set_spec\") return { workspaceId: result.workspaceId, spec: result.spec && { url: result.spec.url, title: result.spec.title, source: result.spec.source }, applied: result.applied, message: result.message };\n if (!result?.prs) return result;\n const workspaceId = result.id;\n if (tool === \"enroll_workspace\") return { workspaceId, goal: result.goal };\n 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 } }; }\n if (tool === \"update_obligation\") return { workspaceId, obligation: result.obligations.find(o => o.id === result.updatedObligationId) };\n 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 } }; }\n 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) } }; }\n return result;\n}\nasync function loadClient() {\n const candidates = [];\n if (process.env.FOLLOW_THROUGH_CLIENT_ENTRY) candidates.push(() => pathToFileURL(process.env.FOLLOW_THROUGH_CLIENT_ENTRY).href);\n const specifier = \"@getpaseo/client/internal/daemon-client\";\n if (process.resourcesPath) candidates.push(() => pathToFileURL(createRequire(join(process.resourcesPath, \"app.asar/node_modules/@getpaseo/cli/dist/index.js\")).resolve(specifier)).href);\n for (const directory of (process.env.PATH ?? \"\").split(delimiter)) {\n const cli = join(directory, process.platform === \"win32\" ? \"paseo.cmd\" : \"paseo\");\n if (existsSync(cli)) candidates.push(() => pathToFileURL(createRequire(realpathSync(cli)).resolve(specifier)).href);\n }\n candidates.push(() => pathToFileURL(createRequire(import.meta.url).resolve(specifier)).href);\n for (const resolve of candidates) try { return await import(resolve()); } catch {}\n throw new Error(\"Cannot load the installed Paseo client. Reload Follow-through to refresh its runtime connection.\");\n}\nconst batchInstructionsMain = \"Follow-through batches contain a header with the batchId and ordered tasks. Read workspace_status and refresh live conditions; skip resolved tasks. Process PRs bottom to top, one fully before the next, using the repository's /fix-pr and safe reparent workflow. Validate feedback, verify changes, submit with Graphite --publish, reply/resolve addressed threads and preserve uncommitted work. Post-deploy tasks require verified serving revisions and existing production permissions. Stakeholder update requests are follow-through tasks: retain the original thread, recipient and developer authorization in communication. Use current evidence, distinguish fixed/deployed/verified, and read existing replies before posting. Record the sent replyUrl; a draft or uncertain send stays blocked and must be checked before retrying. Auto authorizes agent delivery only. Acknowledge the header's batchId with acknowledge_batch before finishing (completed with the result, or blocked with the reason), before declare_done for completion batches. Declare Done only after the whole goal and post-merge work are verified. Leave merging and archiving to the developer.\";\n/**\n * The batch rules for this workspace's PR workflow. Graphite with /fix-pr (and any agent from before workflows\n * existed) gets the original text unchanged; plain GitHub never mentions Graphite, gt or a review command it doesn't have.\n */\nfunction batchInstructions(workflow) {\n const mode = workflow?.mode ?? \"graphite\";\n const fix = workflow === undefined || workflow === null ? \"/fix-pr\" : workflow.reviewFix ?? null;\n if (mode === \"graphite\" && fix === \"/fix-pr\") return batchInstructionsMain;\n const fixing = fix ? `using the repository's ${fix} workflow for review comments` : \"reading each PR's unresolved review threads with gh\";\n const restack = mode === \"graphite\" ? \"the repository's safe reparent workflow\" : \"base branches kept in a chain (restack with git rebase --update-refs, push with --force-with-lease, and after a parent merges retarget its child with gh pr edit --base if GitHub didn't)\";\n const submit = mode === \"graphite\" ? \"submit with Graphite --publish\" : \"push the branch (gh pr create for a new PR, gh pr ready when it leaves draft)\";\n const reply = fix ? \"reply/resolve addressed threads\" : \"reply to each addressed thread and resolve it\";\n return batchInstructionsMain\n .replace(\"using the repository's /fix-pr and safe reparent workflow.\", `${fixing}, with ${restack}.`)\n .replace(\"submit with Graphite --publish, reply/resolve addressed threads\", `${submit}, ${reply}`);\n}\n\nasync function call(method, input) {\n const agentId = process.env.PASEO_AGENT_ID;\n if (!agentId) throw new Error(\"This bridge must run inside a Paseo agent (PASEO_AGENT_ID is missing).\");\n const { DaemonClient } = await loadClient();\n const home = process.env.PASEO_HOME ?? join(homedir(), \".paseo\");\n const config = JSON.parse(await readFile(join(home, \"config.json\"), \"utf8\"));\n let password = process.env.PASEO_PASSWORD;\n if (!password && process.env.PASEO_PASSWORD_FILE) password = (await readFile(process.env.PASEO_PASSWORD_FILE, \"utf8\")).trim();\n if (!password && home === join(homedir(), \".paseo\")) password = await readFile(join(homedir(), \"paseo-hub/secrets/daemon-password\"), \"utf8\").then(s => s.trim()).catch(() => undefined);\n const client = new DaemonClient({ url: process.env.PASEO_DAEMON_URL ?? `ws://${config.daemon?.listen ?? \"127.0.0.1:6767\"}/ws`, clientId: \"follow-through-mcp\", clientType: \"cli\", reconnect: { enabled: false }, connectTimeoutMs: 10000, suppressSendErrors: true, ...(password ? { password } : {}) });\n try { await client.connect(); return await client.invokePluginRpc(\"follow-through\", method, { ...input, agentId }); }\n finally { await client.close().catch(() => undefined); }\n}\n\n\n// The worker imports this file for the same tool tables, validation and receipts (1.4.0-beta.2: Follow-up's tools\n// served natively through Paseo's own MCP). Only a direct run is the CLI / stdio bridge.\nexport { tools, actionTools, overseerTools, toolList, schemas, validate, compact, callInput, needsYouInstruction, actionInstruction, overseerInstruction, batchInstructions, describeAction };\nfunction isMain() {\n try { return !!process.argv[1] && !!import.meta.url && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href; } catch { return false; }\n}\nif (isMain()) runMain().catch(error => { console.error(error?.message ?? String(error)); process.exitCode = 1; });\nasync function runMain() {\nconst command = process.argv[2];\nif (command === \"list\" || command === \"--help\" || command === \"help\") {\n process.stdout.write(command === \"list\" ? JSON.stringify({ tools: schemas([...toolList(undefined, false, true, false, true), ...overseerTools]) }, null, 2) + \"\\n\" : \"Usage: node mcp.mjs list | call <tool> '<json>' [--compact]\\nNative MCP returns compact receipts; workspace_status({detail:full}) requests complete history. CLI calls retain full replies unless --compact is supplied.\\n\");\n} else if (command === \"call\") {\n try {\n const tool = [...toolList(undefined, false, await briefEnabled(), false, await actionsEnabled()), ...(await overseerEnabled() ? overseerTools : [])].find(t => t[0] === process.argv[3]);\n if (!tool) throw new Error(\"Unknown tool. Run list for names and input schemas.\");\n const input = JSON.parse(process.argv[4] ?? \"{}\");\n validate(input, schemas([tool])[0].inputSchema);\n if (process.argv.slice(5).some(arg => arg !== \"--compact\")) throw new Error(\"Unknown CLI option. Use --compact or omit it for a full reply.\");\n const result = await call(tool[2], callInput(tool, input));\n process.stdout.write(JSON.stringify(process.argv.includes(\"--compact\") && input.detail !== \"full\" ? compact(tool[0], input, result) : result, null, 2) + \"\\n\");\n } catch (error) { console.error(error.message); process.exitCode = 1; }\n} else if (command) {\n console.error(\"Unknown command. Use list, --help, or call <tool> '<json>'.\"); process.exitCode = 1;\n} else {\n const lines = createInterface({ input: process.stdin });\n let tail = Promise.resolve(), initialized = false, lastScope = null;\n const timer = process.env.PASEO_AGENT_ID ? setInterval(() => {\n void (async () => { const current = `${await scope()}:${await briefEnabled()}:${await actionsEnabled()}:${await overseerEnabled()}`; if (initialized && current !== lastScope) process.stdout.write(JSON.stringify({ jsonrpc: \"2.0\", method: \"notifications/tools/list_changed\" }) + \"\\n\"); lastScope = current; })().catch(() => {});\n }, 2000) : null;\n timer?.unref(); lines.on(\"close\", () => { if (timer) clearInterval(timer); });\n lines.on(\"line\", line => {\n tail = tail.then(async () => {\n let request;\n try { request = JSON.parse(line); } catch { return; }\n if (request.id === undefined) return;\n try {\n let result;\n const role = await scope(request.method === \"initialize\" || request.method === \"tools/list\");\n const brief = await briefEnabled();\n const acting = await actionsEnabled();\n const overseeing = await overseerEnabled();\n const workflow = workflowOf(process.env.PASEO_AGENT_ID);\n const available = [...(role ? toolList(role === \"recovery\", role === \"contributor\", brief, false, acting) : toolList(false, false, brief, true, acting)), ...(overseeing ? overseerTools : [])];\n if (request.method === \"initialize\") {\n initialized = true; lastScope = `${role}:${brief}:${acting}:${overseeing}`;\n result = { protocolVersion: request.params?.protocolVersion ?? \"2024-11-05\", capabilities: { tools: { listChanged: true } }, serverInfo: { name: \"paseo-follow-through\", version: \"0.3.5\" }, instructions: (role ? (role === \"contributor\" ? \"Register PRs this session submits, including from secondary git worktrees. Read workspace_status and call sync_workspace before finishing. Goal, task, scope and completion changes remain with the designated main agent.\" : role === \"recovery\" ? \"Recover tracking metadata from evidence, acknowledge your assigned batch, and leave completion to the main agent.\" : \"Keep workspace follow-through updated after PR submission and scope changes. Read workspace_status after compaction. Track all post-merge work. When a decision needs the developer, ask it with ask_question (lettered options and a recommendation) and follow the question mode in its reply. If you keep a spec artifact for this workspace, register its link once with set_spec. \" + batchInstructions(workflow)) + \" Perform bookkeeping silently: no sidebar-update announcements, plugin-status commentary or final sidebar recap. Put receipts and summaries in tools. Report actual work outcomes or decisions/blockers; discuss sidebar status only when explicitly asked.\" : brief ? \"\" : \"Follow-through tools are available to tracked workspace root agents and active recovery agents; contributor sessions receive PR registration and status tools.\") + (brief && role !== \"contributor\" && role !== \"recovery\" ? (role ? \" \" : \"\") + needsYouInstruction : \"\") + (acting && role !== \"contributor\" && role !== \"recovery\" ? \" \" + actionInstruction : \"\") + (overseeing ? \" \" + overseerInstruction : \"\") };\n } else if (request.method === \"ping\") result = {};\n else if (request.method === \"tools/list\") result = { tools: schemas(available, workflowsOf()) };\n else if (request.method === \"tools/call\") {\n const tool = available.find(t => t[0] === request.params?.name);\n try {\n if (!tool) throw new Error(\"This tool is unavailable for the current agent. Tracking must be active; recovery authority ends after acknowledgment.\");\n const input = request.params.arguments ?? {}; validate(input, schemas([tool])[0].inputSchema);\n const value = await call(tool[2], callInput(tool, input));\n result = { content: [{ type: \"text\", text: JSON.stringify(input.detail === \"full\" ? value : compact(tool[0], input, value)) }] };\n } catch (error) { result = { isError: true, content: [{ type: \"text\", text: error.message }] }; }\n } else { process.stdout.write(JSON.stringify({ jsonrpc: \"2.0\", id: request.id, error: { code: -32601, message: \"Method not found\" } }) + \"\\n\"); return; }\n process.stdout.write(JSON.stringify({ jsonrpc: \"2.0\", id: request.id, result }) + \"\\n\");\n } catch (error) { process.stdout.write(JSON.stringify({ jsonrpc: \"2.0\", id: request.id, error: { code: -32603, message: error.message } }) + \"\\n\"); }\n });\n });\n}\n}\n";
2
+ export const mcpSource = "#!/usr/bin/env node\nimport { createInterface } from \"node:readline\";\nimport { createRequire } from \"node:module\";\nimport { pathToFileURL } from \"node:url\";\nimport { readFile, stat } from \"node:fs/promises\";\nimport { existsSync, realpathSync } from \"node:fs\";\nimport { join, delimiter } from \"node:path\";\nimport { homedir } from \"node:os\";\n\nconst string = { type: \"string\" };\nconst boolean = { type: \"boolean\" };\nconst integer = { type: \"integer\", minimum: 1 };\nconst array = { type: \"array\", items: string };\nconst communication = { type: \"object\", properties: { threadUrl: string, recipient: string, purpose: { type: \"string\", enum: [\"progress\", \"verified\"] }, authorization: string, replyUrl: { type: [\"string\", \"null\"] } }, required: [\"threadUrl\", \"recipient\"], additionalProperties: false };\nconst trigger = { type: [\"object\", \"null\"], properties: { event: { type: \"string\", enum: [\"now\", \"merge\", \"deploy\"] }, delayDays: { type: \"integer\", minimum: 0, maximum: 3650 } }, required: [\"event\"], additionalProperties: false };\nconst tools = [\n [\"workspace_status\", \"Read the tracked workspace's durable goal, PRs, tasks, work queue and optional recovery history. Read after compaction. Returns current work by default; detail=full includes complete evidence/history. Normal follow-through does not require recovery.\", \"follow.agent-status\", { detail: { type: \"string\", enum: [\"summary\", \"full\"] } }, []],\n [\"sync_workspace\", \"Silently confirm the sidebar matches your work before finishing, after registering owned PRs and substantive tasks. Call even when no changes are needed. Keep the summary in this tool; never announce sync or recap sidebar/plugin status to the developer. Does not declare Done, run recovery, or start repairs. Tracked root agents only.\", \"follow.sync\", { summary: { ...string, minLength: 1, maxLength: 1000 } }, [\"summary\"]],\n [\"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\"]],\n [\"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.\", \"follow.register-pr\", { repo: string, number: integer, stack: string, parentNumber: { type: [\"integer\", \"null\"], minimum: 1 }, disposition: string }, [\"repo\", \"number\", \"stack\"]],\n [\"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\"]],\n [\"update_obligation\", \"Record concrete follow-through: 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.\", \"follow.obligation\", { id: string, title: string, status: { type: \"string\", enum: [\"pending\", \"waiting\", \"working\", \"blocked\", \"done\", \"waived\"] }, afterPrs: array, dependencyStage: { type: \"string\", enum: [\"merged\", \"deployed\"] }, evidence: string, enable_follow_up: boolean, communication, trigger }, [\"title\", \"status\"]],\n [\"acknowledge_batch\", \"Record a follow-up result. Complete only after verifying all tasks; blocked surfaces the reason to the developer. 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 } }, [\"batchId\", \"outcome\", \"result\"]],\n [\"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.\", \"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 }, [\"title\", \"question\"]],\n [\"record_answer\", \"Record the developer's answer when they answered a question in chat instead of in Follow-up. choice is an option letter, 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\"]],\n [\"withdraw_question\", \"Withdraw a question that no longer matters, with a short reason.\", \"follow.withdraw-question\", { id: string, reason: string }, [\"id\", \"reason\"]],\n [\"set_spec\", \"Register the link to this workspace's spec: the Claude artifact (or doc) you keep summarizing the goal, decisions and status. Call it once after the first publish, with the URL from the publish result, and again only if the link changes. Follow-up shows it in the workspace header.\", \"follow.set-spec\", { url: { ...string, maxLength: 2000 }, title: { ...string, maxLength: 120 } }, [\"url\"]],\n [\"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), 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 } }, 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\"]],\n [\"declare_done\", \"Declare that the workspace goal is fulfilled. Live PR status and remaining obligations are checked; returned blockers must be resolved first. Done labels the workspace but never archives it.\", \"follow.done\", { summary: string }, [\"summary\"]],\n];\n\n// Agent parity: every action the developer can click in Follow-up, through the same server path (follow.agent-act).\n// Planned tools return a dry run; confirm=true with its planId runs it. Use them only when the developer asked.\nconst planned = { planId: string, confirm: boolean };\nconst prKey = { ...string, description: \"owner/repo#number, from list_prs\" };\nconst ask = \" Only when the developer asked for it. Returns a dry-run plan first; run it with confirm=true and the planId.\";\nconst read = \" Read-only.\";\nconst actionTools = [\n [\"list_prs\", \"List tracked PRs across all workspaces with state, draft, checks, open threads, requested reviewers and merge blockers. Filters: needs_reviewers, ready_to_merge, workspace (id or title). This is how you act \\\"on all\\\".\", \"follow.agent-act\", { workspace: string, needs_reviewers: boolean, ready_to_merge: boolean, include_closed: boolean }, []],\n [\"add_reviewers\", \"Request reviewers on one or many PRs, the same as the Add reviewers button. Without reviewers, asks the developer's saved reviewers for that repository (each PR row in list_prs shows them as configuredReviewers, with source repo, default or none); otherwise the GitHub logins or org/team slugs you give.\" + ask, \"follow.agent-act\", { prs: { type: \"array\", items: prKey }, reviewers: array, ...planned }, []],\n [\"merge\", \"Merge a PR (and its downstack with scope=downstack) through Graphite, using Follow-up's merge plan and blockers. Can't be undone.\" + ask, \"follow.agent-act\", { pr: prKey, scope: { type: \"string\", enum: [\"target\", \"downstack\"] }, ...planned }, []],\n [\"enable_merge_when_ready\", \"Turn on Graphite merge-when-ready for a PR, as the PR sheet does.\" + ask, \"follow.agent-act\", { pr: prKey, scope: { type: \"string\", enum: [\"target\", \"downstack\"] }, ...planned }, []],\n [\"disable_merge_when_ready\", \"Turn off Graphite merge-when-ready for a PR.\" + ask, \"follow.agent-act\", { pr: prKey, scope: { type: \"string\", enum: [\"target\", \"downstack\"] }, ...planned }, []],\n [\"send_repairs\", \"Send a workspace's waiting repairs (review threads, failed checks) to its main agent, like the Send button. Only when the developer asked. batchId defaults to the waiting batch.\", \"follow.agent-act\", { workspace: string, batchId: string }, [\"workspace\"]],\n [\"set_auto_send\", \"Turn Auto-send on or off for a workspace, like its switch. Only when the developer asked.\", \"follow.agent-act\", { workspace: string, value: boolean }, [\"workspace\", \"value\"]],\n [\"clear_hold\", \"Resume Follow-up on a held workspace, like the Resume button. Only when the developer asked.\", \"follow.agent-act\", { workspace: string }, [\"workspace\"]],\n [\"retry_batch\", \"Queue a blocked or uncertain repair batch again, like the Retry button. Only when the developer asked.\", \"follow.agent-act\", { workspace: string, batchId: string }, [\"workspace\", \"batchId\"]],\n [\"track\", \"Follow a workspace again after the developer opted it out in Settings. Follow-up follows every workspace by default. Only when the developer asked.\", \"follow.agent-act\", { workspace: string }, [\"workspace\"]],\n [\"workspace_about\", \"Read what a workspace is about: a short AI overview (goal, where it stands, what's left), a one-line gist, and its linked Linear issues, PRs, Slack threads and docs. Read-only; writes the overview first when none is cached (up to ~90 s). workspaceId is a workspace id or exact title from list_prs.\", \"follow.agent-act\", { workspaceId: string }, [\"workspaceId\"]],\n [\"agent_settings\", \"Read which agent each of Follow-up's special roles uses (What's this about?, Overseer, Recovery, Priority ranker): provider, model, effort, mode and limits. Read-only; Tom changes them in Follow-up settings → Agents.\", \"follow.agent-act\", {}, []],\n [\"inbox_list\", \"Read the developer's Needs-you inbox: each root agent, whether it is flagged and why, snoozes and finish flags. Your own row has self=true.\", \"follow.agent-act\", { flagged_only: boolean }, []],\n [\"sign_off\", \"Sign off other agents' Needs-you flags on the developer's behalf, like Sign off. Never your own.\" + ask, \"follow.agent-act\", { agentIds: array, ...planned }, []],\n [\"snooze\", \"Snooze other agents' flags (until: next-event, 1h, tomorrow or an ISO time), like Later.\" + ask, \"follow.agent-act\", { agentIds: array, until: string, ...planned }, []],\n [\"set_finish_flags\", \"Turn finish flags on or off for other agents, like Don't flag finishes.\" + ask, \"follow.agent-act\", { agentIds: array, value: boolean, ...planned }, []],\n [\"set_priorities\", \"Rank workspaces for Home's Priority sort: per workspace (id or exact title) a score 0-100, a one-line reason the developer sees, and its sources [{kind: linear|slack|planning|github|paseo, label, url}]. replace=true drops workspaces you leave out. Used for 6 hours. Returns a dry run; store it with confirm=true and the planId.\", \"follow.agent-act\", { priorities: { type: \"array\", items: { type: \"object\", properties: { workspace: string, score: { type: \"integer\", minimum: 0, maximum: 100 }, reason: { ...string, maxLength: 140 }, sources: { type: \"array\", items: { type: \"object\", properties: { kind: { type: \"string\", enum: [\"linear\", \"slack\", \"planning\", \"github\", \"paseo\"] }, label: string, url: string }, required: [\"kind\", \"label\"] } } }, required: [\"workspace\", \"score\", \"reason\"] } }, replace: boolean, ...planned }, [\"priorities\"]],\n // Settings, onboarding, Home and the panel, one developer RPC each (server/agent-parity.ts). Writes plan first.\n [\"make_main_agent\", \"Make yourself or another root agent of this workspace its main agent (the one that asks the developer, reports Needs-you and calls Done). requested=developer when the developer asked for it (refused only while the main is mid-turn); requested=self for your own claim, allowed only when the main is archived, gone or closed 30 minutes, or you registered every open PR and the main has been idle 24 hours, and never within 30 minutes of a change or 2 hours after you lost the role. Give a one-line reason the developer sees. Returns a dry run; run it with confirm=true and the planId.\", \"follow.agent-act\", { agentId: string, reason: string, requested: { type: \"string\", enum: [\"developer\", \"self\"] }, ...planned }, []],\n [\"display_settings\", \"Read Settings → Display: the header button, sidebar item, composer pill, Needs-you inbox, closed-PR flags, brief nudge, Overseer, ranker and trust bypass switches.\" + read, \"follow.agent-act\", {}, []],\n [\"set_display\", \"Change Settings → Display switches, e.g. { values: { enable_trust_bypass: false } }. Keys from display_settings.\" + ask, \"follow.agent-act\", { values: { type: \"object\", additionalProperties: boolean }, ...planned }, []],\n [\"follow_settings\", \"Read Settings → Following: follow every workspace, the Auto-send default, the active window, and per-workspace exceptions.\" + read, \"follow.agent-act\", {}, []],\n [\"set_follow_settings\", \"Change Settings → Following: enable_follow_every, enable_auto_sends_default, activeWindowDays (1-60), or one workspace's exception { workspaceId, follow, enable_auto_sends }.\" + ask, \"follow.agent-act\", { enable_follow_every: boolean, enable_auto_sends_default: boolean, activeWindowDays: { type: \"integer\", minimum: 1, maximum: 60 }, workspace: { type: \"object\" }, ...planned }, []],\n [\"project_settings\", \"Read each project and whether Follow-up follows its new workspaces by default.\" + read, \"follow.agent-act\", {}, []],\n [\"set_project_tracking\", \"Follow a project's new workspaces by default, or stop: { projectId, enable_default_tracking }.\" + ask, \"follow.agent-act\", { projectId: string, enable_default_tracking: boolean, ...planned }, []],\n [\"pr_workflow\", \"Read Settings → Following → Shipping PRs: each repository's PR workflow (graphite or github), merge method and review-fix setting, and the default. refresh=true re-detects.\" + read, \"follow.agent-act\", { refresh: boolean }, []],\n [\"set_pr_workflow\", \"Change Shipping PRs: per repository (repo owner/name) its setting, mergeMethod or reviewFix (null clears back to the default), or the default.\" + ask, \"follow.agent-act\", { repo: string, setting: { type: [\"string\", \"null\"] }, default: string, mergeMethod: { type: [\"string\", \"null\"] }, reviewFix: { type: [\"object\", \"null\"] }, ...planned }, []],\n [\"reviewer_settings\", \"Read Settings → Reviewers: the default reviewers and each repository's own list.\" + read, \"follow.agent-act\", {}, []],\n [\"reviewer_suggestions\", \"Suggest reviewers for a repository (owner/name) from its recent history.\" + read, \"follow.agent-act\", { repo: string }, [\"repo\"]],\n [\"save_reviewers\", \"Save the reviewers Add reviewers asks: repo owner/name, or null for the default; reviewers [{ login, name?, kind? }].\" + ask, \"follow.agent-act\", { repo: { type: [\"string\", \"null\"] }, reviewers: { type: \"array\", items: { type: \"object\" } }, ...planned }, []],\n [\"set_agent_setting\", \"Change which agent a special role uses (Settings → Agents): role about|overseer|recovery|ranker, entry { provider, model, ... } or null for the default. agent_settings shows the current ones.\" + ask, \"follow.agent-act\", { role: string, entry: { type: [\"object\", \"null\"] }, ...planned }, []],\n [\"onboarding_status\", \"Read the setup guide's state: whether it was finished or skipped, and the current step.\" + read, \"follow.agent-act\", {}, []],\n [\"onboarding_checks\", \"Run the setup checks (GitHub login, providers, ...) and return each result with its fix. fresh=true re-runs them.\" + read, \"follow.agent-act\", { fresh: boolean }, []],\n [\"set_onboarding\", \"Move the setup guide: action start|step|finish|skip|restart|dismiss-offer, step for action=step.\" + ask, \"follow.agent-act\", { action: string, step: string, ...planned }, []],\n [\"priorities\", \"Read the stored priorities behind Home's Priority sort.\" + read, \"follow.agent-act\", {}, []],\n [\"rank_status\", \"Read the priority ranker's state: last run, whether it's running, and errors.\" + read, \"follow.agent-act\", {}, []],\n [\"rerank_priorities\", \"Re-rank Home's Priority sort now, like Re-rank. force=true re-runs even when nothing changed.\" + ask, \"follow.agent-act\", { force: boolean, ...planned }, []],\n [\"usage\", \"Read provider usage limits and the VM's memory meter, as Home shows them.\" + read, \"follow.agent-act\", {}, []],\n [\"overseer_status\", \"Read the Overseer's state: running, its agent and model, and what a restart would use.\" + read, \"follow.agent-act\", {}, []],\n [\"overseer_start\", \"Start the Overseer, like Start on Home.\" + ask, \"follow.agent-act\", { ...planned }, []],\n [\"overseer_restart\", \"Restart the Overseer (with the model Settings → Agents names now).\" + ask, \"follow.agent-act\", { ...planned }, []],\n [\"overseer_ask\", \"Send the developer's words to the Overseer, as its box on Home does: { text }.\" + ask, \"follow.agent-act\", { text: string, ...planned }, []],\n [\"inbox_brief\", \"Read another agent's full Needs-you brief (decisions, options, links): { agentId }.\" + read, \"follow.agent-act\", { agentId: string }, [\"agentId\"]],\n [\"brief_action\", \"Answer another agent's brief for the developer, like its card: { agentId, briefId, decisionId + choice, or choices [{ decisionId, choice }], or move: retry }. Never your own brief.\" + ask, \"follow.agent-act\", { agentId: string, briefId: string, decisionId: string, choice: string, move: string, choices: { type: \"array\", items: { type: \"object\" } }, ...planned }, []],\n [\"inbox_act\", \"The inbox's other actions on other agents' rows: action undo|mute_turn|unsorted_flag|unsorted_sign_off|batch_undo, agentIds.\" + ask, \"follow.agent-act\", { action: string, agentIds: array, muteTurn: boolean, ...planned }, []],\n [\"answer_question\", \"Send the developer's answer to another agent's question (Q1…), like its card: { workspaceId, questionId, choice, words }. For a question you asked, use record_answer.\" + ask, \"follow.agent-act\", { workspaceId: string, questionId: string, choice: string, words: string, ...planned }, []],\n [\"run_recovery\", \"Run recovery on a workspace, like Run recovery: a separate agent reads its history for missed PRs and tasks. { workspaceId }.\" + ask, \"follow.agent-act\", { workspaceId: string, ...planned }, []],\n [\"refresh\", \"Refresh PR status now, like Refresh. Cheap; use when status looks stale.\", \"follow.agent-act\", { workspaceId: string }, []],\n [\"set_workspace_spec\", \"Set, remove or reset any workspace's spec link: { workspaceId, action set|remove|reset, url, title }.\" + ask, \"follow.agent-act\", { workspaceId: string, action: string, url: string, title: { type: [\"string\", \"null\"] }, ...planned }, []],\n [\"set_task_trigger\", \"Schedule a task to run now, on merge or on deploy (trigger { event, delayDays } or null), with afterPrs: { workspaceId, obligationId, expectedRevision, trigger, afterPrs }.\" + ask, \"follow.agent-act\", { workspaceId: string, obligationId: string, expectedRevision: { type: \"integer\", minimum: 0 }, trigger, afterPrs: array, ...planned }, []],\n [\"pr_controls\", \"Read a PR's merge controls as the PR sheet shows them (Send to Paseo pairing, Graphite in Chrome): { workspaceId, prKey }.\" + read, \"follow.agent-act\", { workspaceId: string, prKey }, [\"workspaceId\", \"prKey\"]],\n [\"browser_status\", \"Read whether Send to Paseo is paired and which repositories it may control.\" + read, \"follow.agent-act\", {}, []],\n [\"trust_bypass_status\", \"Read how many permission prompts trust bypass approved today, and the latest ones.\" + read, \"follow.agent-act\", {}, []],\n];\n// The Overseer's routing tools (1.4.0-beta.0): only in the session Follow-up started as its Overseer.\nconst overseerTools = [\n [\"workstreams\", \"Every workspace Tom has, as Home groups them (needs, fixing, running, waiting, later, quiet): title, branch, PRs with checks, main agent and status, current ask, last activity, priority and reason, Linear keys. Paged (page, size ≤100); filter by group or query (name, branch, key, #PR).\", \"follow.overseer-act\", { page: integer, size: integer, group: { type: \"string\", enum: [\"needs\", \"fixing\", \"running\", \"waiting\", \"later\", \"quiet\"] }, query: string }, []],\n [\"agent_digest\", \"One agent's last steps (default 10) summarised, its status and its open asks to Tom (flag, decisions, questions). Use before routing when the digest isn't enough.\", \"follow.overseer-act\", { agentId: string, steps: integer }, [\"agentId\"]],\n [\"route_candidates\", \"Score every workspace for Tom's ask by Linear key, PR number, branch, workspace name, open asks and recent activity. Returns the top 3 and whether one is a confident match.\", \"follow.overseer-act\", { ask: string }, [\"ask\"]],\n [\"send_to_agent\", \"Forward Tom's words to the agent that owns the work, prefixed \\\"From Tom via Overseer:\\\". reply_to_ask=true only when Tom is answering that agent's open ask (it then clears its Needs-you flag). Then tell Tom where it went in one line.\", \"follow.overseer-act\", { agentId: string, text: string, reply_to_ask: boolean }, [\"agentId\", \"text\"]],\n [\"start_workspace\", \"Start a new workspace with an agent for a task, branched off main with the default model. Only when Tom asked for a new workspace or picked it. Returns a dry run (title from the task and Linear key, branch, project); run it with confirm=true and the planId.\", \"follow.overseer-act\", { task: string, title: string, project: string, linear_key: string, base: string, planId: string, confirm: boolean }, []],\n [\"rerank\", \"Re-rank Home's Priority sort now from Linear, Slack, GitHub review requests and the weekly plan, when Tom asks for it. Returns the top 10 with their reasons. Skips the model when nothing changed.\", \"follow.overseer-act\", {}, []],\n];\nconst overseerNames = new Set(overseerTools.map(t => t[0]));\nconst overseerInstruction = \"You are Follow-up's Overseer. Route Tom's asks with route_candidates and send_to_agent; ask with needs_you kind=decision when unsure; start_workspace only when Tom asked or approved. Never merge, post to people or archive.\";\nconst actionNames = new Set(actionTools.map(t => t[0]));\nconst readOnlyTools = new Set([\"workspace_status\", \"list_prs\", \"inbox_list\", \"workstreams\", \"agent_digest\", \"route_candidates\", \"workspace_about\", \"agent_settings\", \"display_settings\", \"follow_settings\", \"project_settings\", \"pr_workflow\", \"reviewer_settings\", \"reviewer_suggestions\", \"onboarding_status\", \"onboarding_checks\", \"priorities\", \"rank_status\", \"usage\", \"overseer_status\", \"inbox_brief\", \"pr_controls\", \"browser_status\", \"trust_bypass_status\"]);\nconst destructiveTools = new Set([\"merge\"]);\nconst actionInstruction = \"Follow-up's action tools let you do anything the developer can click, across every tracked workspace and every Settings tab. Read freely: list_prs, inbox_list, inbox_brief, workspace_about, agent_settings, display_settings, follow_settings, project_settings, pr_workflow, reviewer_settings, onboarding_status, priorities, rank_status, usage, overseer_status, pr_controls. Hand the main role on, or claim it, with make_main_agent. Act only when the developer asks (\\\"the PRs look good, assign reviewers on all\\\": list_prs needs_reviewers=true, add_reviewers with those keys, then confirm the plan): add_reviewers, merge, enable/disable_merge_when_ready, send_repairs, set_auto_send, clear_hold, retry_batch, track, run_recovery, set_priorities, rerank_priorities; settings with set_display (trust bypass too), set_follow_settings, set_project_tracking, set_pr_workflow, save_reviewers, set_agent_setting, set_onboarding; and sign_off/snooze/set_finish_flags/inbox_act/brief_action/answer_question for other agents. Planned tools return a dry run showing what changes; run it with confirm=true and its planId. Never sign yourself off or answer your own brief.\";\n\n// The brief's tool: every root agent while the Needs-you inbox is on; never contributors, recovery or subagents.\n// Kept identical to NEEDS_YOU_INSTRUCTION in shared/brief.ts (a test checks it).\nconst needsYouInstruction = \"When you end a turn, call `needs_you` once, just before your final reply, with what the developer has to do next: a decision (give 2–3 options, what each means for them, and the one you recommend), an action only they can take (merge, approve, log in, run or send something), or kind=done (\\\"Nothing needed\\\" plus what you finished, in one line), which means there is nothing for the developer and won't flag you in their inbox. Keep `ask` to one line and `context` to what they need to decide. Don't repeat your report there; still write your normal reply. Don't call it while a permission prompt is waiting or while you're still working.\";\nfunction toolList(recovery = process.env.FOLLOW_THROUGH_RECOVERY === \"1\", contributor = false, brief = false, briefOnly = false, actions = false) {\n // Action tools: root agents (tracked main or untracked) while Follow-up runs; never recovery or contributors.\n // Contributors get make_main_agent only (its claim rules apply); recovery sessions get none.\n const acting = !actions || recovery ? [] : contributor ? actionTools.filter(t => t[0] === \"make_main_agent\") : actionTools;\n if (briefOnly) return [...(brief ? tools.filter(t => t[0] === \"needs_you\") : []), ...acting];\n return [...tools.filter(t => t[0] === \"needs_you\" ? brief && !recovery && !contributor : contributor ? [\"workspace_status\", \"register_pr\", \"sync_workspace\"].includes(t[0]) : !recovery || ![\"declare_done\", \"sync_workspace\", \"ask_question\", \"record_answer\", \"withdraw_question\", \"set_spec\"].includes(t[0])), ...acting];\n}\n/** Whether this session may call needs_you: launched as a root agent (FOLLOW_THROUGH_BRIEF) and the inbox is on. */\nasync function briefEnabled() {\n if (!process.env.FOLLOW_THROUGH_BRIEF || process.env.FOLLOW_THROUGH_RECOVERY === \"1\") return false;\n try {\n const directory = join(process.env.PASEO_HOME ?? join(homedir(), \".paseo\"), \"plugin-data/follow-through\");\n const lease = JSON.parse(await readFile(join(directory, \"hooks-enabled.json\"), \"utf8\"));\n if (!(lease.expiresAt > Date.now())) return false;\n const brief = JSON.parse(await readFile(join(directory, \"brief.json\"), \"utf8\"));\n return brief?.enable_inbox === true;\n } catch { return false; }\n}\n/**\n * Merge and merge-when-ready say how they run. \"github\": every known repository ships plain GitHub, so Graphite is\n * never named; \"mixed\": either, per list_prs prWorkflow; anything else keeps the Graphite wording it always had.\n */\nfunction describeAction(name, description, workflows) {\n if (workflows !== \"github\" && workflows !== \"mixed\") return description;\n const how = workflows === \"github\"\n ? { merge: \"through GitHub (gh pr merge, with the repository's merge method)\", on: \"Turn on GitHub auto-merge\", off: \"Turn off GitHub auto-merge\" }\n : { merge: \"the way its repository ships (Graphite, or GitHub's gh pr merge; list_prs shows prWorkflow)\", on: \"Turn on merge-when-ready (Graphite) or auto-merge (GitHub)\", off: \"Turn off merge-when-ready (Graphite) or auto-merge (GitHub)\" };\n if (name === \"merge\") return description.replace(\"through Graphite\", how.merge);\n if (name === \"enable_merge_when_ready\") return description.replace(\"Turn on Graphite merge-when-ready\", how.on);\n if (name === \"disable_merge_when_ready\") return description.replace(\"Turn off Graphite merge-when-ready\", how.off);\n return description;\n}\nconst schemas = (list, workflows = null) => list.map(([name, description, , properties, required]) => ({ name, description: describeAction(name, description, workflows), inputSchema: { type: \"object\", properties, required, additionalProperties: false }, annotations: { readOnlyHint: readOnlyTools.has(name), destructiveHint: destructiveTools.has(name) } }));\n/** Action tools: a session Paseo launched as a root agent (FOLLOW_THROUGH_ROOT) while Follow-up runs (fresh hook lease). */\nasync function actionsEnabled() {\n if (!process.env.PASEO_AGENT_ID || process.env.FOLLOW_THROUGH_ROOT !== \"1\" || process.env.FOLLOW_THROUGH_RECOVERY === \"1\") return false;\n try {\n const lease = JSON.parse(await readFile(join(process.env.PASEO_HOME ?? join(homedir(), \".paseo\"), \"plugin-data/follow-through/hooks-enabled.json\"), \"utf8\"));\n return lease.expiresAt > Date.now();\n } catch { return false; }\n}\n/** The bridge input for a tool: action tools travel as { tool, args } through follow.agent-act. */\nconst callInput = (tool, input) => actionNames.has(tool[0]) || overseerNames.has(tool[0]) ? { tool: tool[0], args: input } : input;\n/** The Overseer's routing tools: the session Follow-up launched as its Overseer, while Follow-up runs. */\nasync function overseerEnabled() {\n if (process.env.FOLLOW_THROUGH_OVERSEER !== \"1\" || !process.env.PASEO_AGENT_ID) return false;\n try {\n const lease = JSON.parse(await readFile(join(process.env.PASEO_HOME ?? join(homedir(), \".paseo\"), \"plugin-data/follow-through/hooks-enabled.json\"), \"utf8\"));\n return lease.expiresAt > Date.now();\n } catch { return false; }\n}\nlet scopeCache = null;\nasync function scopeOf(directory, agentId) {\n try {\n const path = join(directory, \"scopes.json\");\n const { mtimeMs } = await stat(path);\n if (scopeCache?.mtimeMs !== mtimeMs) { const file = JSON.parse(await readFile(path, \"utf8\")); scopeCache = { mtimeMs, agents: file.agents ?? {}, workflows: file.workflows ?? null }; }\n return scopeCache.agents[agentId]?.role ?? null;\n } catch (error) {\n if (error?.code !== \"ENOENT\") throw error;\n const state = JSON.parse(await readFile(join(directory, \"state.json\"), \"utf8\"));\n for (const w of state.workspaces) {\n if (!w.enable_tracking || w.archived) continue;\n if (w.mainAgentId === agentId) return \"main\";\n if (w.batches.some(b => b.recipientAgentId === agentId && !b.settledAt && [\"sending\", \"sent\", \"blocked\", \"uncertain\"].includes(b.state) && b.tasks.every(t => t.kind === \"inventory\"))) return \"recovery\";\n if (w.contributorAgentIds?.includes(agentId)) return \"contributor\";\n }\n return null;\n }\n}\n/** This agent's PR workflow from scopes.json (undefined: an older worker, which meant Graphite with /fix-pr). */\nconst workflowOf = agentId => scopeCache ? scopeCache.agents[agentId]?.workflow : undefined;\n/** Whether the repositories Follow-up knows ship through Graphite, GitHub or both (\"mixed\"); null: unknown, as before. */\nconst workflowsOf = () => scopeCache?.workflows ?? null;\nasync function scope(resolveRecovery = false) {\n const agentId = process.env.PASEO_AGENT_ID;\n if (!agentId) return null;\n try {\n const home = process.env.PASEO_HOME ?? join(homedir(), \".paseo\");\n const directory = join(home, \"plugin-data/follow-through\");\n const lease = JSON.parse(await readFile(join(directory, \"hooks-enabled.json\"), \"utf8\"));\n if (!(lease.expiresAt > Date.now())) return null;\n // scopes.json (a few KB, rewritten only when a role changes) instead of the whole state.json; re-read only\n // when its mtime changes. Older workers don't write it, so fall back to state.json.\n const known = await scopeOf(directory, agentId);\n if (known === \"main\") return process.env.FOLLOW_THROUGH_RECOVERY === \"1\" ? \"recovery\" : \"main\";\n if (known) return known;\n if (resolveRecovery && process.env.FOLLOW_THROUGH_RECOVERY === \"1\") {\n const w = await call(\"follow.agent-status\", {});\n if (w.enable_tracking && !w.archived && w.mainAgentId !== agentId && w.batches.some(b => b.recipientAgentId === agentId && !b.settledAt && [\"sending\", \"sent\", \"blocked\", \"uncertain\"].includes(b.state) && b.tasks.every(t => t.kind === \"inventory\"))) return \"recovery\";\n }\n } catch {}\n return null;\n}\nfunction validate(value, schema, path = \"arguments\") {\n const types = Array.isArray(schema.type) ? schema.type : [schema.type];\n const type = value === null ? \"null\" : Array.isArray(value) ? \"array\" : typeof value;\n if (!types.includes(type) && !(type === \"number\" && types.includes(\"integer\") && Number.isInteger(value))) throw new Error(`${path}: expected ${types.join(\" or \")}.`);\n if (schema.enum && !schema.enum.includes(value)) throw new Error(`${path}: choose ${schema.enum.join(\", \")}.`);\n if (type === \"object\") {\n const extra = Object.keys(value).filter(k => !Object.hasOwn(schema.properties ?? {}, k));\n if (extra.length && schema.additionalProperties === false) throw new Error(`Unknown argument ${path}.${extra.join(\", \")}. ${extra.includes(\"dependsOnPrs\") ? \"Use afterPrs with owner/repo#number keys.\" : \"Check this tool's input schema with list.\"}`);\n for (const key of schema.required ?? []) if (!(key in value)) throw new Error(`${path}.${key} is required. Check this tool's input schema with list.`);\n for (const [key, nested] of Object.entries(value)) if (schema.properties?.[key]) validate(nested, schema.properties[key], `${path}.${key}`);\n }\n if (type === \"array\") for (let i = 0; i < value.length; i++) validate(value[i], schema.items, `${path}[${i}]`);\n if (type === \"number\" && (schema.minimum !== undefined && value < schema.minimum || schema.maximum !== undefined && value > schema.maximum)) throw new Error(`${path}: outside the allowed range.`);\n if (type === \"string\" && (schema.minLength !== undefined && value.length < schema.minLength || schema.maxLength !== undefined && value.length > schema.maxLength)) throw new Error(`${path}: outside the allowed length.`);\n}\nfunction currentWork(w) {\n return { id: w.id, title: w.title, goal: w.goal, mainAgentId: w.mainAgentId, enable_tracking: w.enable_tracking, enable_auto_sends: w.enable_auto_sends, hold: w.hold, archived: w.archived, runtimeBusy: w.runtimeBusy, runtimeReason: w.runtimeReason, backgroundBusy: w.backgroundBusy, completion: w.completion,\n prs: w.prs.map(p => ({ key: p.key, stack: p.stack, parent: p.parent, disposition: p.disposition, error: p.error, ...(p.snapshot ? { title: p.snapshot.title, state: p.snapshot.state, head: p.snapshot.head, draft: p.snapshot.draft, reviewDecision: p.snapshot.reviewDecision, conflict: p.snapshot.conflict, openThreads: p.snapshot.threads.length, failedChecks: p.snapshot.failedChecks, otherFailedChecks: p.snapshot.otherFailedChecks ?? [], deployment: p.snapshot.deployment } : {}) })),\n obligations: w.obligations.filter(o => ![\"done\", \"waived\"].includes(o.status)), completedObligations: w.obligations.filter(o => [\"done\", \"waived\"].includes(o.status)).length,\n openQuestions: (w.questions ?? []).filter(q => !q.answer && !q.closed).map(q => ({ id: q.id, title: q.title, question: q.question, options: q.options, recommend: q.recommend, big: q.big, mode: q.mode, askedBy: q.askedBy, taskId: q.taskId })),\n spec: w.spec?.url ? { url: w.spec.url, title: w.spec.title, source: w.spec.source } : null,\n recentAnswers: (w.questions ?? []).filter(q => q.answer).slice(-5).map(q => ({ id: q.id, title: q.title, choice: q.answer.choice, words: q.answer.words, delivery: q.answer.delivery.state })),\n batches: w.batches.filter(b => ![\"completed\", \"cancelled\"].includes(b.state)).map(b => ({ id: b.id, state: b.state, tasks: b.tasks, result: b.result, recipientAgentId: b.recipientAgentId, contextPath: b.contextPath })),\n excludedStacks: w.excludedStacks.map(s => ({ name: s.name, reason: s.reason, prs: s.prs.map(p => p.key) })), ...(w.prWorkflow ? { prWorkflow: w.prWorkflow } : {}), detail: \"summary\" };\n}\nfunction compact(tool, input, result) {\n if (actionNames.has(tool)) return result;\n if (tool === \"workspace_status\") return currentWork(result);\n if (tool === \"needs_you\") return { ok: result.ok, briefId: result.briefId };\n if (tool === \"declare_done\") return { workspaceId: result.workspace.id, completion: result.workspace.completion, blockers: result.blockers };\n if (tool === \"ask_question\") return { workspaceId: result.workspaceId, question: { id: result.question.id, title: result.question.title, recommend: result.question.recommend, big: result.question.big }, mode: result.mode, instruction: result.instruction };\n if (tool === \"record_answer\" || tool === \"withdraw_question\") return { workspaceId: result.workspaceId, question: { id: result.question.id, answer: result.question.answer, closed: result.question.closed } };\n if (tool === \"set_spec\") return { workspaceId: result.workspaceId, spec: result.spec && { url: result.spec.url, title: result.spec.title, source: result.spec.source }, applied: result.applied, message: result.message };\n if (!result?.prs) return result;\n const workspaceId = result.id;\n if (tool === \"enroll_workspace\") return { workspaceId, goal: result.goal };\n 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 } }; }\n if (tool === \"update_obligation\") return { workspaceId, obligation: result.obligations.find(o => o.id === result.updatedObligationId) };\n 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 } }; }\n 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) } }; }\n return result;\n}\nasync function loadClient() {\n const candidates = [];\n if (process.env.FOLLOW_THROUGH_CLIENT_ENTRY) candidates.push(() => pathToFileURL(process.env.FOLLOW_THROUGH_CLIENT_ENTRY).href);\n const specifier = \"@getpaseo/client/internal/daemon-client\";\n if (process.resourcesPath) candidates.push(() => pathToFileURL(createRequire(join(process.resourcesPath, \"app.asar/node_modules/@getpaseo/cli/dist/index.js\")).resolve(specifier)).href);\n for (const directory of (process.env.PATH ?? \"\").split(delimiter)) {\n const cli = join(directory, process.platform === \"win32\" ? \"paseo.cmd\" : \"paseo\");\n if (existsSync(cli)) candidates.push(() => pathToFileURL(createRequire(realpathSync(cli)).resolve(specifier)).href);\n }\n candidates.push(() => pathToFileURL(createRequire(import.meta.url).resolve(specifier)).href);\n for (const resolve of candidates) try { return await import(resolve()); } catch {}\n throw new Error(\"Cannot load the installed Paseo client. Reload Follow-through to refresh its runtime connection.\");\n}\nconst batchInstructionsMain = \"Follow-through batches contain a header with the batchId and ordered tasks. Read workspace_status and refresh live conditions; skip resolved tasks. Process PRs bottom to top, one fully before the next, using the repository's /fix-pr and safe reparent workflow. Validate feedback, verify changes, submit with Graphite --publish, reply/resolve addressed threads and preserve uncommitted work. Post-deploy tasks require verified serving revisions and existing production permissions. Stakeholder update requests are follow-through tasks: retain the original thread, recipient and developer authorization in communication. Use current evidence, distinguish fixed/deployed/verified, and read existing replies before posting. Record the sent replyUrl; a draft or uncertain send stays blocked and must be checked before retrying. Auto authorizes agent delivery only. Acknowledge the header's batchId with acknowledge_batch before finishing (completed with the result, or blocked with the reason), before declare_done for completion batches. Declare Done only after the whole goal and post-merge work are verified. Leave merging and archiving to the developer.\";\n/**\n * The batch rules for this workspace's PR workflow. Graphite with /fix-pr (and any agent from before workflows\n * existed) gets the original text unchanged; plain GitHub never mentions Graphite, gt or a review command it doesn't have.\n */\nfunction batchInstructions(workflow) {\n const mode = workflow?.mode ?? \"graphite\";\n const fix = workflow === undefined || workflow === null ? \"/fix-pr\" : workflow.reviewFix ?? null;\n if (mode === \"graphite\" && fix === \"/fix-pr\") return batchInstructionsMain;\n const fixing = fix ? `using the repository's ${fix} workflow for review comments` : \"reading each PR's unresolved review threads with gh\";\n const restack = mode === \"graphite\" ? \"the repository's safe reparent workflow\" : \"base branches kept in a chain (restack with git rebase --update-refs, push with --force-with-lease, and after a parent merges retarget its child with gh pr edit --base if GitHub didn't)\";\n const submit = mode === \"graphite\" ? \"submit with Graphite --publish\" : \"push the branch (gh pr create for a new PR, gh pr ready when it leaves draft)\";\n const reply = fix ? \"reply/resolve addressed threads\" : \"reply to each addressed thread and resolve it\";\n return batchInstructionsMain\n .replace(\"using the repository's /fix-pr and safe reparent workflow.\", `${fixing}, with ${restack}.`)\n .replace(\"submit with Graphite --publish, reply/resolve addressed threads\", `${submit}, ${reply}`);\n}\n\nasync function call(method, input) {\n const agentId = process.env.PASEO_AGENT_ID;\n if (!agentId) throw new Error(\"This bridge must run inside a Paseo agent (PASEO_AGENT_ID is missing).\");\n const { DaemonClient } = await loadClient();\n const home = process.env.PASEO_HOME ?? join(homedir(), \".paseo\");\n const config = JSON.parse(await readFile(join(home, \"config.json\"), \"utf8\"));\n let password = process.env.PASEO_PASSWORD;\n if (!password && process.env.PASEO_PASSWORD_FILE) password = (await readFile(process.env.PASEO_PASSWORD_FILE, \"utf8\")).trim();\n if (!password && home === join(homedir(), \".paseo\")) password = await readFile(join(homedir(), \"paseo-hub/secrets/daemon-password\"), \"utf8\").then(s => s.trim()).catch(() => undefined);\n const client = new DaemonClient({ url: process.env.PASEO_DAEMON_URL ?? `ws://${config.daemon?.listen ?? \"127.0.0.1:6767\"}/ws`, clientId: \"follow-through-mcp\", clientType: \"cli\", reconnect: { enabled: false }, connectTimeoutMs: 10000, suppressSendErrors: true, ...(password ? { password } : {}) });\n try { await client.connect(); return await client.invokePluginRpc(\"follow-through\", method, { ...input, agentId }); }\n finally { await client.close().catch(() => undefined); }\n}\n\n\n// The worker imports this file for the same tool tables, validation and receipts (1.4.0-beta.2: Follow-up's tools\n// served natively through Paseo's own MCP). Only a direct run is the CLI / stdio bridge.\nexport { tools, actionTools, overseerTools, toolList, schemas, validate, compact, callInput, needsYouInstruction, actionInstruction, overseerInstruction, batchInstructions, describeAction };\nfunction isMain() {\n try { return !!process.argv[1] && !!import.meta.url && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href; } catch { return false; }\n}\nif (isMain()) runMain().catch(error => { console.error(error?.message ?? String(error)); process.exitCode = 1; });\nasync function runMain() {\nconst command = process.argv[2];\nif (command === \"list\" || command === \"--help\" || command === \"help\") {\n process.stdout.write(command === \"list\" ? JSON.stringify({ tools: schemas([...toolList(undefined, false, true, false, true), ...overseerTools]) }, null, 2) + \"\\n\" : \"Usage: node mcp.mjs list | call <tool> '<json>' [--compact]\\nNative MCP returns compact receipts; workspace_status({detail:full}) requests complete history. CLI calls retain full replies unless --compact is supplied.\\n\");\n} else if (command === \"call\") {\n try {\n const tool = [...toolList(undefined, false, await briefEnabled(), false, await actionsEnabled()), ...(await overseerEnabled() ? overseerTools : [])].find(t => t[0] === process.argv[3]);\n if (!tool) throw new Error(\"Unknown tool. Run list for names and input schemas.\");\n const input = JSON.parse(process.argv[4] ?? \"{}\");\n validate(input, schemas([tool])[0].inputSchema);\n if (process.argv.slice(5).some(arg => arg !== \"--compact\")) throw new Error(\"Unknown CLI option. Use --compact or omit it for a full reply.\");\n const result = await call(tool[2], callInput(tool, input));\n process.stdout.write(JSON.stringify(process.argv.includes(\"--compact\") && input.detail !== \"full\" ? compact(tool[0], input, result) : result, null, 2) + \"\\n\");\n } catch (error) { console.error(error.message); process.exitCode = 1; }\n} else if (command) {\n console.error(\"Unknown command. Use list, --help, or call <tool> '<json>'.\"); process.exitCode = 1;\n} else {\n const lines = createInterface({ input: process.stdin });\n let tail = Promise.resolve(), initialized = false, lastScope = null;\n const timer = process.env.PASEO_AGENT_ID ? setInterval(() => {\n void (async () => { const current = `${await scope()}:${await briefEnabled()}:${await actionsEnabled()}:${await overseerEnabled()}`; if (initialized && current !== lastScope) process.stdout.write(JSON.stringify({ jsonrpc: \"2.0\", method: \"notifications/tools/list_changed\" }) + \"\\n\"); lastScope = current; })().catch(() => {});\n }, 2000) : null;\n timer?.unref(); lines.on(\"close\", () => { if (timer) clearInterval(timer); });\n lines.on(\"line\", line => {\n tail = tail.then(async () => {\n let request;\n try { request = JSON.parse(line); } catch { return; }\n if (request.id === undefined) return;\n try {\n let result;\n const role = await scope(request.method === \"initialize\" || request.method === \"tools/list\");\n const brief = await briefEnabled();\n const acting = await actionsEnabled();\n const overseeing = await overseerEnabled();\n const workflow = workflowOf(process.env.PASEO_AGENT_ID);\n const available = [...(role ? toolList(role === \"recovery\", role === \"contributor\", brief, false, acting) : toolList(false, false, brief, true, acting)), ...(overseeing ? overseerTools : [])];\n if (request.method === \"initialize\") {\n initialized = true; lastScope = `${role}:${brief}:${acting}:${overseeing}`;\n result = { protocolVersion: request.params?.protocolVersion ?? \"2024-11-05\", capabilities: { tools: { listChanged: true } }, serverInfo: { name: \"paseo-follow-through\", version: \"0.3.5\" }, instructions: (role ? (role === \"contributor\" ? \"Register PRs this session submits, including from secondary git worktrees. Read workspace_status and call sync_workspace before finishing. Goal, task, scope and completion changes remain with the designated main agent.\" : role === \"recovery\" ? \"Recover tracking metadata from evidence, acknowledge your assigned batch, and leave completion to the main agent.\" : \"Keep workspace follow-through updated after PR submission and scope changes. Read workspace_status after compaction. Track all post-merge work. When a decision needs the developer, ask it with ask_question (lettered options and a recommendation) and follow the question mode in its reply. If you keep a spec artifact for this workspace, register its link once with set_spec. \" + batchInstructions(workflow)) + \" Perform bookkeeping silently: no sidebar-update announcements, plugin-status commentary or final sidebar recap. Put receipts and summaries in tools. Report actual work outcomes or decisions/blockers; discuss sidebar status only when explicitly asked.\" : brief ? \"\" : \"Follow-through tools are available to tracked workspace root agents and active recovery agents; contributor sessions receive PR registration and status tools.\") + (brief && role !== \"contributor\" && role !== \"recovery\" ? (role ? \" \" : \"\") + needsYouInstruction : \"\") + (acting && role !== \"contributor\" && role !== \"recovery\" ? \" \" + actionInstruction : \"\") + (overseeing ? \" \" + overseerInstruction : \"\") };\n } else if (request.method === \"ping\") result = {};\n else if (request.method === \"tools/list\") result = { tools: schemas(available, workflowsOf()) };\n else if (request.method === \"tools/call\") {\n const tool = available.find(t => t[0] === request.params?.name);\n try {\n if (!tool) throw new Error(\"This tool is unavailable for the current agent. Tracking must be active; recovery authority ends after acknowledgment.\");\n const input = request.params.arguments ?? {}; validate(input, schemas([tool])[0].inputSchema);\n const value = await call(tool[2], callInput(tool, input));\n result = { content: [{ type: \"text\", text: JSON.stringify(input.detail === \"full\" ? value : compact(tool[0], input, value)) }] };\n } catch (error) { result = { isError: true, content: [{ type: \"text\", text: error.message }] }; }\n } else { process.stdout.write(JSON.stringify({ jsonrpc: \"2.0\", id: request.id, error: { code: -32601, message: \"Method not found\" } }) + \"\\n\"); return; }\n process.stdout.write(JSON.stringify({ jsonrpc: \"2.0\", id: request.id, result }) + \"\\n\");\n } catch (error) { process.stdout.write(JSON.stringify({ jsonrpc: \"2.0\", id: request.id, error: { code: -32603, message: error.message } }) + \"\\n\"); }\n });\n });\n}\n}\n";
package/server/mcp.mjs CHANGED
@@ -54,6 +54,7 @@ const actionTools = [
54
54
  ["set_finish_flags", "Turn finish flags on or off for other agents, like Don't flag finishes." + ask, "follow.agent-act", { agentIds: array, value: boolean, ...planned }, []],
55
55
  ["set_priorities", "Rank workspaces for Home's Priority sort: per workspace (id or exact title) a score 0-100, a one-line reason the developer sees, and its sources [{kind: linear|slack|planning|github|paseo, label, url}]. replace=true drops workspaces you leave out. Used for 6 hours. Returns a dry run; store it with confirm=true and the planId.", "follow.agent-act", { priorities: { type: "array", items: { type: "object", properties: { workspace: string, score: { type: "integer", minimum: 0, maximum: 100 }, reason: { ...string, maxLength: 140 }, sources: { type: "array", items: { type: "object", properties: { kind: { type: "string", enum: ["linear", "slack", "planning", "github", "paseo"] }, label: string, url: string }, required: ["kind", "label"] } } }, required: ["workspace", "score", "reason"] } }, replace: boolean, ...planned }, ["priorities"]],
56
56
  // Settings, onboarding, Home and the panel, one developer RPC each (server/agent-parity.ts). Writes plan first.
57
+ ["make_main_agent", "Make yourself or another root agent of this workspace its main agent (the one that asks the developer, reports Needs-you and calls Done). requested=developer when the developer asked for it (refused only while the main is mid-turn); requested=self for your own claim, allowed only when the main is archived, gone or closed 30 minutes, or you registered every open PR and the main has been idle 24 hours, and never within 30 minutes of a change or 2 hours after you lost the role. Give a one-line reason the developer sees. Returns a dry run; run it with confirm=true and the planId.", "follow.agent-act", { agentId: string, reason: string, requested: { type: "string", enum: ["developer", "self"] }, ...planned }, []],
57
58
  ["display_settings", "Read Settings → Display: the header button, sidebar item, composer pill, Needs-you inbox, closed-PR flags, brief nudge, Overseer, ranker and trust bypass switches." + read, "follow.agent-act", {}, []],
58
59
  ["set_display", "Change Settings → Display switches, e.g. { values: { enable_trust_bypass: false } }. Keys from display_settings." + ask, "follow.agent-act", { values: { type: "object", additionalProperties: boolean }, ...planned }, []],
59
60
  ["follow_settings", "Read Settings → Following: follow every workspace, the Auto-send default, the active window, and per-workspace exceptions." + read, "follow.agent-act", {}, []],
@@ -103,14 +104,15 @@ const overseerInstruction = "You are Follow-up's Overseer. Route Tom's asks with
103
104
  const actionNames = new Set(actionTools.map(t => t[0]));
104
105
  const readOnlyTools = new Set(["workspace_status", "list_prs", "inbox_list", "workstreams", "agent_digest", "route_candidates", "workspace_about", "agent_settings", "display_settings", "follow_settings", "project_settings", "pr_workflow", "reviewer_settings", "reviewer_suggestions", "onboarding_status", "onboarding_checks", "priorities", "rank_status", "usage", "overseer_status", "inbox_brief", "pr_controls", "browser_status", "trust_bypass_status"]);
105
106
  const destructiveTools = new Set(["merge"]);
106
- const actionInstruction = "Follow-up's action tools let you do anything the developer can click, across every tracked workspace and every Settings tab. Read freely: list_prs, inbox_list, inbox_brief, workspace_about, agent_settings, display_settings, follow_settings, project_settings, pr_workflow, reviewer_settings, onboarding_status, priorities, rank_status, usage, overseer_status, pr_controls. Act only when the developer asks (\"the PRs look good, assign reviewers on all\": list_prs needs_reviewers=true, add_reviewers with those keys, then confirm the plan): add_reviewers, merge, enable/disable_merge_when_ready, send_repairs, set_auto_send, clear_hold, retry_batch, track, run_recovery, set_priorities, rerank_priorities; settings with set_display (trust bypass too), set_follow_settings, set_project_tracking, set_pr_workflow, save_reviewers, set_agent_setting, set_onboarding; and sign_off/snooze/set_finish_flags/inbox_act/brief_action/answer_question for other agents. Planned tools return a dry run showing what changes; run it with confirm=true and its planId. Never sign yourself off or answer your own brief.";
107
+ const actionInstruction = "Follow-up's action tools let you do anything the developer can click, across every tracked workspace and every Settings tab. Read freely: list_prs, inbox_list, inbox_brief, workspace_about, agent_settings, display_settings, follow_settings, project_settings, pr_workflow, reviewer_settings, onboarding_status, priorities, rank_status, usage, overseer_status, pr_controls. Hand the main role on, or claim it, with make_main_agent. Act only when the developer asks (\"the PRs look good, assign reviewers on all\": list_prs needs_reviewers=true, add_reviewers with those keys, then confirm the plan): add_reviewers, merge, enable/disable_merge_when_ready, send_repairs, set_auto_send, clear_hold, retry_batch, track, run_recovery, set_priorities, rerank_priorities; settings with set_display (trust bypass too), set_follow_settings, set_project_tracking, set_pr_workflow, save_reviewers, set_agent_setting, set_onboarding; and sign_off/snooze/set_finish_flags/inbox_act/brief_action/answer_question for other agents. Planned tools return a dry run showing what changes; run it with confirm=true and its planId. Never sign yourself off or answer your own brief.";
107
108
 
108
109
  // The brief's tool: every root agent while the Needs-you inbox is on; never contributors, recovery or subagents.
109
110
  // Kept identical to NEEDS_YOU_INSTRUCTION in shared/brief.ts (a test checks it).
110
111
  const needsYouInstruction = "When you end a turn, call `needs_you` once, just before your final reply, with what the developer has to do next: a decision (give 2–3 options, what each means for them, and the one you recommend), an action only they can take (merge, approve, log in, run or send something), or kind=done (\"Nothing needed\" plus what you finished, in one line), which means there is nothing for the developer and won't flag you in their inbox. Keep `ask` to one line and `context` to what they need to decide. Don't repeat your report there; still write your normal reply. Don't call it while a permission prompt is waiting or while you're still working.";
111
112
  function toolList(recovery = process.env.FOLLOW_THROUGH_RECOVERY === "1", contributor = false, brief = false, briefOnly = false, actions = false) {
112
113
  // Action tools: root agents (tracked main or untracked) while Follow-up runs; never recovery or contributors.
113
- const acting = actions && !recovery && !contributor ? actionTools : [];
114
+ // Contributors get make_main_agent only (its claim rules apply); recovery sessions get none.
115
+ const acting = !actions || recovery ? [] : contributor ? actionTools.filter(t => t[0] === "make_main_agent") : actionTools;
114
116
  if (briefOnly) return [...(brief ? tools.filter(t => t[0] === "needs_you") : []), ...acting];
115
117
  return [...tools.filter(t => t[0] === "needs_you" ? brief && !recovery && !contributor : contributor ? ["workspace_status", "register_pr", "sync_workspace"].includes(t[0]) : !recovery || !["declare_done", "sync_workspace", "ask_question", "record_answer", "withdraw_question", "set_spec"].includes(t[0])), ...acting];
116
118
  }
package/server/scopes.ts CHANGED
@@ -10,7 +10,8 @@ export type Role = "main" | "contributor" | "recovery";
10
10
  * agent runs both; they used to parse the whole state.json (5.3 MB on the VM) every 2 seconds and on every tool
11
11
  * call. This file is a few KB and rewritten only when a role changes.
12
12
  */
13
- type Entry = { role: Role; workspaceId: string; workflow?: AgentWorkflow };
13
+ /** `demoted` (1.4.0-beta.22): the newest time this contributor lost the main role, so its hook can say so on its next turn. */
14
+ type Entry = { role: Role; workspaceId: string; workflow?: AgentWorkflow; demoted?: { to: string; at: string; reason: string | null; by: string } };
14
15
  /**
15
16
  * `workflow` (1.4.0-beta.14) is the workspace's PR workflow and review-fix command, so the hook and bridge give
16
17
  * GitHub-only workspaces GitHub instructions. Absent: Graphite with /fix-pr, as every earlier version said.
@@ -20,7 +21,10 @@ export function scopes(state: State, workflow?: (w: Workspace) => AgentWorkflow)
20
21
  for (const w of state.workspaces) {
21
22
  if (!w.enable_tracking || w.archived) continue;
22
23
  const flow = workflow ? { workflow: workflow(w) } : {};
23
- for (const id of w.contributorAgentIds ?? []) agents[id] ??= { role: "contributor", workspaceId: w.id, ...flow };
24
+ for (const id of w.contributorAgentIds ?? []) {
25
+ const lost = w.mainHistory?.findLast(c => c.from === id);
26
+ agents[id] ??= { role: "contributor", workspaceId: w.id, ...flow, ...(lost ? { demoted: { to: lost.to, at: lost.at, reason: lost.reason, by: lost.by } } : {}) };
27
+ }
24
28
  for (const b of w.batches) if (b.recipientAgentId && !b.settledAt && ["sending", "sent", "blocked", "uncertain"].includes(b.state) && b.tasks.every(t => t.kind === "inventory")) agents[b.recipientAgentId] = { role: "recovery", workspaceId: w.id, ...flow };
25
29
  agents[w.mainAgentId] = { role: "main", workspaceId: w.id, ...flow };
26
30
  }
package/shared/home.ts CHANGED
@@ -32,6 +32,14 @@ export const tierOf = (key: HeadlineKey): Tier => TIER[key];
32
32
 
33
33
  export type BadgeTone = "warning" | "danger" | "success" | "merged" | "muted";
34
34
  export type Badge = { text: string; tone: BadgeTone };
35
+ /**
36
+ * The newest change of main agent within a day, when an agent or Follow-up made it (the developer knows their own).
37
+ * Home badges it; the panel shows "Main agent changed: A → B" with Undo.
38
+ */
39
+ export function recentMainChange(w: Pick<Workspace, "mainHistory" | "mainAgentId">, now: number): NonNullable<Workspace["mainHistory"]>[number] | null {
40
+ const last = w.mainHistory?.at(-1);
41
+ return last && last.by !== "developer" && last.to === w.mainAgentId && now - Date.parse(last.at) < 24 * 60 * 60_000 ? last : null;
42
+ }
35
43
  export type PrChip = { label: string; tone: PrTone; checks: { text: string; tone: BadgeTone } | null; url: string | null };
36
44
  /** A Paseo workspace as Home needs it. Untracked workspaces still get a row, in Quiet. */
37
45
  export type PaseoWorkspaceLite = {
@@ -214,7 +222,10 @@ export function buildHome(input: { rows: InboxRow[]; tracked: Workspace[]; paseo
214
222
  const urgent = !!w?.questions.some(q => questionOpen(q) && !!q.big);
215
223
  const due = w ? followUpObligations(w).filter(o => !["done", "waived"].includes(o.status)).map(o => taskSchedule(o, w, now).dueAt).filter((x): x is string => !!x).sort()[0] ?? null : null;
216
224
  const priority = p ? { score: p.score, reason: p.reason, source: p.sources[0] ? { kind: p.sources[0].kind, label: p.sources[0].label } : null } : null;
217
- return make({ ...stripSig(s), activityAt, urgent, due, priority });
225
+ // Rule 5 of main-agent claims: a quiet badge for a day after an agent or Follow-up changed the main agent.
226
+ // Last in line, so it never pushes out a badge that asks for something.
227
+ const badges = w && recentMainChange(w, now) ? [...s.badges, { text: "Main agent changed", tone: "muted" as const }].slice(0, 2) : s.badges;
228
+ return make({ ...stripSig(s), badges, activityAt, urgent, due, priority });
218
229
  });
219
230
  const byGroup = new Map<HomeGroupId, Workstream[]>(HOME_GROUPS.map(g => [g, []]));
220
231
  for (const s of finished) byGroup.get(s.group)!.push(s);
package/shared/model.ts CHANGED
@@ -71,6 +71,10 @@ export const workspaceSchema = z.object({
71
71
  mainClosedSince: z.string().optional(),
72
72
  /** A main agent closed for MAIN_CLOSED_HANDOVER_MS handed the workspace to `mainAgentId`; until that agent does main-agent work, a live `from` takes it back. */
73
73
  handover: z.object({ from: idSchema, at: z.string(), worked: z.boolean() }).optional(),
74
+ /** Every change of main agent, newest last, at most 20 (1.4.0-beta.22). by: developer, auto, or agent:<id>. */
75
+ mainHistory: z.array(z.object({ from: idSchema, to: idSchema, by: z.string(), reason: z.string().nullable(), at: z.string() })).optional(),
76
+ /** When the main agent last made a main-agent call (sync, tasks, questions, needs_you, Done), hourly at most. */
77
+ mainWorkAt: z.string().optional(),
74
78
  enable_tracking: z.boolean().default(false), enable_auto_sends: z.boolean().default(false), hold: z.string().nullable(), archived: z.boolean(),
75
79
  prs: z.array(prSchema), obligations: z.array(obligationSchema), batches: z.array(batchSchema),
76
80
  excludedStacks: z.array(z.object({ name: textSchema, reason: textSchema, excludedAt: z.string(), prs: z.array(prSchema), obligations: z.array(obligationSchema) })).default([]),