paseo-follow-up 1.4.0-beta.6 → 1.4.0-beta.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/OVERVIEW.md +3 -0
- package/README.md +14 -1
- package/client/display.tsx +1 -0
- package/client/home-chrome.tsx +29 -6
- package/client/home-list.tsx +3 -3
- package/client/home-view.ts +19 -1
- package/client/home.tsx +2 -1
- package/index.server.ts +21 -2
- package/package.json +1 -1
- package/server/ai-jobs.ts +16 -6
- package/server/mcp-source.ts +1 -1
- package/server/mcp.mjs +1 -0
- package/server/overseer-prompt-source.ts +1 -1
- package/server/overseer-prompt.md +1 -0
- package/server/overseer.ts +7 -2
- package/server/ranker.ts +313 -0
- package/shared/contracts.ts +4 -0
- package/shared/display.ts +3 -1
- package/shared/ranker.ts +135 -0
package/OVERVIEW.md
CHANGED
|
@@ -6,6 +6,7 @@ Follow-up watches every pull request a Paseo workspace opens until the work is a
|
|
|
6
6
|
|
|
7
7
|
- Home: every workspace grouped by what it needs from you (Needs you, Follow-up is fixing, Running, Waiting on others, Quiet), with the selected one beside the list so you can allow a permission, answer, merge, reply or sign off in place, and a brief with what Follow-up did while you were away. Above the list: the status counts, provider limits from Smart Session when it's installed, a search over names, branches, PRs, agents and asks, and a sort menu (Priority, Recent, Oldest waiting, Name, By project).
|
|
8
8
|
- The Overseer (1.4 beta), pinned on Home: one agent you talk to about all your workspaces. It forwards your asks to the agent that owns them, asks you when it isn't sure, and starts a new workspace only when you say so. You can ask it from Home's search box (the last row, "Ask the Overseer: …") or with ⌘K → Follow-up: Ask the Overseer.
|
|
9
|
+
- AI priority (1.4 beta): Home's Priority sort ranked from your Linear issues, Slack DMs and mentions, GitHub review requests and the weekly plan, each row with a one-line reason that names its source. It runs hourly on workdays, only when something changed, and Re-rank now is in the sort menu.
|
|
9
10
|
- What's this about?, a collapsible section at the top of Home's detail pane and the workspace panel: a one-line gist, a short AI overview of what the workspace is for and where it stands, and its linked Linear issues, PRs, Slack threads and docs.
|
|
10
11
|
- A workspace panel for the open workspace only, with a Home button: PRs merged, what needs you, what needs fixing, a bar with one segment per PR, and what the agent is doing now. "Open full" on Home docks it beside the agent's chat.
|
|
11
12
|
- A Needs you card with one button per decision: Send repairs, Merge, Resume, Retry, or Answer.
|
|
@@ -45,3 +46,5 @@ The Overseer (beta) is one Claude agent in a Follow-up workspace under `plugin-d
|
|
|
45
46
|
"What's this about?" keeps its overviews in `plugin-data/follow-through/about.json` (gist, overview, linked rows, when and from what; never raw history) and logs each model call's duration and cost to `ai-jobs.jsonl`. To write one it reads the root agent's latest steps from its live timeline only when Paseo already has the agent loaded; otherwise it reads the first and last part of the agent's provider transcript on disk (Claude Code's `~/.claude/projects`, Codex's `~/.codex/sessions`), read-only, and never wakes the agent. It reads subagent titles from Paseo's agent list, PR titles and bodies with `gh pr view`, and only the Linear issues and Slack threads the workspace itself links, through `mcpproxy call tool-read` (`linear:get_issue`, `slack-user:slack_read_thread`); there are no searches. The model is set under Settings → Agents (default Haiku). With Claude it runs as a headless `claude -p` with no tools, no MCP servers, no settings and no saved session. With Codex it runs as `codex exec --ephemeral` with no user config or rules, no shell tool and a read-only sandbox in an empty temporary folder. Either way it gets one turn, a 90-second timeout, and runs one call at a time; on timeout the whole process group is killed. Overviews are written ahead of time only for non-dormant workspaces in Needs you, at most 60 a day by default (Settings → Agents), and not while a Claude account is above 85% of a limit or the resource governor has paused background work; above its higher threshold, opening the section shows the cached overview and writes none.
|
|
46
47
|
|
|
47
48
|
Settings → Agents (`plugin-data/follow-through/agents.json`, its own file) chooses the provider, model, effort and mode for What's this about?, the Overseer, recovery agents and the priority ranker. Missing or invalid entries use the defaults. The provider and model list comes from Paseo's provider snapshot. It is read only when that settings screen opens, and cached for ten minutes. A changed Overseer setting is never applied mid-conversation: Home offers a restart, and the new Overseer is handed the old one's last steps (read from its transcript on disk when it isn't loaded). The old agent is left as it is. A recovery agent on a different provider than the main agent keeps the main agent's system prompt, MCP servers and tool policy, and drops its provider-specific model, mode and options. `FOLLOW_UP_OVERSEER_PROVIDER` ("provider/model") overrides the Overseer's setting; it exists only for isolated test daemons.
|
|
49
|
+
|
|
50
|
+
The ranker behind AI priority (beta) runs inside Follow-up's worker as bounded one-shot jobs (Claude or Codex, per the ranker role) through the shared job runner (`server/ai-jobs.ts`), one at a time and only while the resource governor allows background work. It reads Follow-up's own state, `mcpproxy call tool-read` for `linear:list_issues` (assigned to you) and `slack-user:slack_search_public_and_private` (DMs and mentions, last 48 hours), `gh search prs --review-requested=@me`, and the planning artifact through one Claude turn limited to the Artifact tool. It hashes those inputs and calls the model only when they changed. It writes only `plugin-data/follow-through/priorities.json` (its ranking, which replaces its previous one) and `ranker.json` (input hash, run count, source health, the day's plan summary, and Linear issues no workspace covers). It never stores raw artifact HTML or share keys. The provider, model, cadence and daily cap come from the ranker role in Settings → Agents; the plan reader always uses Claude, the only provider with the Artifact tool.
|
package/README.md
CHANGED
|
@@ -150,6 +150,19 @@ One agent you talk to about all your workspaces. It sits pinned at the top of Ho
|
|
|
150
150
|
|
|
151
151
|
Turn it off under Settings → **Overseer (beta)**. While it's off, search has no ask row.
|
|
152
152
|
|
|
153
|
+
#### AI priority (1.4 beta)
|
|
154
|
+
|
|
155
|
+
Home's **Priority** sort can come from a ranker that reads what's happening outside Paseo: your assigned Linear issues (priority, due date, project and milestone), Slack DMs and mentions from the last 48 hours, open GitHub review requests, and the CPO's weekly planning artifact. Each row then shows a one-line reason that names its source, such as "HER-1312 · Urgent · due today" or "Slack: Dana asked twice". Needs you still comes first, whatever the score.
|
|
156
|
+
|
|
157
|
+
- **When it runs:** about once an hour, Sunday to Thursday from 08:00 to 20:00 Israel time. **Re-rank now** in the sort menu runs it at any time, and so does asking the Overseer what to work on first. The menu says when it last ranked and names any source it couldn't read ("Ranked 12m ago · Slack unavailable").
|
|
158
|
+
- **What it costs:** it calls the model only when its inputs changed since the last run, and at most 24 times a day (Re-rank now isn't capped). A run at about 100 workspaces is one Sonnet call of roughly 10k input tokens, about $0.06 and 20 s. The weekly plan is read at most once a day, for about $0.03. Each run's cost and duration go to `ai-jobs.jsonl`.
|
|
159
|
+
- **What it touches:** everything is read-only: Follow-up's own state, read-only Linear and Slack tools through mcpproxy, `gh search prs`, and one read of the planning artifact with Claude's Artifact tool and no other tools. It never posts, comments or publishes. The artifact's link comes from `FOLLOW_UP_PLAN_URL`, or else from the morning-brief skill's source list (link only, without any share key).
|
|
160
|
+
- Linear issues assigned to you that no workspace covers are kept for a later "Not started" group; they aren't shown yet.
|
|
161
|
+
|
|
162
|
+
Turn it off under Settings → **Overseer (beta)** → **AI priority**.
|
|
163
|
+
|
|
164
|
+

|
|
165
|
+
|
|
153
166
|

|
|
154
167
|
|
|
155
168
|
### Choosing models
|
|
@@ -170,7 +183,7 @@ The choices live in `agents.json` in Follow-up's data folder. Anything missing o
|
|
|
170
183
|
Install the beta:
|
|
171
184
|
|
|
172
185
|
```sh
|
|
173
|
-
paseo plugin update follow-through --version 1.4.0-beta.
|
|
186
|
+
paseo plugin update follow-through --version 1.4.0-beta.7
|
|
174
187
|
# or, for a fresh install:
|
|
175
188
|
paseo plugin install npm:paseo-follow-up@beta
|
|
176
189
|
```
|
package/client/display.tsx
CHANGED
|
@@ -67,6 +67,7 @@ export function DisplaySections({ theme }: Pick<PluginSurfaceProps, "theme">) {
|
|
|
67
67
|
<SettingsSection title="Overseer (beta)" info="One agent you can ask about all your work. It sends each task to the agent that owns it and asks you when it isn't sure.">
|
|
68
68
|
<SettingsCard>
|
|
69
69
|
<SettingsSwitch label="Overseer" hint="Off hides its row on Home and stops its digest. An Overseer you already started stays in its workspace; Follow-up never archives it." value={settings.values.enable_overseer} disabled={settings.saving} onValueChange={(enable_overseer) => save({ enable_overseer })} />
|
|
70
|
+
<SettingsSwitch label="AI priority" hint="Ranks Home's Priority sort from Linear, Slack, GitHub and the weekly plan. Read-only; runs hourly on workdays when something changed." value={settings.values.enable_ranker} disabled={settings.saving} onValueChange={(enable_ranker) => save({ enable_ranker })} />
|
|
70
71
|
</SettingsCard>
|
|
71
72
|
</SettingsSection>
|
|
72
73
|
</>
|
package/client/home-chrome.tsx
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from "react";
|
|
2
2
|
import { Platform, Pressable, Text, TextInput, View } from "react-native";
|
|
3
|
-
import { Icon } from "@getpaseo/plugin/client/ui";
|
|
3
|
+
import { Icon, useToast } from "@getpaseo/plugin/client/ui";
|
|
4
4
|
import { GROUP_TITLE, homeCounts, type HomeGroupId, type HomeModel } from "../shared/home";
|
|
5
5
|
import { FIELD_LABEL, excerpt, highlightRuns, homeSearchDocs, indexDocs, defaultActive, omniboxResults, overseerProvider, workspaceProvider, type OmniboxItem, type OmniboxProvider, type Range, type WorkspaceItem } from "../shared/search";
|
|
6
6
|
import { SORT_HINT, SORT_LABEL, SORT_MODES, type SortMode } from "../shared/sort";
|
|
@@ -112,14 +112,30 @@ export function SearchField({ theme, omnibox, dense, onEnter }: { theme: Theme;
|
|
|
112
112
|
|
|
113
113
|
// ---------- sort ----------
|
|
114
114
|
|
|
115
|
-
export
|
|
115
|
+
export type RankState = { enabled: boolean; running: boolean; healthLine: string; error: string | null } | null;
|
|
116
|
+
|
|
117
|
+
export function SortMenu({ theme, mode, onChange, rankedAt, touch, rank = null, onRerank }: { theme: Theme; mode: SortMode; onChange: (m: SortMode) => void; rankedAt: string | null; touch: boolean; rank?: RankState; onRerank?: () => Promise<{ ok: boolean; skipped: string | null; error: string | null; top?: { title: string }[] }> }) {
|
|
116
118
|
const c = theme.colors;
|
|
117
119
|
const [open, setOpen] = useState(false);
|
|
118
120
|
const now = useMinute();
|
|
121
|
+
const toast = useToast();
|
|
122
|
+
const running = !!rank?.running;
|
|
123
|
+
const rerank = async () => {
|
|
124
|
+
if (!onRerank || running) return;
|
|
125
|
+
setOpen(false);
|
|
126
|
+
try {
|
|
127
|
+
const r = await onRerank();
|
|
128
|
+
if (!r.ok) toast.error(r.error ?? "Couldn't re-rank.");
|
|
129
|
+
else if (r.skipped === "busy") toast.show("Already re-ranking");
|
|
130
|
+
else toast.show(r.skipped === "same" ? "Nothing new in Linear, Slack, GitHub or the plan since the last ranking" : r.top?.[0] ? `Re-ranked · ${r.top[0].title} first` : "Re-ranked", { variant: "success" });
|
|
131
|
+
} catch (e) { toast.error(e instanceof Error ? e.message : String(e)); }
|
|
132
|
+
};
|
|
133
|
+
// "Ranked 12m ago · Slack unavailable": the age, then any source the last run couldn't read.
|
|
134
|
+
const note = running ? "Re-ranking…" : [priorityNote(rankedAt, now), rank?.enabled ? rank.healthLine : ""].filter(Boolean).join(" · ");
|
|
119
135
|
return <View style={{ position: "relative", zIndex: 20 }}>
|
|
120
136
|
<Pressable accessibilityRole="button" accessibilityLabel={`Sort: ${SORT_LABEL[mode]}`} aria-expanded={open} accessibilityState={{ expanded: open }} onPress={() => setOpen(o => !o)}
|
|
121
137
|
style={state => ({ flexDirection: "row", alignItems: "center", gap: 4, height: touch ? 36 : 30, paddingHorizontal: 8, borderRadius: 6, backgroundColor: open || (state as { hovered?: boolean }).hovered ? c.surface2 : "transparent" })}>
|
|
122
|
-
<Icon name="ArrowUpDown" size={13} color={c.foregroundMuted} />
|
|
138
|
+
{running ? <Spinner color={c.foregroundMuted} size={12} label="Re-ranking" /> : <Icon name="ArrowUpDown" size={13} color={c.foregroundMuted} />}
|
|
123
139
|
<Text numberOfLines={1} style={{ color: c.foreground, fontSize: 12 }}>{SORT_LABEL[mode]}</Text>
|
|
124
140
|
<Icon name="ChevronDown" size={12} color={c.foregroundMuted} />
|
|
125
141
|
</Pressable>
|
|
@@ -133,7 +149,14 @@ export function SortMenu({ theme, mode, onChange, rankedAt, touch }: { theme: Th
|
|
|
133
149
|
<Text numberOfLines={1} style={{ color: c.foregroundMuted, fontSize: 11, lineHeight: 15 }}>{SORT_HINT[m]}</Text>
|
|
134
150
|
</View>
|
|
135
151
|
</Pressable>)}
|
|
136
|
-
<
|
|
152
|
+
<View style={{ marginTop: 4, borderTopWidth: 1, borderTopColor: c.border, paddingTop: 2 }}>
|
|
153
|
+
{rank?.enabled && onRerank && <Pressable accessibilityRole="menuitem" accessibilityState={{ busy: running, disabled: running }} disabled={running} onPress={() => void rerank()}
|
|
154
|
+
style={state => ({ flexDirection: "row", alignItems: "center", gap: 8, minHeight: touch ? 44 : 34, paddingHorizontal: 10, backgroundColor: (state as { hovered?: boolean }).hovered ? c.surface2 : "transparent" })}>
|
|
155
|
+
<View style={{ width: 14 }}>{running ? <Spinner color={c.foregroundMuted} size={12} label="Re-ranking" /> : <Icon name="RefreshCw" size={13} color={c.foreground} />}</View>
|
|
156
|
+
<Text style={{ color: running ? c.foregroundMuted : c.foreground, fontSize: 13 }}>{running ? "Re-ranking…" : "Re-rank now"}</Text>
|
|
157
|
+
</Pressable>}
|
|
158
|
+
<Text style={{ color: c.foregroundMuted, fontSize: 11, paddingHorizontal: 10, paddingTop: 4, paddingBottom: 4 }}>Priority: {note}</Text>
|
|
159
|
+
</View>
|
|
137
160
|
</View>}
|
|
138
161
|
</View>;
|
|
139
162
|
}
|
|
@@ -285,12 +308,12 @@ export function AskRow({ ask, theme, active, dense, touch, sending, onPress }: {
|
|
|
285
308
|
}
|
|
286
309
|
|
|
287
310
|
/** The muted reason and source chip a fresh external priority adds to a row. */
|
|
288
|
-
export function PriorityLine({ reason, source, c, size = 12 }: { reason: string; source: { kind: keyof typeof PRIORITY_SOURCE_LABEL; label: string } | null; c: Colors; size?: number }) {
|
|
311
|
+
export function PriorityLine({ reason, source, c, size = 12, lines = 1 }: { reason: string; source: { kind: keyof typeof PRIORITY_SOURCE_LABEL; label: string } | null; c: Colors; size?: number; lines?: number }) {
|
|
289
312
|
return <View style={{ flexDirection: "row", alignItems: "center", gap: 6, minWidth: 0 }}>
|
|
290
313
|
{source && <View style={{ paddingHorizontal: 5, height: 16, justifyContent: "center", borderRadius: 3, backgroundColor: c.surface2 }}>
|
|
291
314
|
<Text numberOfLines={1} style={{ color: c.foregroundMuted, fontSize: 10, lineHeight: 13 }}>{PRIORITY_SOURCE_LABEL[source.kind]}</Text>
|
|
292
315
|
</View>}
|
|
293
|
-
<Text numberOfLines={
|
|
316
|
+
<Text numberOfLines={lines} style={{ flex: 1, minWidth: 0, color: c.foregroundMuted, fontSize: size, fontStyle: "italic" }}>{reason}</Text>
|
|
294
317
|
</View>;
|
|
295
318
|
}
|
|
296
319
|
|
package/client/home-list.tsx
CHANGED
|
@@ -237,18 +237,18 @@ const Row = memo(function Row({ s, theme, dense, touch, selected, onSelect }: Ro
|
|
|
237
237
|
{(!!s.word || !!s.line) && <Text numberOfLines={2} style={{ color: c.foregroundMuted, fontSize: 12, lineHeight: 16 }}>
|
|
238
238
|
{s.word && s.group === "needs" ? <Text style={{ color, fontWeight: "600" }}>{s.word}</Text> : null}{s.word && s.group === "needs" && s.line ? " · " : ""}{line}
|
|
239
239
|
</Text>}
|
|
240
|
-
{s.priority && <PriorityLine reason={s.priority.reason} source={s.priority.source} c={c} size={11} />}
|
|
240
|
+
{!!s.priority?.reason && <PriorityLine reason={s.priority.reason} source={s.priority.source} c={c} size={11} lines={2} />}
|
|
241
241
|
{touch && (s.pr || s.badges.length > 0) && <View style={{ flexDirection: "row", flexWrap: "wrap", gap: 6, marginTop: 4 }}>
|
|
242
242
|
{s.badges.map(b => <BadgeView key={b.text} b={b} c={c} />)}<PrChipView s={s} c={c} />
|
|
243
243
|
</View>}
|
|
244
|
-
</View> : <View style={{ flex: 1, minWidth: 0, gap: 1, paddingVertical: s.priority ? 4 : 0 }}><View style={{ flexDirection: "row", alignItems: "center", gap: 10 }}>
|
|
244
|
+
</View> : <View style={{ flex: 1, minWidth: 0, gap: 1, paddingVertical: s.priority?.reason ? 4 : 0 }}><View style={{ flexDirection: "row", alignItems: "center", gap: 10 }}>
|
|
245
245
|
<Text numberOfLines={1} style={{ flexShrink: 0, maxWidth: "55%", color: muted ? c.foregroundMuted : c.foreground, fontSize: 13, fontWeight: muted ? "400" : "500" }}>{s.title}{s.agent ? <Text style={{ color: c.foregroundMuted, fontWeight: "400" }}>{` › ${s.agent}`}</Text> : null}</Text>
|
|
246
246
|
<Text numberOfLines={1} style={{ flex: 1, minWidth: 0, color: c.foregroundMuted, fontSize: 12 }}>
|
|
247
247
|
{s.word && s.group === "needs" ? <Text style={{ color }}>{s.word}</Text> : null}{s.word && s.group === "needs" && s.line ? " · " : ""}{line}
|
|
248
248
|
</Text>
|
|
249
249
|
{s.badges.map(b => <BadgeView key={b.text} b={b} c={c} />)}
|
|
250
250
|
<PrChipView s={s} c={c} />
|
|
251
|
-
</View>{s.priority && <View style={{ paddingRight: 40 }}><PriorityLine reason={s.priority.reason} source={s.priority.source} c={c} /></View>}</View>}
|
|
251
|
+
</View>{!!s.priority?.reason && <View style={{ paddingRight: 40 }}><PriorityLine reason={s.priority.reason} source={s.priority.source} c={c} /></View>}</View>}
|
|
252
252
|
<Age iso={s.at} c={c} size={dense ? 11 : 12} />
|
|
253
253
|
</Pressable>;
|
|
254
254
|
}, (a, b) => a.sig === b.sig && a.selected === b.selected && a.theme === b.theme && a.dense === b.dense && a.touch === b.touch && a.onSelect === b.onSelect);
|
package/client/home-view.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { PluginClientContext } from "@getpaseo/plugin/client";
|
|
2
|
-
import { overseerAskRpc, overseerRestartRpc, overseerStartRpc, overseerStatusRpc, prioritiesRpc, usageRpc } from "../shared/contracts";
|
|
2
|
+
import { overseerAskRpc, overseerRestartRpc, overseerStartRpc, overseerStatusRpc, prioritiesRpc, rankNowRpc, rankStatusRpc, usageRpc } from "../shared/contracts";
|
|
3
3
|
import type { RpcOutput } from "@getpaseo/plugin";
|
|
4
4
|
import type { Priority } from "../shared/priorities";
|
|
5
5
|
import { DEFAULT_SORT, isSortMode, type SortMode } from "../shared/sort";
|
|
@@ -29,6 +29,7 @@ export function createHomeExtras(client: PluginClientContext) {
|
|
|
29
29
|
let priorities: Priority[] = [];
|
|
30
30
|
let usage: Usage = NO_USAGE;
|
|
31
31
|
let overseer: RpcOutput<typeof overseerStatusRpc> | null = null;
|
|
32
|
+
let rank: RpcOutput<typeof rankStatusRpc> | null = null;
|
|
32
33
|
const agents = new Map<string, AgentLite>();
|
|
33
34
|
let version = 0;
|
|
34
35
|
let focusToken = 0;
|
|
@@ -60,6 +61,12 @@ export function createHomeExtras(client: PluginClientContext) {
|
|
|
60
61
|
if (JSON.stringify(next) === JSON.stringify(priorities)) return false;
|
|
61
62
|
priorities = next; return true;
|
|
62
63
|
});
|
|
64
|
+
// The ranker's last run and source health, with the priorities (the ranker runs at most hourly).
|
|
65
|
+
poll(PRIORITY_POLL_MS, async () => {
|
|
66
|
+
const next = await client.rpc(rankStatusRpc, {});
|
|
67
|
+
if (JSON.stringify(next) === JSON.stringify(rank)) return false;
|
|
68
|
+
rank = next; return true;
|
|
69
|
+
});
|
|
63
70
|
poll(15_000, async () => {
|
|
64
71
|
const next = await client.rpc(overseerStatusRpc, {});
|
|
65
72
|
if (JSON.stringify(next) === JSON.stringify(overseer)) return false;
|
|
@@ -117,6 +124,17 @@ export function createHomeExtras(client: PluginClientContext) {
|
|
|
117
124
|
setSort(next: SortMode) { if (next === sort) return; sort = next; storage.set(SORT_KEY, next); emit(); },
|
|
118
125
|
priorities: () => priorities,
|
|
119
126
|
usage: () => usage,
|
|
127
|
+
/** The ranker: on or off, its last run and which sources it could read. */
|
|
128
|
+
rank: () => rank,
|
|
129
|
+
/** "Re-rank now": runs the ranker, then refreshes priorities and status. */
|
|
130
|
+
async rankNow() {
|
|
131
|
+
rank = rank ? { ...rank, running: true } : rank; emit();
|
|
132
|
+
try { return await client.rpc(rankNowRpc, { force: true }); }
|
|
133
|
+
finally {
|
|
134
|
+
const [p, st] = await Promise.all([client.rpc(prioritiesRpc, {}).catch(() => null), client.rpc(rankStatusRpc, {}).catch(() => null)]);
|
|
135
|
+
if (p) priorities = p.items; if (st) rank = st; emit();
|
|
136
|
+
}
|
|
137
|
+
},
|
|
120
138
|
/** The Overseer: off, not started yet, or its agent and workspace. */
|
|
121
139
|
overseer: () => overseer,
|
|
122
140
|
async startOverseer() { overseer = await client.rpc(overseerStartRpc, {}); emit(); return overseer; },
|
package/client/home.tsx
CHANGED
|
@@ -60,6 +60,7 @@ export function FollowHome(props: PluginScreenProps & { deps: HomeDeps }) {
|
|
|
60
60
|
const tracked = useSyncExternalStore(deps.sources.live.subscribe, deps.sources.live.version, deps.sources.live.version);
|
|
61
61
|
const rows = useInbox(inbox, () => inbox.rows());
|
|
62
62
|
const pane = useMemo(() => briefPane({ model, rows, tracked: deps.sources.live.all(), now: Date.now() }), [model, rows, tracked, deps.sources.live]);
|
|
63
|
+
const rank = useSyncExternalStore(deps.sources.extras.subscribe, deps.sources.extras.rank, deps.sources.extras.rank);
|
|
63
64
|
const overseerStatus = useSyncExternalStore(deps.sources.extras.subscribe, deps.sources.extras.overseer, deps.sources.extras.overseer);
|
|
64
65
|
const overseerInbox = useInbox(inbox, () => inbox.overseer());
|
|
65
66
|
const overseer = overseerRowState(overseerStatus, overseerInbox);
|
|
@@ -112,7 +113,7 @@ export function FollowHome(props: PluginScreenProps & { deps: HomeDeps }) {
|
|
|
112
113
|
strip and meters below if this row sits above them. */}
|
|
113
114
|
<View style={{ zIndex: 2, flexDirection: "row", alignItems: "center", gap: 6, paddingHorizontal: compact ? 12 : 16 }}>
|
|
114
115
|
<SearchField theme={theme} omnibox={omnibox} dense={compact} onEnter={item => void pick(item)} />
|
|
115
|
-
<SortMenu theme={theme} mode={model.sort} onChange={deps.sources.extras.setSort} rankedAt={model.rankedAt} touch={compact} />
|
|
116
|
+
<SortMenu theme={theme} mode={model.sort} onChange={deps.sources.extras.setSort} rankedAt={model.rankedAt} touch={compact} rank={rank} onRerank={deps.sources.extras.rankNow} />
|
|
116
117
|
</View>
|
|
117
118
|
{!omnibox.results && <StatusStrip theme={theme} model={model} filter={filter} onFilter={setFilter} touch={compact} dense={compact} />}
|
|
118
119
|
{!omnibox.results && <UsageMeters theme={theme} sources={deps.sources} dense={compact} />}
|
package/index.server.ts
CHANGED
|
@@ -52,6 +52,7 @@ import { OVERSEER_LABEL } from "./shared/overseer";
|
|
|
52
52
|
import { withDaemon } from "./server/daemon";
|
|
53
53
|
import { inboxAnswer } from "./server/etag";
|
|
54
54
|
import { AiJobs } from "./server/ai-jobs";
|
|
55
|
+
import { liveRankSources, planningUrl, Ranker, RANKER_ROLE_DEFAULT } from "./server/ranker";
|
|
55
56
|
import { AboutService, AboutStore, liveSources, rootHistory, type AboutContext } from "./server/about";
|
|
56
57
|
import { readTranscript } from "./server/transcript";
|
|
57
58
|
import { AgentSettingsStore, ProviderCatalog, type CatalogSource } from "./server/agent-settings";
|
|
@@ -119,6 +120,7 @@ export default function contribute(server: PluginServerContext) {
|
|
|
119
120
|
const needsYouPath = (agentId: string) => join(directory, "hook-state", `needs-you-${agentId}.json`);
|
|
120
121
|
const trackedMain = async (agentId: string) => (await store.snapshot()).workspaces.find(w => w.enable_tracking && !w.archived && w.mainAgentId === agentId) ?? null;
|
|
121
122
|
let overseer: Overseer | null = null;
|
|
123
|
+
let ranker: Ranker | null = null;
|
|
122
124
|
const inbox: Inbox = new Inbox(directory, {
|
|
123
125
|
enabled: inboxSettings,
|
|
124
126
|
overseer: async () => (await overseer?.state())?.agentId ?? null,
|
|
@@ -177,6 +179,8 @@ export default function contribute(server: PluginServerContext) {
|
|
|
177
179
|
catch (error) { inboxError = error instanceof Error ? error.message : "The Needs-you inbox couldn't update."; }
|
|
178
180
|
// The Overseer's digest for its next turn, and its recreation if it was archived. Never blocks the inbox.
|
|
179
181
|
if (overseer) { await overseer.writeDigest().catch(() => undefined); if (api) await overseer.ensure(api as unknown as OverseerPaseo, { periodic: true }).catch(() => undefined); }
|
|
182
|
+
// The ranker's scheduled run (window, cadence, cap and the governor are its own checks). Never awaited: it can take minutes.
|
|
183
|
+
if (ranker) void ranker.tick().catch(() => undefined);
|
|
180
184
|
if (!stopped) inboxTimer = setTimeout(() => void inboxLoop(), 15_000);
|
|
181
185
|
};
|
|
182
186
|
// Hooks run in the background; an inbox failure never blocks the rest of Follow-up.
|
|
@@ -561,7 +565,8 @@ export default function contribute(server: PluginServerContext) {
|
|
|
561
565
|
overseer = new Overseer({ directory, store, inbox, priorities: priorityStore, workspaces: paseoWorkspaces, enabled: overseerOn, paseoHome, tight: async () => !governor.allowsBackground(),
|
|
562
566
|
windowMs: async () => activeWindowMs(await store.snapshot()), agent: () => agentSettings.role("overseer"),
|
|
563
567
|
// Harness override only (isolated test daemons): "provider/model" wins over Settings → Agents.
|
|
564
|
-
provider: process.env.FOLLOW_UP_OVERSEER_PROVIDER || undefined
|
|
568
|
+
provider: process.env.FOLLOW_UP_OVERSEER_PROVIDER || undefined,
|
|
569
|
+
rerank: async () => { if (!ranker) throw new Error("The ranker isn't ready yet."); return rankSummary(await ranker.run({ trigger: "overseer" })); } });
|
|
565
570
|
const overseerStatus = async () => {
|
|
566
571
|
const [s, info] = await Promise.all([overseer!.state(), overseer!.agentInfo()]);
|
|
567
572
|
// Labels from the last catalog Settings read (never fetched here: this is polled), so both surfaces say the same.
|
|
@@ -601,6 +606,20 @@ export default function contribute(server: PluginServerContext) {
|
|
|
601
606
|
});
|
|
602
607
|
// "What's this about?": small model jobs through the shared runner, cached per workspace in about.json.
|
|
603
608
|
const aiJobs = new AiJobs({ concurrency: 1, logPath: join(directory, "ai-jobs.jsonl") });
|
|
609
|
+
// The ranker behind Home's Priority sort (1.4.0-beta.0). Its provider, model and limits come from the ranker role
|
|
610
|
+
// in Settings → Agents. Inputs are read-only: Follow-up's state, mcpproxy, gh, the plan.
|
|
611
|
+
const rankerOn = async () => (await inboxSettings()).enable_ranker !== false;
|
|
612
|
+
const rankerRole = async () => {
|
|
613
|
+
const r = await agentSettings.role("ranker");
|
|
614
|
+
return { provider: r.provider, model: r.model, thinking: r.thinking, dailyCap: r.dailyCap ?? RANKER_ROLE_DEFAULT.dailyCap, maxPromptChars: r.maxPromptChars ?? RANKER_ROLE_DEFAULT.maxPromptChars, cadenceMinutes: r.cadenceMinutes ?? RANKER_ROLE_DEFAULT.cadenceMinutes };
|
|
615
|
+
};
|
|
616
|
+
ranker = new Ranker({ directory, jobs: aiJobs, priorities: priorityStore, role: rankerRole, enabled: rankerOn, tight: async () => !governor.allowsBackground(),
|
|
617
|
+
workstreams: () => overseer!.workstreams(), planningUrl: () => planningUrl(process.env.FOLLOW_UP_PLAN_URL),
|
|
618
|
+
sources: liveRankSources(aiJobs, { model: async () => { const r = await rankerRole(); return r.provider === "claude" ? r.model : null; } }) });
|
|
619
|
+
const rankSummary = (r: Awaited<ReturnType<Ranker["run"]>>) => ({ ok: r.ok, skipped: r.skipped, error: r.error, healthLine: r.healthLine, costUsd: r.costUsd, durationMs: r.durationMs,
|
|
620
|
+
top: r.priorities.slice(0, 10).map(p => ({ title: p.title, score: p.score, reason: p.reason })), notStarted: r.notStarted.length });
|
|
621
|
+
handle(rpc.rankStatusRpc, async () => { await requireReady(); return ranker!.status(); });
|
|
622
|
+
handle(rpc.rankNowRpc, async ({ force }) => { await requireReady(); return rankSummary(await ranker!.run({ trigger: "manual", force: !!force })); });
|
|
604
623
|
// Agent metadata only (agents.list never loads an agent), cached for a minute and shared by every overview.
|
|
605
624
|
type AgentMeta = { id: string; title: string | null; parent: string | null; snapshot: LoadSignals };
|
|
606
625
|
let agentMeta: { at: number; rows: Map<string, AgentMeta> } | null = null;
|
|
@@ -838,7 +857,7 @@ export default function contribute(server: PluginServerContext) {
|
|
|
838
857
|
server.on("workspace.archived", async event => { await ready; if (!loadError && !stopped) await store.mutate(state => { const w = state.workspaces.find(w => w.id === event.workspace.id); if (w) w.archived = true; }); }),
|
|
839
858
|
];
|
|
840
859
|
return async () => {
|
|
841
|
-
stopped = true; governor.stop(); if (timer) clearTimeout(timer); if (aboutTimer) clearTimeout(aboutTimer); aiJobs.stop(); if (inboxTimer) clearTimeout(inboxTimer); inbox.stop(); if (hookTimer) clearInterval(hookTimer); removers.forEach(remove => remove());
|
|
860
|
+
stopped = true; governor.stop(); if (timer) clearTimeout(timer); if (aboutTimer) clearTimeout(aboutTimer); aiJobs.stop(); ranker = null; if (inboxTimer) clearTimeout(inboxTimer); inbox.stop(); if (hookTimer) clearInterval(hookTimer); removers.forEach(remove => remove());
|
|
842
861
|
await ready; if (hooksStarted) await agentHooks.stop().catch(() => {});
|
|
843
862
|
await actions.close(); await closeConnections(); await engine.stop(); await ready; await store.flush().catch(() => undefined); await unlock?.();
|
|
844
863
|
};
|
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.
|
|
4
|
+
"version": "1.4.0-beta.7",
|
|
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": [
|
package/server/ai-jobs.ts
CHANGED
|
@@ -34,6 +34,8 @@ export type JobSpec<T> = {
|
|
|
34
34
|
maxPromptChars?: number;
|
|
35
35
|
/** The reply cap in characters; a longer reply is refused. */
|
|
36
36
|
maxOutputChars?: number;
|
|
37
|
+
/** This job's own runner (the ranker's plan reader needs the Artifact tool); it still takes a queue slot. */
|
|
38
|
+
runner?: Runner;
|
|
37
39
|
};
|
|
38
40
|
export type JobResult<T> =
|
|
39
41
|
| { ok: true; value: T; costUsd: number | null; durationMs: number }
|
|
@@ -68,7 +70,8 @@ export class AiJobs {
|
|
|
68
70
|
if (spec.prompt.length > (spec.maxPromptChars ?? 60_000)) return done({ ok: false, reason: "too-large", error: `The prompt is ${spec.prompt.length} characters; the cap is ${spec.maxPromptChars ?? 60_000}.`, costUsd: null, durationMs: 0 });
|
|
69
71
|
if (this.stopped) return done({ ok: false, reason: "stopped", error: "Follow-up is stopping.", costUsd: null, durationMs: 0 });
|
|
70
72
|
const provider = spec.provider ?? "claude";
|
|
71
|
-
|
|
73
|
+
// An injected runner (tests) always wins, so a job can never reach the real CLI from a test; then the job's own.
|
|
74
|
+
const runner = this.opts.runner ?? spec.runner ?? this.opts.runners?.[provider] ?? defaultRunner(provider);
|
|
72
75
|
if (!runner) return done({ ok: false, reason: "failed", error: `${provider} can't run one-shot jobs; pick Claude or Codex in Settings → Agents.`, costUsd: null, durationMs: 0 });
|
|
73
76
|
await this.slot();
|
|
74
77
|
const controller = new AbortController(); this.controllers.add(controller);
|
|
@@ -172,25 +175,32 @@ export function defaultRunner(provider: string): Runner | null {
|
|
|
172
175
|
/** The envelope of a one-turn reply is a few KB; anything near this is runaway output. */
|
|
173
176
|
export const MAX_STDOUT = 512 * 1024;
|
|
174
177
|
|
|
178
|
+
/** A job's environment: `defaults` (Claude: no nonessential traffic), then `env`; an empty value in `env` removes that variable. */
|
|
179
|
+
export function childEnv(env: Record<string, string> = {}, defaults: Record<string, string> = { CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1" }): NodeJS.ProcessEnv {
|
|
180
|
+
const out: NodeJS.ProcessEnv = { ...process.env, ...defaults, ...env };
|
|
181
|
+
for (const [k, v] of Object.entries(env)) if (v === "") delete out[k];
|
|
182
|
+
return out;
|
|
183
|
+
}
|
|
184
|
+
|
|
175
185
|
/** Spawns `claude` with an argument array (no shell); the prompt goes on stdin. */
|
|
176
|
-
export function claudeRunner(command = "claude"): Runner {
|
|
177
|
-
return input => spawnJob(command,
|
|
186
|
+
export function claudeRunner(command = "claude", args: (input: RunInput) => string[] = claudeArgs, env: Record<string, string> = {}): Runner {
|
|
187
|
+
return input => spawnJob(command, args(input), input.prompt, parseClaudeEnvelope, input, childEnv(env));
|
|
178
188
|
}
|
|
179
189
|
|
|
180
190
|
/** Spawns `codex exec` the same way, from an empty private temp directory that is removed afterwards. */
|
|
181
191
|
export function codexRunner(command = "codex"): Runner {
|
|
182
192
|
return async input => {
|
|
183
193
|
const cwd = await mkdtemp(join(tmpdir(), "follow-up-job-"));
|
|
184
|
-
try { return await spawnJob(command, codexArgs({ ...input, cwd }), codexPrompt(input), parseCodexEvents, input, {}); }
|
|
194
|
+
try { return await spawnJob(command, codexArgs({ ...input, cwd }), codexPrompt(input), parseCodexEvents, input, childEnv({}, {})); }
|
|
185
195
|
finally { await rm(cwd, { recursive: true, force: true }).catch(() => undefined); }
|
|
186
196
|
};
|
|
187
197
|
}
|
|
188
198
|
|
|
189
|
-
function spawnJob(command: string, args: string[], stdin: string, parse: (stdout: string) => RunOutput, input: RunInput, env:
|
|
199
|
+
function spawnJob(command: string, args: string[], stdin: string, parse: (stdout: string) => RunOutput, input: RunInput, env: NodeJS.ProcessEnv): Promise<RunOutput> {
|
|
190
200
|
return new Promise((resolve, reject) => {
|
|
191
201
|
const name = basename(command);
|
|
192
202
|
// Its own process group, so a timeout kills the CLI and anything it started.
|
|
193
|
-
const child = spawn(command, args, { cwd: tmpdir(), detached: true, stdio: ["pipe", "pipe", "pipe"], env
|
|
203
|
+
const child = spawn(command, args, { cwd: tmpdir(), detached: true, stdio: ["pipe", "pipe", "pipe"], env });
|
|
194
204
|
let stdout = "", stderr = "", capped = false;
|
|
195
205
|
const kill = () => { try { if (child.pid) process.kill(-child.pid, "SIGKILL"); } catch { child.kill("SIGKILL"); } };
|
|
196
206
|
input.signal.addEventListener("abort", kill, { once: true });
|
package/server/mcp-source.ts
CHANGED
|
@@ -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>), 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 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];\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];\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\"]);\nconst destructiveTools = new Set([\"merge\"]);\nconst actionInstruction = \"Follow-up's action tools let you do what the developer can click, across every tracked workspace: list_prs, inbox_list, workspace_about and agent_settings to read; add_reviewers, merge, enable/disable_merge_when_ready, send_repairs, set_auto_send, clear_hold, retry_batch, track, set_priorities, and sign_off/snooze/set_finish_flags for other agents. Use them 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). Planned tools return a dry run; run it with confirm=true and its planId. Never sign yourself off.\";\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}\nconst schemas = list => list.map(([name, description, , properties, required]) => ({ name, description, 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) scopeCache = { mtimeMs, agents: JSON.parse(await readFile(path, \"utf8\")).agents ?? {} };\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}\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) })), 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 batchInstructions = \"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\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 };\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 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) + \" 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) };\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>), 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 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];\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\"]);\nconst destructiveTools = new Set([\"merge\"]);\nconst actionInstruction = \"Follow-up's action tools let you do what the developer can click, across every tracked workspace: list_prs, inbox_list, workspace_about and agent_settings to read; add_reviewers, merge, enable/disable_merge_when_ready, send_repairs, set_auto_send, clear_hold, retry_batch, track, set_priorities, and sign_off/snooze/set_finish_flags for other agents. Use them 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). Planned tools return a dry run; run it with confirm=true and its planId. Never sign yourself off.\";\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}\nconst schemas = list => list.map(([name, description, , properties, required]) => ({ name, description, 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) scopeCache = { mtimeMs, agents: JSON.parse(await readFile(path, \"utf8\")).agents ?? {} };\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}\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) })), 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 batchInstructions = \"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\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 };\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 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) + \" 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) };\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
|
@@ -60,6 +60,7 @@ const overseerTools = [
|
|
|
60
60
|
["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"]],
|
|
61
61
|
["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"]],
|
|
62
62
|
["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 }, []],
|
|
63
|
+
["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", {}, []],
|
|
63
64
|
];
|
|
64
65
|
const overseerNames = new Set(overseerTools.map(t => t[0]));
|
|
65
66
|
const 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.";
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// Generated by scripts/build.mjs from server/overseer-prompt.md.
|
|
2
|
-
export const overseerPrompt = "You are the Overseer: the developer's (Tom's) single point of contact for all of his Paseo workspaces and agents. Follow-up runs you. You route work; you don't do it.\n\nEvery turn starts with a fresh \"Follow-up digest\" in your context: what changed since your last turn and what needs Tom. Trust it over memory. For more, call `workstreams` (paged, filterable) and `agent_digest(agentId)`; `workspace_about` when it is available.\n\nRules:\n1. Route, don't do the work. Never edit code, run builds, open PRs or review diffs yourself. Find the agent that owns the work and hand it over.\n2. Find the right agent. Call `route_candidates` with Tom's ask (it scores by Linear key, PR number, branch, workspace name, open asks and recent activity), then check the top ones with the digest or `agent_digest`.\n - Confident (one clear owner): `send_to_agent` with Tom's words. Set `reply_to_ask` only when Tom is answering that agent's open ask. Then tell Tom where it went in one line: \"Sent to <workspace> (<why>).\"\n - Not sure: don't guess. Call `needs_you` with kind=decision: the top 2–3 candidates as options (workspace name and why) plus \"New workspace\", and recommend one. Then stop.\n3. New workspaces only when Tom said so or picked \"New workspace\". Call `start_workspace` (dry run), then confirm it. Name it from the task (Linear key first). It branches off main with the default model.\n4. Asks across many workspaces (\"the PRs look good, assign reviewers on all\"): use the action tools (`list_prs`, `add_reviewers`, `sign_off`…). They return a dry run first; show Tom the plan in one or two lines and confirm only after he agrees, unless his ask was already explicit and complete.\n5. Never merge, approve, close or archive anything, and never post to people (Slack, email, Linear, GitHub comments). Those stay Tom's. If he asks, tell him the agent that should do it or that it's his click.\n6. Status questions (\"what's going on with SCIM?\", \"what needs me?\"): answer from the digest and the tools. Be specific: workspace, state, what it waits for.\n7. Keep replies to Tom brief: one to three lines, no headers, no recap of the digest, and don't repeat his answer back to him. Name workspaces as Home shows them. Talk to Tom as \"you\".\n8. Subagents: if you ever start one, start it in bypass permission mode (Claude `--mode bypassPermissions`, Codex `--mode full-access`) and tell it to do the same.\n";
|
|
2
|
+
export const overseerPrompt = "You are the Overseer: the developer's (Tom's) single point of contact for all of his Paseo workspaces and agents. Follow-up runs you. You route work; you don't do it.\n\nEvery turn starts with a fresh \"Follow-up digest\" in your context: what changed since your last turn and what needs Tom. Trust it over memory. For more, call `workstreams` (paged, filterable) and `agent_digest(agentId)`; `workspace_about` when it is available.\n\nRules:\n1. Route, don't do the work. Never edit code, run builds, open PRs or review diffs yourself. Find the agent that owns the work and hand it over.\n2. Find the right agent. Call `route_candidates` with Tom's ask (it scores by Linear key, PR number, branch, workspace name, open asks and recent activity), then check the top ones with the digest or `agent_digest`.\n - Confident (one clear owner): `send_to_agent` with Tom's words. Set `reply_to_ask` only when Tom is answering that agent's open ask. Then tell Tom where it went in one line: \"Sent to <workspace> (<why>).\"\n - Not sure: don't guess. Call `needs_you` with kind=decision: the top 2–3 candidates as options (workspace name and why) plus \"New workspace\", and recommend one. Then stop.\n3. New workspaces only when Tom said so or picked \"New workspace\". Call `start_workspace` (dry run), then confirm it. Name it from the task (Linear key first). It branches off main with the default model.\n4. Asks across many workspaces (\"the PRs look good, assign reviewers on all\"): use the action tools (`list_prs`, `add_reviewers`, `sign_off`…). They return a dry run first; show Tom the plan in one or two lines and confirm only after he agrees, unless his ask was already explicit and complete.\n5. Never merge, approve, close or archive anything, and never post to people (Slack, email, Linear, GitHub comments). Those stay Tom's. If he asks, tell him the agent that should do it or that it's his click.\n6. Status questions (\"what's going on with SCIM?\", \"what needs me?\"): answer from the digest and the tools. Be specific: workspace, state, what it waits for.\n - \"What should I work on first?\" or \"re-rank\": call `rerank`. It refreshes Home's Priority sort from Linear, Slack, review requests and the weekly plan, and returns the top 10 with reasons. Answer with the first two or three.\n7. Keep replies to Tom brief: one to three lines, no headers, no recap of the digest, and don't repeat his answer back to him. Name workspaces as Home shows them. Talk to Tom as \"you\".\n8. Subagents: if you ever start one, start it in bypass permission mode (Claude `--mode bypassPermissions`, Codex `--mode full-access`) and tell it to do the same.\n";
|
|
@@ -11,5 +11,6 @@ Rules:
|
|
|
11
11
|
4. Asks across many workspaces ("the PRs look good, assign reviewers on all"): use the action tools (`list_prs`, `add_reviewers`, `sign_off`…). They return a dry run first; show Tom the plan in one or two lines and confirm only after he agrees, unless his ask was already explicit and complete.
|
|
12
12
|
5. Never merge, approve, close or archive anything, and never post to people (Slack, email, Linear, GitHub comments). Those stay Tom's. If he asks, tell him the agent that should do it or that it's his click.
|
|
13
13
|
6. Status questions ("what's going on with SCIM?", "what needs me?"): answer from the digest and the tools. Be specific: workspace, state, what it waits for.
|
|
14
|
+
- "What should I work on first?" or "re-rank": call `rerank`. It refreshes Home's Priority sort from Linear, Slack, review requests and the weekly plan, and returns the top 10 with reasons. Answer with the first two or three.
|
|
14
15
|
7. Keep replies to Tom brief: one to three lines, no headers, no recap of the digest, and don't repeat his answer back to him. Name workspaces as Home shows them. Talk to Tom as "you".
|
|
15
16
|
8. Subagents: if you ever start one, start it in bypass permission mode (Claude `--mode bypassPermissions`, Codex `--mode full-access`) and tell it to do the same.
|
package/server/overseer.ts
CHANGED
|
@@ -56,10 +56,12 @@ export type OverseerDeps = {
|
|
|
56
56
|
agent?: () => Promise<OverseerAgentSetting>;
|
|
57
57
|
/** Harness override ("provider/model", from FOLLOW_UP_OVERSEER_PROVIDER): wins over the setting. */
|
|
58
58
|
provider?: string;
|
|
59
|
+
/** Re-rank Home's Priority sort now (the ranker); Tom asked the Overseer for it. */
|
|
60
|
+
rerank?: () => Promise<unknown>;
|
|
59
61
|
now?: () => number;
|
|
60
62
|
};
|
|
61
63
|
|
|
62
|
-
export const OVERSEER_TOOLS = ["workstreams", "agent_digest", "route_candidates", "send_to_agent", "start_workspace"] as const;
|
|
64
|
+
export const OVERSEER_TOOLS = ["workstreams", "agent_digest", "route_candidates", "send_to_agent", "start_workspace", "rerank"] as const;
|
|
63
65
|
export type OverseerTool = typeof OVERSEER_TOOLS[number];
|
|
64
66
|
const id = z.string().trim().min(1).max(200);
|
|
65
67
|
export const OVERSEER_INPUT: Record<OverseerTool, z.ZodType> = {
|
|
@@ -67,6 +69,7 @@ export const OVERSEER_INPUT: Record<OverseerTool, z.ZodType> = {
|
|
|
67
69
|
agent_digest: z.strictObject({ agentId: id, steps: z.number().int().min(1).max(30).optional() }),
|
|
68
70
|
route_candidates: z.strictObject({ ask: z.string().trim().min(1).max(4000) }),
|
|
69
71
|
send_to_agent: z.strictObject({ agentId: id, text: z.string().trim().min(1).max(20_000), reply_to_ask: z.boolean().optional() }),
|
|
72
|
+
rerank: z.strictObject({}),
|
|
70
73
|
start_workspace: z.strictObject({ task: z.string().trim().min(1).max(20_000).optional(), title: z.string().trim().min(1).max(80).optional(), project: id.optional(), linear_key: z.string().trim().max(30).optional(), base: z.string().trim().max(200).optional(), planId: id.optional(), confirm: z.boolean().optional() }),
|
|
71
74
|
};
|
|
72
75
|
|
|
@@ -250,6 +253,7 @@ export class Overseer {
|
|
|
250
253
|
}
|
|
251
254
|
case "send_to_agent": return this.send(paseo, s, args as { agentId: string; text: string; reply_to_ask?: boolean });
|
|
252
255
|
case "start_workspace": return args.confirm ? this.confirm(args.planId) : this.planWorkspace(paseo, s, args);
|
|
256
|
+
case "rerank": { if (!this.d.rerank) throw new Error("Re-ranking isn't available on this host."); return this.d.rerank(); }
|
|
253
257
|
}
|
|
254
258
|
}
|
|
255
259
|
|
|
@@ -355,7 +359,8 @@ export function handoffSummary(steps: { kind: string; text: string }[]): string
|
|
|
355
359
|
return steps.length ? steps.map(x => `- ${x.kind === "you" ? "Tom" : x.kind}: ${clip(x.text.replace(/\s+/g, " ").trim(), 240)}`).join("\n") : "(no history could be read)";
|
|
356
360
|
}
|
|
357
361
|
|
|
358
|
-
|
|
362
|
+
/** Write JSON to a temp file, then rename: readers never see half a file. */
|
|
363
|
+
export async function atomic(path: string, value: unknown) {
|
|
359
364
|
const temporary = `${path}.${randomUUID()}`;
|
|
360
365
|
await writeFile(temporary, JSON.stringify(value), { mode: 0o600 });
|
|
361
366
|
await rename(temporary, path);
|
package/server/ranker.ts
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { promisify } from "node:util";
|
|
4
|
+
import { readFile } from "node:fs/promises";
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { z } from "zod";
|
|
8
|
+
import { mkdir } from "node:fs/promises";
|
|
9
|
+
import { atomic } from "./overseer";
|
|
10
|
+
import { claudeArgs, claudeRunner, type AiJobs, type RunInput } from "./ai-jobs";
|
|
11
|
+
import { mcpproxyText } from "./about";
|
|
12
|
+
import {
|
|
13
|
+
healthLine, inRankWindow, jerusalem, stableInputs, rankPrompt, rankReplySchema, RANK_SYSTEM, rankWorkstream, toPriorities,
|
|
14
|
+
type NotStarted, type RankInputs, type RankIssue, type RankMessage, type RankPlanning, type RankReview, type RankSource, type SourceHealth,
|
|
15
|
+
} from "../shared/ranker";
|
|
16
|
+
import type { Priority } from "../shared/priorities";
|
|
17
|
+
import type { WorkstreamRow } from "../shared/overseer";
|
|
18
|
+
|
|
19
|
+
const exec = promisify(execFile);
|
|
20
|
+
|
|
21
|
+
/** The inputs' fingerprint: equal means the model would see the same material. */
|
|
22
|
+
export const inputsHash = (inputs: RankInputs) => createHash("sha256").update(stableInputs(inputs)).digest("hex").slice(0, 32);
|
|
23
|
+
|
|
24
|
+
// ---------- role ----------
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* The ranker's provider, model and limits, from the ranker role in Settings → Agents. These defaults match its
|
|
28
|
+
* ROLE_DEFAULTS.ranker and fill any limit the role leaves unset. Never a hardcoded model at the call site.
|
|
29
|
+
*/
|
|
30
|
+
export type RankerRole = { provider: string; model: string | null; thinking: string | null; dailyCap: number; maxPromptChars: number | null; cadenceMinutes: number };
|
|
31
|
+
export const RANKER_ROLE_DEFAULT: RankerRole = { provider: "claude", model: "sonnet", thinking: null, dailyCap: 24, maxPromptChars: 60_000, cadenceMinutes: 60 };
|
|
32
|
+
|
|
33
|
+
// ---------- sources ----------
|
|
34
|
+
|
|
35
|
+
export type RankSources = {
|
|
36
|
+
linear(): Promise<RankIssue[]>;
|
|
37
|
+
/** DMs and mentions since `since` (ms). */
|
|
38
|
+
slack(since: number): Promise<RankMessage[]>;
|
|
39
|
+
github(): Promise<RankReview[]>;
|
|
40
|
+
/** The CPO's plan, read once a day at most (the caller caches). Null when there's no plan to read. */
|
|
41
|
+
planning(url: string): Promise<RankPlanning | null>;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const str = (v: unknown) => typeof v === "string" && v.trim() ? v.trim() : null;
|
|
45
|
+
|
|
46
|
+
/** `linear:list_issues` (JSON `{issues: […]}`), open ones only. */
|
|
47
|
+
export function parseLinearIssues(text: string): RankIssue[] {
|
|
48
|
+
let j: unknown; try { j = JSON.parse(text); } catch { return []; }
|
|
49
|
+
const issues = (j as { issues?: unknown[] })?.issues;
|
|
50
|
+
if (!Array.isArray(issues)) return [];
|
|
51
|
+
return issues.flatMap(raw => {
|
|
52
|
+
const i = raw as Record<string, unknown>;
|
|
53
|
+
const key = str(i.id) ?? str(i.identifier); const title = str(i.title);
|
|
54
|
+
if (!key || !title || /^(completed|canceled)$/i.test(str(i.statusType) ?? "")) return [];
|
|
55
|
+
const named = (v: unknown) => typeof v === "object" && v ? str((v as { name?: unknown }).name) : str(v);
|
|
56
|
+
const priority = named(i.priority);
|
|
57
|
+
return [{ key, title, priority: priority === "No priority" ? null : priority, status: str(i.status) ?? named(i.state), due: str(i.dueDate), project: named(i.project), milestone: named(i.projectMilestone), url: str(i.url) }];
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* `slack_search_public_and_private` in concise form: "1. DM with Tom, Dana Levi - Dana Levi: text… 2026-11-09 18:12:18 IST".
|
|
63
|
+
* The developer's own messages and bots are dropped.
|
|
64
|
+
*/
|
|
65
|
+
export function parseSlackSearch(text: string, self: string | null): RankMessage[] {
|
|
66
|
+
const out: RankMessage[] = [];
|
|
67
|
+
const body = (() => { try { const j = JSON.parse(text) as { results?: string }; return typeof j.results === "string" ? j.results : text; } catch { return text; } })();
|
|
68
|
+
for (const m of body.matchAll(/(?:^|\n)\s*\d+\.\s+([\s\S]*?)(?=\n\s*\d+\.\s|\n*$)/g)) {
|
|
69
|
+
const item = m[1].replace(/\\n/g, " ").replace(/\s+/g, " ").trim();
|
|
70
|
+
const at = /(\d{4}-\d{2}-\d{2} \d{2}:\d{2}(?::\d{2})?(?: [A-Z]{2,4})?)\s*$/.exec(item);
|
|
71
|
+
const rest = at ? item.slice(0, at.index).trim() : item;
|
|
72
|
+
const head = /^(.*?),\s*([^:]{1,80}?)\s*-\s*([^:]{1,80}?):\s*([\s\S]*)$/.exec(rest);
|
|
73
|
+
const where = head ? head[1] : "Slack"; const who = head ? head[3].trim() : null; const msg = (head ? head[4] : rest).replace(/…$/, "").trim();
|
|
74
|
+
if (!msg || (who && self && who.toLowerCase() === self.toLowerCase()) || /^(GitHub|Linear|Graphite|Jira|Sentry|Datadog|Slackbot)\b/i.test(who ?? "")) continue;
|
|
75
|
+
out.push({ where, who, text: msg, at: at ? at[1] : null });
|
|
76
|
+
}
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** `gh search prs --review-requested=@me --json number,title,url,repository,author`. */
|
|
81
|
+
export function parseReviewRequests(stdout: string): RankReview[] {
|
|
82
|
+
let j: unknown; try { j = JSON.parse(stdout); } catch { return []; }
|
|
83
|
+
if (!Array.isArray(j)) return [];
|
|
84
|
+
return j.flatMap(raw => {
|
|
85
|
+
const r = raw as { number?: unknown; title?: unknown; url?: unknown; repository?: { nameWithOwner?: unknown; name?: unknown }; author?: { login?: unknown } };
|
|
86
|
+
const repo = str(r.repository?.nameWithOwner) ?? str(r.repository?.name);
|
|
87
|
+
return typeof r.number === "number" && repo && str(r.title) ? [{ repo, number: r.number, title: str(r.title)!, url: str(r.url), author: str(r.author?.login) }] : [];
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export const planReplySchema = z.object({
|
|
92
|
+
title: z.string().trim().max(200).nullable().catch(null).default(null),
|
|
93
|
+
// Items as objects, or plain lines (models sometimes flatten them); anything else is dropped, not fatal.
|
|
94
|
+
items: z.array(z.union([
|
|
95
|
+
z.object({ level: z.string().trim().min(1).max(30).catch("item"), title: z.string().trim().min(1).max(300), keys: z.array(z.string().trim().max(30)).max(10).catch([]).default([]) }),
|
|
96
|
+
z.string().trim().min(1).max(300).transform(title => ({ level: "item", title, keys: title.match(/\b[A-Z][A-Z0-9]+-\d+\b/g) ?? [] })),
|
|
97
|
+
]).nullable().catch(null)).max(120).transform(items => items.filter((i): i is { level: string; title: string; keys: string[] } => !!i).slice(0, 80)),
|
|
98
|
+
});
|
|
99
|
+
export const PLAN_SYSTEM = "You read one Claude artifact with the Artifact tool, action \"read\" only, and summarise its planning content. Never call the Artifact tool with any other action (never publish, update, delete, comment or share). Reply with one JSON object only: {\"title\": string|null, \"items\": [{\"level\": \"initiative|project|milestone|issue\", \"title\": string, \"keys\": [Linear keys like HER-123]}]}. Focus on this week; at most 60 items. Never include share keys, links or raw HTML.";
|
|
100
|
+
|
|
101
|
+
/** The plan reader: one Claude turn with only the Artifact tool, which Paseo's Claude provider enables with CLAUDE_CODE_ARTIFACT=1. */
|
|
102
|
+
export const planArgs = (input: RunInput) => {
|
|
103
|
+
const base = claudeArgs(input);
|
|
104
|
+
const tools = base.indexOf("--tools");
|
|
105
|
+
base.splice(tools, 2, "--tools", "Artifact", "--allowedTools", "Artifact");
|
|
106
|
+
base[base.indexOf("--max-turns") + 1] = "4";
|
|
107
|
+
return base;
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
/** The Artifact tool needs CLAUDE_CODE_ARTIFACT=1, and Claude Code drops it when nonessential traffic is off. */
|
|
111
|
+
export const PLAN_ENV = { CLAUDE_CODE_ARTIFACT: "1", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "" };
|
|
112
|
+
|
|
113
|
+
/** A claude.ai artifact link without a query string or fragment, so no share key travels. */
|
|
114
|
+
export function canonicalArtifactUrl(url: string | null | undefined): string | null {
|
|
115
|
+
if (!url) return null;
|
|
116
|
+
try { const u = new URL(url); if (u.hostname !== "claude.ai" || !/^\/(code\/)?artifact\/[\w-]+$/.test(u.pathname)) return null; return `https://claude.ai${u.pathname}`; } catch { return null; }
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** The plan's link: Follow-up's own setting, else the one the morning-brief skill already verified (link only, read-only). */
|
|
120
|
+
export async function planningUrl(setting: string | null | undefined, registry = join(homedir(), ".codex/skills/morning-brief/references/sources.json")): Promise<string | null> {
|
|
121
|
+
const own = canonicalArtifactUrl(setting);
|
|
122
|
+
if (own) return own;
|
|
123
|
+
try {
|
|
124
|
+
const j = JSON.parse(await readFile(registry, "utf8")) as { sources?: { reader?: string; url?: string }[] };
|
|
125
|
+
return canonicalArtifactUrl(j.sources?.find(s => s.reader === "claude_artifact")?.url);
|
|
126
|
+
} catch { return null; }
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
type Run = (command: string, args: string[], timeoutMs: number) => Promise<string>;
|
|
130
|
+
/** The developer's Slack user id, as the Slack tool describes it ("Current logged in user's user_id is U…"). */
|
|
131
|
+
export function slackUserFrom(toolsList: string): string | null { return /user_id is (U[A-Z0-9]{6,})/.exec(toolsList)?.[1] ?? null; }
|
|
132
|
+
const runFile: Run = async (command, args, timeout) => (await exec(command, args, { timeout, maxBuffer: 4 * 1024 * 1024 })).stdout;
|
|
133
|
+
|
|
134
|
+
/** The live sources: read-only mcpproxy and gh calls, and one Artifact read for the plan. */
|
|
135
|
+
export function liveRankSources(jobs: AiJobs, opts: { run?: Run; slackSelf?: string | null; slackUser?: string | null; model?: () => Promise<string | null> } = {}): RankSources {
|
|
136
|
+
const run = opts.run ?? runFile;
|
|
137
|
+
let slackUser: Promise<string | null> | null = opts.slackUser !== undefined ? Promise.resolve(opts.slackUser) : null;
|
|
138
|
+
const me = () => slackUser ??= run("mcpproxy", ["tools", "list", "--server=slack-user", "-o", "json", "--log-level=error"], 30_000).then(slackUserFrom).catch(() => { slackUser = null; return null; });
|
|
139
|
+
const call = async (tool: string, args: unknown) => mcpproxyText(await run("mcpproxy", ["call", "tool-read", `--tool-name=${tool}`, `--json_args=${JSON.stringify(args)}`, "--reason=Follow-up: rank today's workstreams", "--log-level=error", "-o", "json"], 60_000));
|
|
140
|
+
return {
|
|
141
|
+
async linear() {
|
|
142
|
+
return parseLinearIssues(await call("linear:list_issues", { assignee: "me", limit: 60, orderBy: "updatedAt", fields: ["id", "title", "priority", "dueDate", "status", "statusType", "project", "projectMilestone", "url"] }));
|
|
143
|
+
},
|
|
144
|
+
async slack(since) {
|
|
145
|
+
const after = new Date(since).toISOString().slice(0, 10);
|
|
146
|
+
const base = { limit: 20, response_format: "concise", sort: "timestamp", include_context: false, natural_language_query: "" };
|
|
147
|
+
const dms = parseSlackSearch(await call("slack-user:slack_search_public_and_private", { ...base, filters: `is:dm after:${after}` }), opts.slackSelf ?? null);
|
|
148
|
+
const user = await me();
|
|
149
|
+
const mentions = user ? parseSlackSearch(await call("slack-user:slack_search_public_and_private", { ...base, keywords: [`<@${user}>`], filters: `after:${after}` }), opts.slackSelf ?? null) : [];
|
|
150
|
+
const seen = new Set<string>();
|
|
151
|
+
return [...mentions, ...dms].filter(m => { const k = `${m.who}|${m.text}`; if (seen.has(k)) return false; seen.add(k); return true; });
|
|
152
|
+
},
|
|
153
|
+
async github() {
|
|
154
|
+
return parseReviewRequests(await run("gh", ["search", "prs", "--review-requested=@me", "--state=open", "--limit=30", "--json", "number,title,url,repository,author"], 30_000));
|
|
155
|
+
},
|
|
156
|
+
async planning(url) {
|
|
157
|
+
const model = (await opts.model?.()) ?? "sonnet";
|
|
158
|
+
const r = await jobs.run({ name: "rank-plan", prompt: `Read this artifact with the Artifact tool (action "read"): ${url}\nThen reply with the JSON object.`, system: PLAN_SYSTEM, schema: planReplySchema, model,
|
|
159
|
+
// Always Claude: the Artifact tool is Claude Code's.
|
|
160
|
+
provider: "claude", runner: claudeRunner("claude", planArgs, PLAN_ENV), timeoutMs: 180_000, maxOutputChars: 20_000 });
|
|
161
|
+
if (!r.ok) throw new Error(r.error);
|
|
162
|
+
return { title: r.value.title, url, items: r.value.items.map(i => ({ level: i.level, title: i.title, keys: i.keys.filter(k => /^[A-Z][A-Z0-9]+-\d+$/.test(k)) })) };
|
|
163
|
+
},
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// ---------- state ----------
|
|
168
|
+
|
|
169
|
+
const healthSchema = z.enum(["ok", "failed", "off"]);
|
|
170
|
+
export const rankerStateSchema = z.object({
|
|
171
|
+
version: z.literal(1),
|
|
172
|
+
lastHash: z.string().nullable(), lastRunAt: z.string().nullable(), lastModelAt: z.string().nullable(),
|
|
173
|
+
day: z.string().nullable(), runsToday: z.number().int(),
|
|
174
|
+
health: z.record(z.string(), healthSchema), notStarted: z.array(z.object({ key: z.string(), title: z.string(), url: z.string().nullable(), reason: z.string() })),
|
|
175
|
+
last: z.object({ ok: z.boolean(), trigger: z.string(), costUsd: z.number().nullable(), durationMs: z.number(), skipped: z.string().nullable(), error: z.string().nullable() }).nullable(),
|
|
176
|
+
slackSince: z.number().nullable(),
|
|
177
|
+
planning: z.object({ url: z.string(), at: z.string(), value: z.object({ title: z.string().nullable(), url: z.string().nullable(), items: z.array(z.object({ level: z.string(), title: z.string(), keys: z.array(z.string()) })) }) }).nullable(),
|
|
178
|
+
});
|
|
179
|
+
export type RankerState = z.infer<typeof rankerStateSchema>;
|
|
180
|
+
const EMPTY: RankerState = { version: 1, lastHash: null, lastRunAt: null, lastModelAt: null, day: null, runsToday: 0, health: {}, notStarted: [], last: null, slackSince: null, planning: null };
|
|
181
|
+
|
|
182
|
+
export type RankTrigger = "schedule" | "manual" | "overseer";
|
|
183
|
+
export type RankResult = {
|
|
184
|
+
ok: boolean; trigger: RankTrigger; dryRun: boolean;
|
|
185
|
+
/** Why the model wasn't called: nothing changed, the daily cap, memory, a run already going, off. */
|
|
186
|
+
skipped: "same" | "cap" | "tight" | "busy" | "off" | "sources" | null;
|
|
187
|
+
priorities: (Priority & { title: string })[]; notStarted: NotStarted[]; health: Partial<Record<RankSource, SourceHealth>>; healthLine: string;
|
|
188
|
+
costUsd: number | null; durationMs: number; error: string | null; dropped: string[];
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
export type RankerDeps = {
|
|
192
|
+
directory: string;
|
|
193
|
+
jobs: AiJobs;
|
|
194
|
+
sources: RankSources;
|
|
195
|
+
workstreams(): Promise<WorkstreamRow[]>;
|
|
196
|
+
priorities: { read(): Promise<Priority[]>; write(batch: Priority[], replace: boolean): Promise<Priority[]> };
|
|
197
|
+
role(): Promise<RankerRole>;
|
|
198
|
+
enabled(): Promise<boolean>;
|
|
199
|
+
/** The resource governor: background runs wait while this is true. Manual runs still go. */
|
|
200
|
+
tight?: () => Promise<boolean>;
|
|
201
|
+
planningUrl?: () => Promise<string | null>;
|
|
202
|
+
now?: () => number;
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
const SLACK_WINDOW_MS = 48 * 3_600_000;
|
|
206
|
+
const PLAN_EVERY_MS = 24 * 3_600_000;
|
|
207
|
+
/** Unchanged inputs keep the last ranking; it is re-stamped before Home's 6-hour freshness runs out. */
|
|
208
|
+
const RESTAMP_MS = 4 * 3_600_000;
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* One ranking run at a time. Inputs are read in sequence (concurrency 1), hashed, and the model is called only
|
|
212
|
+
* when they changed. State lives in ranker.json, priorities in priorities.json; neither touches state.json.
|
|
213
|
+
*/
|
|
214
|
+
export class Ranker {
|
|
215
|
+
private running: Promise<RankResult> | null = null;
|
|
216
|
+
constructor(private d: RankerDeps) {}
|
|
217
|
+
private now() { return this.d.now?.() ?? Date.now(); }
|
|
218
|
+
private get path() { return join(this.d.directory, "ranker.json"); }
|
|
219
|
+
async state(): Promise<RankerState> { try { return rankerStateSchema.parse(JSON.parse(await readFile(this.path, "utf8"))); } catch { return { ...EMPTY }; } }
|
|
220
|
+
|
|
221
|
+
/** The scheduled run: in the window, at the role's cadence, only with room to spare. */
|
|
222
|
+
async tick(): Promise<RankResult | null> {
|
|
223
|
+
if (this.running || !inRankWindow(this.now()) || !await this.d.enabled()) return null;
|
|
224
|
+
const [s, role] = await Promise.all([this.state(), this.d.role()]);
|
|
225
|
+
if (s.lastRunAt && this.now() - Date.parse(s.lastRunAt) < role.cadenceMinutes * 60_000) return null;
|
|
226
|
+
if (await this.d.tight?.()) return null;
|
|
227
|
+
return this.run({ trigger: "schedule" });
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
run(opts: { trigger: RankTrigger; dryRun?: boolean; force?: boolean }): Promise<RankResult> {
|
|
231
|
+
if (this.running) return this.running.then(r => ({ ...r, skipped: "busy" as const }));
|
|
232
|
+
this.running = this.once(opts).finally(() => { this.running = null; });
|
|
233
|
+
return this.running;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
private async once({ trigger, dryRun = false, force = false }: { trigger: RankTrigger; dryRun?: boolean; force?: boolean }): Promise<RankResult> {
|
|
237
|
+
const started = this.now();
|
|
238
|
+
const base = (patch: Partial<RankResult>): RankResult => ({ ok: false, trigger, dryRun, skipped: null, priorities: [], notStarted: [], health: {}, healthLine: "", costUsd: null, durationMs: this.now() - started, error: null, dropped: [], ...patch });
|
|
239
|
+
if (!await this.d.enabled()) return base({ skipped: "off" });
|
|
240
|
+
if (trigger === "schedule" && await this.d.tight?.()) return base({ skipped: "tight" });
|
|
241
|
+
const s = await this.state();
|
|
242
|
+
const role = await this.d.role();
|
|
243
|
+
const day = jerusalem(started).day;
|
|
244
|
+
const runsToday = s.day === day ? s.runsToday : 0;
|
|
245
|
+
|
|
246
|
+
// Inputs, one source at a time. A failing source is reported, never fatal.
|
|
247
|
+
const health: Partial<Record<RankSource, SourceHealth>> = {};
|
|
248
|
+
const read = async <T>(source: RankSource, fn: () => Promise<T>, fallback: T): Promise<T> => { try { const v = await fn(); health[source] = "ok"; return v; } catch { health[source] = "failed"; return fallback; } };
|
|
249
|
+
const rows = await this.d.workstreams();
|
|
250
|
+
const linear = await read("linear", () => this.d.sources.linear(), []);
|
|
251
|
+
// The whole 48-hour window every run, so equal inputs hash equal; the last read time is kept for the log.
|
|
252
|
+
const slackSince = started;
|
|
253
|
+
const slack = await read("slack", () => this.d.sources.slack(started - SLACK_WINDOW_MS), []);
|
|
254
|
+
const github = await read("github", () => this.d.sources.github(), []);
|
|
255
|
+
const url = await this.d.planningUrl?.().catch(() => null) ?? null;
|
|
256
|
+
let planning: RankPlanning | null = null; let planCache = s.planning;
|
|
257
|
+
if (!url) health.planning = "off";
|
|
258
|
+
else if (s.planning && s.planning.url === url && started - Date.parse(s.planning.at) < PLAN_EVERY_MS) { planning = s.planning.value; health.planning = "ok"; }
|
|
259
|
+
else {
|
|
260
|
+
planning = await read("planning", () => this.d.sources.planning(url), null);
|
|
261
|
+
if (planning) planCache = { url, at: new Date(started).toISOString(), value: planning };
|
|
262
|
+
else if (s.planning?.url === url) planning = s.planning.value; // keep yesterday's plan over none
|
|
263
|
+
}
|
|
264
|
+
const inputs: RankInputs = { workstreams: rows.map(rankWorkstream), linear, slack, github, planning };
|
|
265
|
+
const hash = inputsHash(inputs);
|
|
266
|
+
const save = async (patch: Partial<RankerState>) => dryRun ? undefined : (await mkdir(this.d.directory, { recursive: true, mode: 0o700 }), atomic(this.path, { ...s, day, runsToday, health, planning: planCache, slackSince, lastRunAt: new Date(started).toISOString(), ...patch }));
|
|
267
|
+
|
|
268
|
+
// Nothing from outside could be read (no logins, mcpproxy down, an isolated test daemon): a ranking would have
|
|
269
|
+
// nothing to go on, so don't spend a model call. The next tick tries again at the cadence.
|
|
270
|
+
if (!(["linear", "slack", "github", "planning"] as const).some(k => health[k] === "ok")) {
|
|
271
|
+
await save({ last: { ok: false, trigger, costUsd: null, durationMs: this.now() - started, skipped: "sources", error: "No outside source could be read." } });
|
|
272
|
+
return base({ skipped: "sources", health, healthLine: healthLine(health), error: "No outside source could be read." });
|
|
273
|
+
}
|
|
274
|
+
// Nothing changed: keep the ranking, re-stamping it before it goes stale.
|
|
275
|
+
if (!force && hash === s.lastHash) {
|
|
276
|
+
const stored = (await this.d.priorities.read()).filter(p => p.by === "ranker");
|
|
277
|
+
const newest = stored.reduce((m, p) => p.at > m ? p.at : m, "");
|
|
278
|
+
if (!dryRun && stored.length && started - Date.parse(newest) > RESTAMP_MS) await this.d.priorities.write(stored.map(p => ({ ...p, at: new Date(started).toISOString() })), false);
|
|
279
|
+
await save({ last: { ok: true, trigger, costUsd: null, durationMs: this.now() - started, skipped: "same", error: null } });
|
|
280
|
+
return base({ ok: true, skipped: "same", health, healthLine: healthLine(health), notStarted: s.notStarted, priorities: this.titled(stored, inputs) });
|
|
281
|
+
}
|
|
282
|
+
if (runsToday >= role.dailyCap && trigger !== "manual") {
|
|
283
|
+
await save({ last: { ok: false, trigger, costUsd: null, durationMs: this.now() - started, skipped: "cap", error: null } });
|
|
284
|
+
return base({ skipped: "cap", health, healthLine: healthLine(health) });
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const maxPromptChars = role.maxPromptChars ?? 60_000;
|
|
288
|
+
const prompt = rankPrompt(inputs, day, maxPromptChars);
|
|
289
|
+
const r = await this.d.jobs.run({ name: "rank", prompt, system: RANK_SYSTEM, schema: rankReplySchema, provider: role.provider, model: role.model ?? undefined, thinking: role.thinking, maxPromptChars, maxOutputChars: 40_000, timeoutMs: 240_000 });
|
|
290
|
+
const durationMs = this.now() - started;
|
|
291
|
+
if (!r.ok) {
|
|
292
|
+
await save({ runsToday: runsToday + 1, last: { ok: false, trigger, costUsd: r.costUsd, durationMs, skipped: null, error: r.error } });
|
|
293
|
+
return base({ health, healthLine: healthLine(health), costUsd: r.costUsd, error: r.error });
|
|
294
|
+
}
|
|
295
|
+
const at = new Date(this.now()).toISOString();
|
|
296
|
+
const { priorities, notStarted, dropped } = toPriorities(r.value, inputs, at);
|
|
297
|
+
// The ranker's own job: stored directly (set_priorities without the confirm step), replacing its last ranking.
|
|
298
|
+
if (!dryRun && priorities.length) await this.d.priorities.write(priorities, true);
|
|
299
|
+
await save({ lastHash: hash, lastModelAt: at, runsToday: runsToday + 1, notStarted, last: { ok: true, trigger, costUsd: r.costUsd, durationMs, skipped: null, error: null } });
|
|
300
|
+
return base({ ok: true, priorities: this.titled(priorities, inputs), notStarted, health, healthLine: healthLine(health), costUsd: r.costUsd, durationMs, dropped });
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
private titled(items: Priority[], inputs: RankInputs) {
|
|
304
|
+
const by = new Map(inputs.workstreams.map(w => [w.id, w.title]));
|
|
305
|
+
return items.map(p => ({ ...p, title: by.get(p.workspaceId) ?? p.workspaceId }));
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** For Home's sort header: the last run and what it could read. */
|
|
309
|
+
async status(): Promise<{ enabled: boolean; running: boolean; lastRunAt: string | null; healthLine: string; error: string | null; costUsd: number | null; notStarted: number }> {
|
|
310
|
+
const s = await this.state();
|
|
311
|
+
return { enabled: await this.d.enabled(), running: !!this.running, lastRunAt: s.lastRunAt, healthLine: healthLine(s.health as Partial<Record<RankSource, SourceHealth>>), error: s.last?.error ?? null, costUsd: s.last?.costUsd ?? null, notStarted: s.notStarted.length };
|
|
312
|
+
}
|
|
313
|
+
}
|
package/shared/contracts.ts
CHANGED
|
@@ -148,6 +148,10 @@ export const overseerStatusSchema = z.object({ enabled: z.boolean(), agentId: z.
|
|
|
148
148
|
export const overseerStatusRpc = defineRpc({ name: "follow.overseer-status", input: z.object({}), output: overseerStatusSchema });
|
|
149
149
|
export const overseerStartRpc = defineRpc({ name: "follow.overseer-start", input: z.object({}), output: overseerStatusSchema });
|
|
150
150
|
export const overseerAskRpc = defineRpc({ name: "follow.overseer-ask", input: z.strictObject({ text: z.string().trim().min(1).max(2000) }), output: overseerStatusSchema });
|
|
151
|
+
export const rankStatusSchema = z.object({ enabled: z.boolean(), running: z.boolean(), lastRunAt: z.string().nullable(), healthLine: z.string(), error: z.string().nullable(), costUsd: z.number().nullable(), notStarted: z.number().int() });
|
|
152
|
+
export const rankStatusRpc = defineRpc({ name: "follow.rank-status", input: z.object({}), output: rankStatusSchema });
|
|
153
|
+
export const rankNowRpc = defineRpc({ name: "follow.rank-now", input: z.strictObject({ force: z.boolean().optional() }), output: z.object({ ok: z.boolean(), skipped: z.string().nullable(), error: z.string().nullable(), healthLine: z.string(), costUsd: z.number().nullable(), durationMs: z.number(),
|
|
154
|
+
top: z.array(z.object({ title: z.string(), score: z.number(), reason: z.string() })), notStarted: z.number().int() }) });
|
|
151
155
|
export const overseerActRpc = defineRpc({ name: "follow.overseer-act", input: z.strictObject({ agentId: idSchema, tool: z.string().max(60), args: z.record(z.string(), z.unknown()).default({}) }), output: z.unknown() });
|
|
152
156
|
export const overseerRestartRpc = defineRpc({ name: "follow.overseer-restart", input: z.object({}), output: overseerStatusSchema });
|
|
153
157
|
/** Settings → Agents. `catalog` asks for Paseo's provider list (cached ten minutes; `fresh` re-reads it). */
|
package/shared/display.ts
CHANGED
|
@@ -16,7 +16,9 @@ export const displayPreferences = defineSettings({
|
|
|
16
16
|
// R2: Claude Code root agents that end a turn without needs_you are asked once to state what you need.
|
|
17
17
|
enable_brief_nudge: z.boolean().default(true),
|
|
18
18
|
// 1.4.0-beta.0: the Overseer row on Home and its per-turn digest. Off never archives an existing Overseer.
|
|
19
|
-
enable_overseer: z.boolean().default(true)
|
|
19
|
+
enable_overseer: z.boolean().default(true),
|
|
20
|
+
// 1.4.0-beta.0: the ranker behind Home's Priority sort (Linear, Slack, GitHub reviews, the CPO's plan).
|
|
21
|
+
enable_ranker: z.boolean().default(true) }),
|
|
20
22
|
});
|
|
21
23
|
|
|
22
24
|
export const displayRpc = settingsRpc(displayPreferences.id);
|
package/shared/ranker.ts
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { PRIORITY_SOURCES, prioritySourceSchema, type Priority } from "./priorities";
|
|
3
|
+
import type { WorkstreamRow } from "./overseer";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The ranker (1.4.0-beta.0, slice 3): one bounded model job that orders Tom's workstreams by what matters today and
|
|
7
|
+
* says why in one line that names its source. Follow-up collects every input itself, read-only and without model
|
|
8
|
+
* tools (Follow-up's own state, Linear, Slack, GitHub review requests and the CPO's weekly plan), hashes them, and
|
|
9
|
+
* calls the model only when they changed. The result goes to the priorities store Home's Priority sort already reads.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export const RANK_SOURCES = ["linear", "slack", "github", "planning"] as const;
|
|
13
|
+
export type RankSource = typeof RANK_SOURCES[number];
|
|
14
|
+
export const RANK_SOURCE_LABEL: Record<RankSource, string> = { linear: "Linear", slack: "Slack", github: "GitHub", planning: "Plan" };
|
|
15
|
+
export type SourceHealth = "ok" | "failed" | "off";
|
|
16
|
+
|
|
17
|
+
export type RankWorkstream = { id: string; title: string; branch: string | null; group: string; ask: string | null; prs: string[]; keys: string[]; dormant: boolean };
|
|
18
|
+
export type RankIssue = { key: string; title: string; priority: string | null; status: string | null; due: string | null; project: string | null; milestone: string | null; url: string | null };
|
|
19
|
+
export type RankMessage = { where: string; who: string | null; text: string; at: string | null };
|
|
20
|
+
export type RankReview = { repo: string; number: number; title: string; url: string | null; author: string | null };
|
|
21
|
+
export type RankPlanItem = { level: string; title: string; keys: string[] };
|
|
22
|
+
export type RankPlanning = { title: string | null; url: string | null; items: RankPlanItem[] };
|
|
23
|
+
export type RankInputs = { workstreams: RankWorkstream[]; linear: RankIssue[]; slack: RankMessage[]; github: RankReview[]; planning: RankPlanning | null };
|
|
24
|
+
|
|
25
|
+
export const RANK_LIMITS = { workstreams: 150, issues: 60, messages: 40, reviews: 30, planItems: 60, textChars: 220, titleChars: 120 };
|
|
26
|
+
const clip = (s: string | null | undefined, n: number) => { const t = (s ?? "").replace(/\s+/g, " ").trim(); return t.length > n ? `${t.slice(0, n - 1)}…` : t; };
|
|
27
|
+
|
|
28
|
+
/** The ranker's view of a workstream. Follow-up's own priority is left out, so a ranking never feeds itself. */
|
|
29
|
+
export function rankWorkstream(w: WorkstreamRow): RankWorkstream {
|
|
30
|
+
return {
|
|
31
|
+
id: w.workspaceId, title: clip(w.title, RANK_LIMITS.titleChars), branch: w.branch, group: w.group, ask: w.ask ? clip(w.ask, RANK_LIMITS.textChars) : null,
|
|
32
|
+
prs: w.prs.map(p => `#${p.number} ${p.state.toLowerCase()}${p.checks ? ` checks ${p.checks}` : ""}`), keys: w.keys, dormant: w.dormant,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Stable across runs: sorted, no timestamps that move by themselves. Equal text means the model would see the same thing. */
|
|
37
|
+
export function stableInputs(inputs: RankInputs): string {
|
|
38
|
+
const stable = {
|
|
39
|
+
w: [...inputs.workstreams].sort((a, b) => a.id.localeCompare(b.id)).map(w => [w.id, w.title, w.branch, w.group, w.ask, w.prs, w.keys, w.dormant]),
|
|
40
|
+
l: [...inputs.linear].sort((a, b) => a.key.localeCompare(b.key)).map(i => [i.key, i.title, i.priority, i.status, i.due, i.project, i.milestone]),
|
|
41
|
+
s: inputs.slack.map(m => [m.where, m.who, m.text]).sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))),
|
|
42
|
+
g: [...inputs.github].sort((a, b) => `${a.repo}#${a.number}`.localeCompare(`${b.repo}#${b.number}`)).map(r => [r.repo, r.number, r.title]),
|
|
43
|
+
p: inputs.planning ? inputs.planning.items.map(i => [i.level, i.title, i.keys]) : null,
|
|
44
|
+
};
|
|
45
|
+
return JSON.stringify(stable);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export const RANK_SYSTEM = `You rank a developer's workstreams (Paseo workspaces) by what matters most today. Reply with one JSON object only, no prose or code fence:
|
|
49
|
+
{"priorities":[{"workspace":"<workspace id>","score":0-100,"reason":"<one line, at most 60 characters, or empty>","sources":[{"kind":"linear|slack|github|planning|paseo","label":"<short>","url":"<only a url given in the material>"}]}],"notStarted":[{"key":"<Linear key>","title":"<title>","url":"<url>","reason":"<one line>"}]}
|
|
50
|
+
Rules:
|
|
51
|
+
- Rank only workspace ids from WORKSTREAMS. Give every non-resting workstream a score; leave resting ones out unless an input names them.
|
|
52
|
+
- The reason is the concrete fact, at most 60 characters, fact first: "HER-1312 · Urgent · due today", "This week's Okta milestone", "Dana asked twice, demo tomorrow", "Review requested by Avi". Never start it with the source's name ("Slack:", "Plan:", "Linear:"): the list shows the source beside it. Never "important" or "high priority" alone.
|
|
53
|
+
- When no outside input (Linear, Slack, GitHub, plan) names a workstream, still score it, but give reason "" and sources [].
|
|
54
|
+
- Spread the scores: a clear outside signal (urgent or due Linear issue, a person asking in Slack, a review request, this week's plan) scores above one without. A workstream waiting on the developer (group needs) with a real ask scores higher than the same work without one.
|
|
55
|
+
- Use only facts in the material. Never invent a key, a person, a date or a url.
|
|
56
|
+
- notStarted: Linear issues assigned to the developer that no workstream covers (match by key in keys, branch or title), at most 10, most urgent first.`;
|
|
57
|
+
|
|
58
|
+
/** The material for one run, bounded: each list is cut to its limit before the prompt is built, never after. */
|
|
59
|
+
export function rankPrompt(inputs: RankInputs, today: string, maxChars: number): string {
|
|
60
|
+
const L = RANK_LIMITS;
|
|
61
|
+
const sections: [string, string[]][] = [
|
|
62
|
+
["WORKSTREAMS (id · title · group · branch · PRs · keys · open ask)", inputs.workstreams.slice(0, L.workstreams).map(w =>
|
|
63
|
+
[w.id, w.title, w.dormant ? "resting" : w.group, w.branch ?? "-", w.prs.join(", ") || "-", w.keys.join(" ") || "-", w.ask ?? "-"].join(" · "))],
|
|
64
|
+
["LINEAR (assigned to the developer: key · priority · status · due · project / milestone · title · url)", inputs.linear.slice(0, L.issues).map(i =>
|
|
65
|
+
[i.key, i.priority ?? "-", i.status ?? "-", i.due ?? "-", [i.project, i.milestone].filter(Boolean).join(" / ") || "-", clip(i.title, L.titleChars), i.url ?? "-"].join(" · "))],
|
|
66
|
+
["SLACK (DMs and mentions, last 48 h: where · who · text · when)", inputs.slack.slice(0, L.messages).map(m => [m.where, m.who ?? "-", clip(m.text, L.textChars), m.at ?? "-"].join(" · "))],
|
|
67
|
+
["GITHUB (review requested from the developer: repo#number · title · author · url)", inputs.github.slice(0, L.reviews).map(r => [`${r.repo}#${r.number}`, clip(r.title, L.titleChars), r.author ?? "-", r.url ?? "-"].join(" · "))],
|
|
68
|
+
["PLAN (the CPO's weekly plan: level · title · keys)", (inputs.planning?.items ?? []).slice(0, L.planItems).map(i => [i.level, clip(i.title, L.titleChars), i.keys.join(" ") || "-"].join(" · "))],
|
|
69
|
+
];
|
|
70
|
+
const head = `Today is ${today} (Asia/Jerusalem).\n`;
|
|
71
|
+
let body = sections.map(([title, lines]) => `${title}:\n${lines.length ? lines.join("\n") : "(none)"}`).join("\n\n");
|
|
72
|
+
// Still too long: drop resting workstreams first, then the tail of each list.
|
|
73
|
+
if (head.length + body.length > maxChars) {
|
|
74
|
+
const lean = { ...inputs, workstreams: inputs.workstreams.filter(w => !w.dormant), slack: inputs.slack.slice(0, 20), linear: inputs.linear.slice(0, 30), planning: inputs.planning && { ...inputs.planning, items: inputs.planning.items.slice(0, 30) } };
|
|
75
|
+
if (lean.workstreams.length < inputs.workstreams.length || lean.slack.length < inputs.slack.length || lean.linear.length < inputs.linear.length) return rankPrompt(lean, today, maxChars);
|
|
76
|
+
body = body.slice(0, Math.max(0, maxChars - head.length - 1));
|
|
77
|
+
}
|
|
78
|
+
return head + body;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const sourceOut = z.object({ kind: z.enum(PRIORITY_SOURCES), label: z.string().trim().min(1).max(60), url: z.string().url().max(2000).optional().catch(undefined) });
|
|
82
|
+
export const rankReplySchema = z.object({
|
|
83
|
+
priorities: z.array(z.object({ workspace: z.string().trim().min(1).max(200), score: z.number().min(0).max(100), reason: z.string().trim().max(300).catch(""), sources: z.array(sourceOut).max(5).catch([]).default([]) })).max(200),
|
|
84
|
+
notStarted: z.array(z.object({ key: z.string().trim().min(1).max(30), title: z.string().trim().min(1).max(200), url: z.string().url().max(2000).optional().catch(undefined), reason: z.string().trim().max(300).catch("") })).max(20).catch([]).default([]),
|
|
85
|
+
});
|
|
86
|
+
export type RankReply = z.infer<typeof rankReplySchema>;
|
|
87
|
+
/** "Slack: ", "Plan: "…: the source chip already says it. */
|
|
88
|
+
const SOURCE_PREFIX = /^(slack|plan|planning|linear|github|paseo)\s*[:·-]\s*/i;
|
|
89
|
+
export type NotStarted = { key: string; title: string; url: string | null; reason: string };
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* The reply as priorities Home can show: known workspace ids only, one per workspace (the first), reasons cut to one
|
|
93
|
+
* line, urls only when the material had them. Blocking asks need no floor: Home lists Needs you first whatever the score.
|
|
94
|
+
*/
|
|
95
|
+
export function toPriorities(reply: RankReply, inputs: RankInputs, at: string): { priorities: Priority[]; notStarted: NotStarted[]; dropped: string[] } {
|
|
96
|
+
const by = new Map(inputs.workstreams.map(w => [w.id, w]));
|
|
97
|
+
const urls = new Set<string>([...inputs.linear.map(i => i.url), ...inputs.github.map(r => r.url), inputs.planning?.url ?? null].filter((u): u is string => !!u));
|
|
98
|
+
const seen = new Set<string>(); const dropped: string[] = [];
|
|
99
|
+
const priorities: Priority[] = [];
|
|
100
|
+
for (const p of reply.priorities) {
|
|
101
|
+
const w = by.get(p.workspace);
|
|
102
|
+
if (!w) { dropped.push(p.workspace); continue; }
|
|
103
|
+
if (seen.has(w.id)) continue;
|
|
104
|
+
seen.add(w.id);
|
|
105
|
+
const sources = p.sources.map(s => ({ kind: s.kind, label: clip(s.label, 60), ...(s.url && urls.has(s.url) ? { url: s.url } : {}) })).filter(s => prioritySourceSchema.safeParse(s).success);
|
|
106
|
+
const reason = clip(p.reason.split(/\r?\n/)[0].replace(SOURCE_PREFIX, ""), 140);
|
|
107
|
+
// No outside signal: a score but no line, so the list doesn't fill with "nothing here".
|
|
108
|
+
priorities.push({ workspaceId: w.id, score: Math.round(Math.min(100, p.score)), reason, sources: reason ? sources : [], at, by: "ranker" });
|
|
109
|
+
}
|
|
110
|
+
priorities.sort((a, b) => b.score - a.score || a.workspaceId.localeCompare(b.workspaceId));
|
|
111
|
+
const covered = new Set(inputs.workstreams.flatMap(w => w.keys.map(k => k.toUpperCase())));
|
|
112
|
+
const known = new Map(inputs.linear.map(i => [i.key.toUpperCase(), i]));
|
|
113
|
+
const notStarted = reply.notStarted.filter(n => known.has(n.key.toUpperCase()) && !covered.has(n.key.toUpperCase())).slice(0, 10)
|
|
114
|
+
.map(n => { const i = known.get(n.key.toUpperCase())!; return { key: i.key, title: i.title, url: i.url, reason: clip(n.reason, 140) }; });
|
|
115
|
+
return { priorities, notStarted, dropped };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// ---------- when it runs ----------
|
|
119
|
+
|
|
120
|
+
const JERUSALEM = new Intl.DateTimeFormat("en-US", { timeZone: "Asia/Jerusalem", weekday: "short", hour: "2-digit", hourCycle: "h23", year: "numeric", month: "2-digit", day: "2-digit" });
|
|
121
|
+
/** The Asia/Jerusalem calendar day and hour for a moment. */
|
|
122
|
+
export function jerusalem(now: number): { day: string; weekday: string; hour: number } {
|
|
123
|
+
const parts = Object.fromEntries(JERUSALEM.formatToParts(new Date(now)).map(p => [p.type, p.value]));
|
|
124
|
+
return { day: `${parts.year}-${parts.month}-${parts.day}`, weekday: parts.weekday, hour: Number(parts.hour) };
|
|
125
|
+
}
|
|
126
|
+
/** Sunday to Thursday, 08:00–20:00 in Asia/Jerusalem: the automatic runs. "Re-rank now" works any time. */
|
|
127
|
+
export function inRankWindow(now: number): boolean {
|
|
128
|
+
const j = jerusalem(now);
|
|
129
|
+
return ["Sun", "Mon", "Tue", "Wed", "Thu"].includes(j.weekday) && j.hour >= 8 && j.hour < 20;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** "Linear ok · Slack failed · Plan off": what the last run could read, for the sort header. */
|
|
133
|
+
export function healthLine(health: Partial<Record<RankSource, SourceHealth>>): string {
|
|
134
|
+
return RANK_SOURCES.filter(s => health[s] && health[s] !== "ok").map(s => `${RANK_SOURCE_LABEL[s]} ${health[s] === "off" ? "off" : "unavailable"}`).join(" · ");
|
|
135
|
+
}
|