paseo-follow-up 2.4.0-beta.0 → 2.4.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/client/header.tsx +9 -4
- package/client/home-list.tsx +3 -3
- package/client/home.tsx +3 -2
- package/client/merge-button.tsx +1 -1
- package/index.server.ts +32 -4
- package/package.json +2 -1
- package/server/agent-hook.mjs +35 -6
- package/server/check-watches.ts +145 -0
- package/server/engine.ts +13 -2
- package/server/github.ts +15 -2
- package/server/hook-source.ts +35 -6
- package/server/mcp-source.ts +8 -5
- package/server/mcp.mjs +8 -5
- package/server/obligations.ts +18 -2
- package/server/pr-stats-gate.ts +102 -0
- package/server/pr-stats-store.ts +196 -0
- package/server/pr-stats-sync.ts +228 -0
- package/server/questions.ts +35 -8
- package/server/wait-for-checks.ts +108 -0
- package/shared/attention.ts +6 -5
- package/shared/chat.ts +1 -1
- package/shared/check-watch.ts +129 -0
- package/shared/contracts.ts +7 -1
- package/shared/home.ts +18 -6
- package/shared/model.ts +17 -2
- package/shared/poll.ts +9 -2
- package/shared/pr-stats-records.ts +169 -0
- package/shared/questions.ts +75 -0
- package/shared/queue.ts +1 -1
- package/shared/status-invariants.ts +25 -2
- package/shared/task-status.ts +9 -2
package/client/header.tsx
CHANGED
|
@@ -17,12 +17,17 @@ export const STALE_MS = 10 * 60_000;
|
|
|
17
17
|
|
|
18
18
|
/**
|
|
19
19
|
* One mark per PR in stack order, coloured by state; past STACK_BAR_BUDGET PRs, runs or slices of the stack as wide as
|
|
20
|
-
* their share (`barMarks`, stack-bar-reads-at-any-size). The signature of the panel
|
|
20
|
+
* their share (`barMarks`, stack-bar-reads-at-any-size). The signature of the panel. A mark opens its loudest PR on
|
|
21
|
+
* desktop only: on a phone the marks are 6-8 pt wide and 2 pt apart, far under the 44 pt touch rule, and the Pull
|
|
22
|
+
* requests card's rows right below open every PR, so the compact header draws it without `onOpen` (one progress bar,
|
|
23
|
+
* no buttons).
|
|
21
24
|
*/
|
|
22
25
|
export function StackBar({ workspace, theme, height = 6, onOpen }: { workspace: Pick<Workspace, "prs">; theme: Theme; height?: number; onOpen?: (key: string) => void }) {
|
|
23
26
|
const bar = stackBar(workspace);
|
|
24
27
|
if (!bar.total) return null;
|
|
25
|
-
|
|
28
|
+
// The label says what the marks show, so a phone's bar (no per-mark buttons) still tells a screen reader what is red (failed checks or a conflict: the header's "to fix").
|
|
29
|
+
const failing = bar.segments.filter(s => s.tone === "danger").length;
|
|
30
|
+
return <View accessibilityRole="progressbar" accessibilityLabel={`${bar.merged} of ${bar.total} PRs merged${failing ? `, ${failing} to fix` : ""}`} accessibilityValue={{ min: 0, max: bar.total, now: bar.merged }}
|
|
26
31
|
style={{ flexDirection: "row", gap: 2, height, borderRadius: height / 2, overflow: onOpen ? "visible" : "hidden" }}>
|
|
27
32
|
{barMarks(bar.segments).map((s, i, marks) => {
|
|
28
33
|
const paint = segmentPaint(theme.colors, s.tone);
|
|
@@ -110,7 +115,7 @@ export function WorkspaceHeader({ workspace: w, theme, compact, now, onSettings,
|
|
|
110
115
|
<Text accessibilityLiveRegion="polite" style={[t.ask, { color: c.foregroundMuted }]}>
|
|
111
116
|
{parts.map((part, i) => <Text key={part.text} style={toneOf(part.tone) ? { color: toneOf(part.tone) } : { color: c.foreground }}>{i ? <Text style={{ color: c.foregroundMuted, fontWeight: "400" }}>{" · "}</Text> : null}{part.text}</Text>)}
|
|
112
117
|
</Text>
|
|
113
|
-
<StackBar workspace={w} theme={theme} onOpen={onOpenPr} />
|
|
118
|
+
<StackBar workspace={w} theme={theme} onOpen={compact ? undefined : onOpenPr} />
|
|
114
119
|
{tail}
|
|
115
120
|
</View>;
|
|
116
121
|
return <View style={{ paddingHorizontal: pad, paddingTop: compact ? 14 : 12, paddingBottom: 10, gap: 6, borderBottomWidth: 1, borderBottomColor: c.border }}>
|
|
@@ -127,7 +132,7 @@ export function WorkspaceHeader({ workspace: w, theme, compact, now, onSettings,
|
|
|
127
132
|
<Text accessibilityLiveRegion="polite" style={[t.meta, { color: c.foregroundMuted, marginTop: 2 }]}>
|
|
128
133
|
{parts.map((part, i) => <Text key={part.text} style={toneOf(part.tone) ? { color: toneOf(part.tone), fontWeight: "600" } : { color: c.foreground }}>{i ? <Text style={{ color: c.foregroundMuted, fontWeight: "400" }}>{" · "}</Text> : null}{part.text}</Text>)}
|
|
129
134
|
</Text>
|
|
130
|
-
<StackBar workspace={w} theme={theme} onOpen={onOpenPr} />
|
|
135
|
+
<StackBar workspace={w} theme={theme} onOpen={compact ? undefined : onOpenPr} />
|
|
131
136
|
{tail}
|
|
132
137
|
</View>;
|
|
133
138
|
}
|
package/client/home-list.tsx
CHANGED
|
@@ -2,7 +2,7 @@ import { memo, useCallback, useEffect, useMemo, useRef, useState, type ReactNode
|
|
|
2
2
|
import { View, type FlatList as NativeFlatList } from "react-native";
|
|
3
3
|
import { Pressable, Text } from "./text";
|
|
4
4
|
import { Icon, FlatList } from "@getpaseo/plugin/client/ui";
|
|
5
|
-
import { type Badge, type HomeGroupId, type HomeModel, type Workstream, railChips } from "../shared/home";
|
|
5
|
+
import { type Badge, type HomeGroupId, type HomeModel, type Workstream, prChipSpoken, railChips } from "../shared/home";
|
|
6
6
|
import { ASK_KEY, excerpt, FIELD_LABEL, type OmniboxItem, type Range, type RowHit, type SearchHit } from "../shared/search";
|
|
7
7
|
import { AskRow, PriorityLine } from "./home-chrome";
|
|
8
8
|
import { age, wakeLabel, wakeShort } from "../shared/inbox";
|
|
@@ -260,7 +260,7 @@ export function BadgeView({ b, c }: { b: Badge; c: Colors }) {
|
|
|
260
260
|
export function PrChipView({ s, c }: { s: Workstream; c: Colors }) {
|
|
261
261
|
if (!s.pr) return null;
|
|
262
262
|
const checks = s.pr.checks;
|
|
263
|
-
return <View testID="follow-up-row-chip" style={{ flexShrink: 1, minWidth: 0, flexDirection: "row", alignItems: "center", gap: 4, paddingHorizontal: 6, height: 20, borderRadius: 4, borderWidth: 1, borderColor: c.border }}>
|
|
263
|
+
return <View testID="follow-up-row-chip" role="img" aria-label={prChipSpoken(s.pr)} style={{ flexShrink: 1, minWidth: 0, flexDirection: "row", alignItems: "center", gap: 4, paddingHorizontal: 6, height: 20, borderRadius: 4, borderWidth: 1, borderColor: c.border }}>
|
|
264
264
|
<Icon name="GitPullRequest" size={11} color={toneColor(c, s.pr.tone)} />
|
|
265
265
|
<Text numberOfLines={1} style={{ flexShrink: 0, color: c.foreground, fontSize: 11, lineHeight: 14, fontVariant: ["tabular-nums"] }}>{s.pr.label}</Text>
|
|
266
266
|
{checks && <Text numberOfLines={1} style={{ flexShrink: 1, minWidth: 0, color: checks.tone === "muted" ? c.foregroundMuted : badgeColor({ text: "", tone: checks.tone }, c), fontSize: 11, lineHeight: 14 }}>{checks.text}</Text>}
|
|
@@ -343,7 +343,7 @@ const Row = memo(function Row({ s, theme, dense, touch, selected, onSelect, onMe
|
|
|
343
343
|
const waited = s.group === "later" && s.at ? age(s.at, Date.now()) : "";
|
|
344
344
|
const label = [s.title + (s.agent ? ` › ${s.agent}` : ""), s.word, s.line, hit?.via && `${FIELD_LABEL[hit.via.field]}: ${hit.via.text}`,
|
|
345
345
|
// Every chip, even one a narrow row hides (row-chips-never-cover-the-time).
|
|
346
|
-
...s.badges.map(b => b.text), s.pr &&
|
|
346
|
+
...s.badges.map(b => b.text), s.pr && prChipSpoken(s.pr), wake && `Later until ${wake}`, waited && (waited === "now" ? "just now" : `waiting ${waited}`)].filter(Boolean).join(". ");
|
|
347
347
|
return <Pressable ref={trigger.ref} nativeID={rowDomId(s.key)} accessibilityRole="button" accessibilityState={{ selected }} accessibilityLabel={label} accessibilityHint={quickActionsHint(touch)}
|
|
348
348
|
onPress={() => onSelect(s.key)} onLongPress={trigger.onLongPress} delayLongPress={450}
|
|
349
349
|
style={state => ({ ...focusRing((state as { focused?: boolean }).focused, c, true), flexDirection: "row", alignItems: dense ? "flex-start" : "center", gap: touch ? 10 : dense ? 8 : 10, minHeight: touch ? 56 : dense ? 36 : 38, paddingLeft: touch ? 14 : dense ? 8 : 16, paddingRight: touch ? 16 : dense ? 8 : 16, paddingVertical: touch ? 12 : dense ? 6 : 0,
|
package/client/home.tsx
CHANGED
|
@@ -8,7 +8,7 @@ import { useQuery } from "@tanstack/react-query";
|
|
|
8
8
|
import { browserStatusRpc, controlRpc, inboxBriefRpc, sendRpc } from "../shared/contracts";
|
|
9
9
|
import { needsYou, workspaceSnoozed } from "../shared/attention";
|
|
10
10
|
import { briefAsks, briefCardShown, liveBrief } from "../shared/brief";
|
|
11
|
-
import { briefPane, followUpLog, lastWorkdayEnd, nextNeeds, paneButtons, sameText, sinceLabel, tailSteps, type HomeGroupId, type HomeModel, type LogLine, type TailStep, type Workstream } from "../shared/home";
|
|
11
|
+
import { briefPane, followUpLog, lastWorkdayEnd, nextNeeds, paneButtons, prChipSpoken, sameText, sinceLabel, tailSteps, type HomeGroupId, type HomeModel, type LogLine, type TailStep, type Workstream } from "../shared/home";
|
|
12
12
|
import { age, backLabel, snoozeUntil, type InboxRow } from "../shared/inbox";
|
|
13
13
|
import { errorText } from "../shared/errors";
|
|
14
14
|
import { isLoaded, type LoadSignals } from "../shared/agent-load";
|
|
@@ -489,7 +489,8 @@ function DetailPane({ s, model, theme, compact, deps, openFull, signOffNext, ask
|
|
|
489
489
|
{!writing && s.workspaceId && w && <View style={{ marginTop: 6 }}><ReferencesLine key={`refs:${s.workspaceId}`} workspace={w} theme={theme} compact /></View>}
|
|
490
490
|
{!writing && <View style={{ flexDirection: "row", alignItems: "center", gap: 6, minHeight: 44 }}>
|
|
491
491
|
<Icon name={s.icon} size={14} color={color} />
|
|
492
|
-
|
|
492
|
+
{/* Read as one line, with the PR summary in words: a nested Text can't carry its own label. */}
|
|
493
|
+
<Text numberOfLines={1} accessibilityLabel={[s.word, metaRest, s.pr && prChipSpoken(s.pr)].filter(Boolean).join(" · ")} style={[t.meta, { flex: 1, minWidth: 0 }]}>
|
|
493
494
|
{!!s.word && <Text style={{ color, fontWeight: "600" }}>{s.word}</Text>}
|
|
494
495
|
{metaRest ? (s.word ? ` · ${metaRest}` : metaRest) : ""}
|
|
495
496
|
<PrSummaryText s={s} c={c} lead=" · " />
|
package/client/merge-button.tsx
CHANGED
|
@@ -88,7 +88,7 @@ export function useMergeButtons(w: Workspace | undefined): MergeButtons {
|
|
|
88
88
|
}
|
|
89
89
|
|
|
90
90
|
/**
|
|
91
|
-
* "#143 approved · waits on #142 (checks
|
|
91
|
+
* "#143 approved · waits on #142 (checks failed)": an approved PR that Merge isn't offered on because a PR under it
|
|
92
92
|
* can't merge yet (heldMerges). Quiet, not an ask; both numbers open their PRs. The panel's Pull requests card and
|
|
93
93
|
* Home's detail pane draw it, so an approved PR never goes invisible.
|
|
94
94
|
*/
|
package/index.server.ts
CHANGED
|
@@ -10,7 +10,7 @@ import { moveData, dataDirs, writeLegacyHeartbeat, type DataMove } from "./serve
|
|
|
10
10
|
import { isRecovery, withRuntimePrelude, invokeSelf, PLUGIN_ID } from "./shared/legacy";
|
|
11
11
|
import { displayPreferences } from "./shared/display";
|
|
12
12
|
import { DEFAULT_QUESTION_MODE, QUESTION_DEDUPE_MIGRATION, awaitingSend, collapseDuplicateQuestions, questionPreferences, signedOffAnswers, type QuestionMode } from "./shared/questions";
|
|
13
|
-
import { answerRecipients, askQuestion, needsYouQuestions, recordAnswer, syncTaskQuestions, withdrawQuestion } from "./server/questions";
|
|
13
|
+
import { answerRecipients, askQuestion, coverNote, needsYouQuestions, recordAnswer, syncTaskQuestions, withdrawQuestion } from "./server/questions";
|
|
14
14
|
import { dismissItem, dismissedNeeds, undoDismissItem } from "./server/dismiss";
|
|
15
15
|
import { agentSetSpec, developerSetSpec } from "./server/spec";
|
|
16
16
|
import type { PluginServerContext, PluginHandlerContext, PluginHookContext, PluginSessionOpenRequest } from "@getpaseo/plugin/server";
|
|
@@ -95,6 +95,8 @@ import { hostFeature, type ServerInfo } from "./server/host-features";
|
|
|
95
95
|
import { newWorkspaceTarget, sendReport, type ReportSendDeps } from "./server/report-send";
|
|
96
96
|
type ServerInfoClient = { getLastServerInfoMessage?: () => ServerInfo };
|
|
97
97
|
import { inboxAnswer } from "./server/etag";
|
|
98
|
+
import { CheckWatches } from "./server/check-watches";
|
|
99
|
+
import { waitForChecksAnswer } from "./server/wait-for-checks";
|
|
98
100
|
import { jobAgentRunner, type JobPaseo } from "./server/job-agent";
|
|
99
101
|
import { AiJobs } from "./server/ai-jobs";
|
|
100
102
|
import { liveRankSources, planningUrl, Ranker, RANKER_ROLE_DEFAULT } from "./server/ranker";
|
|
@@ -228,6 +230,17 @@ export default function contribute(server: PluginServerContext) {
|
|
|
228
230
|
const actions = new PrActions(store, github, graphite, browser);
|
|
229
231
|
actions.savedMethod = repo => prWorkflow.current().repos[repoKey(repo)]?.mergeMethod ?? null;
|
|
230
232
|
const engine = new Engine(store, github, gateway);
|
|
233
|
+
// Wait for checks (docs/wait-for-checks.md): judged after each engine pass from the reads it made; a verdict is one
|
|
234
|
+
// queued message. The agent is read from the directory's list (no load), live only when the list lacks it.
|
|
235
|
+
const checkWatches = new CheckWatches(directory, {
|
|
236
|
+
snapshot: () => store.snapshot(),
|
|
237
|
+
quietSince: key => github.quietSince(key),
|
|
238
|
+
agent: async id => {
|
|
239
|
+
const a = gateway.directory.cached(id) ?? (await gateway.directory.read({ fresh: "agents" })).agents.find(r => r.agent.id === id)?.agent;
|
|
240
|
+
return a ? { status: a.status, archived: !!a.archivedAt, workspaceId: a.workspaceId ?? null } : null;
|
|
241
|
+
},
|
|
242
|
+
});
|
|
243
|
+
engine.checkWatches = checkWatches;
|
|
231
244
|
engine.wording = { reviewFix: repo => commandName(prWorkflow.reviewFix(repo)) };
|
|
232
245
|
actions.settleTasks = w => engine.settleTasks(w);
|
|
233
246
|
const governor = new Governor();
|
|
@@ -324,6 +337,7 @@ export default function contribute(server: PluginServerContext) {
|
|
|
324
337
|
// a-message-is-saved-before-sent-and-arrives-once: every message to an agent goes through one queue (queue.json).
|
|
325
338
|
const queue = new MessageQueue(directory, { deliverTo: (target, text, messageId, by) => gateway.deliverTo(target, text, messageId, by), arrived: (agentId, messageId, since, marker) => gateway.arrivedMessage(agentId, messageId, since, marker), probe: () => gateway.probe() }, { health: writeHealth });
|
|
326
339
|
engine.attachQueue(queue);
|
|
340
|
+
checkWatches.attachQueue(queue);
|
|
327
341
|
inbox.attachQueue(queue);
|
|
328
342
|
// Overseer forwards and reports handed to an agent: no record of their own, so the queue item is their status
|
|
329
343
|
// (follow_queue_list). Archived agents cancel, with the reason on the item.
|
|
@@ -718,7 +732,9 @@ export default function contribute(server: PluginServerContext) {
|
|
|
718
732
|
const w = agentWorkspace(state, agentId, "write", workspaceId);
|
|
719
733
|
const obligation = updateObligation(w, { ...input, caller: agentId, workingAgentId });
|
|
720
734
|
syncTaskQuestions(w, Date.now());
|
|
721
|
-
|
|
735
|
+
// one-decision-one-card: say so when the blocked task is already asked (or answered) as a question.
|
|
736
|
+
const note = coverNote(w, obligation.id);
|
|
737
|
+
changed(w); return { ...w, updatedObligationId: obligation.id, ...(note ? { note } : {}) };
|
|
722
738
|
});
|
|
723
739
|
void engine.nudge(result.id); return result;
|
|
724
740
|
});
|
|
@@ -730,7 +746,8 @@ export default function contribute(server: PluginServerContext) {
|
|
|
730
746
|
const w = agentWorkspace(state, agentId, "write", workspaceId);
|
|
731
747
|
const { supersedes, ...ask } = input;
|
|
732
748
|
const { question, instruction, outcome, of } = askQuestion(w, agentId, ask, mode, Date.now(), { via: "ask", ...(supersedes ? { supersedes } : {}) });
|
|
733
|
-
|
|
749
|
+
// A card a blocked task made for this decision closes now (one-decision-one-card), not on the next tick.
|
|
750
|
+
if (outcome !== "duplicate") { syncTaskQuestions(w, Date.now()); changed(w); }
|
|
734
751
|
return { workspaceId: w.id, question, mode, instruction, outcome, of };
|
|
735
752
|
});
|
|
736
753
|
});
|
|
@@ -1005,6 +1022,16 @@ export default function contribute(server: PluginServerContext) {
|
|
|
1005
1022
|
}) };
|
|
1006
1023
|
});
|
|
1007
1024
|
handle(rpc.contextListRpc, async ({ workspaceId }) => ({ requests: await contextRequests.list(workspaceId ? { workspaceId } : {}) }));
|
|
1025
|
+
// Paseo 0.17's own PR watch (subscribe_change_request): named only for PRs Follow-up can't see. No feature flag says
|
|
1026
|
+
// it's there; server_info's version does, read from the connection's last hello (no request).
|
|
1027
|
+
const hostVersion = async () => { try { return String(((await withDaemon(async client => (client as ServerInfoClient).getLastServerInfoMessage?.())) as { version?: unknown } | null)?.version ?? ""); } catch { return ""; } };
|
|
1028
|
+
handle(rpc.waitForChecksRpc, async (input, { paseo }) => {
|
|
1029
|
+
await requireReady();
|
|
1030
|
+
return waitForChecksAnswer(input, {
|
|
1031
|
+
state: () => store.snapshot(), watches: checkWatches, nudge: id => engine.nudge(id), hostVersion,
|
|
1032
|
+
register: (repo, number) => handlers.get(rpc.registerPrRpc.name)!.run({ agentId: input.agentId, repo, number, stack: `${repo}#${number}` }, { paseo } as PluginHandlerContext) as Promise<unknown>,
|
|
1033
|
+
});
|
|
1034
|
+
});
|
|
1008
1035
|
handle(rpc.contextReplyRpc, async ({ agentId, requestId, text }) => {
|
|
1009
1036
|
await requireReady();
|
|
1010
1037
|
await contextRequests.reply(requestId, agentId, text);
|
|
@@ -1434,6 +1461,7 @@ export default function contribute(server: PluginServerContext) {
|
|
|
1434
1461
|
const linked = await store.mutate(state => {
|
|
1435
1462
|
const w = findWorkspace(state, tracked.id);
|
|
1436
1463
|
const result = needsYouQuestions(w, agentId, call, mode, Date.now(), sameTurn ? previous : null);
|
|
1464
|
+
if (result.createdIds.length) syncTaskQuestions(w, Date.now());
|
|
1437
1465
|
if (result.questionIds.length || sameTurn) changed(w);
|
|
1438
1466
|
return { ...result, ask: foldedAsk(call.ask, result.questionIds, w.questions) };
|
|
1439
1467
|
});
|
|
@@ -1659,7 +1687,7 @@ export default function contribute(server: PluginServerContext) {
|
|
|
1659
1687
|
// One deadline for every wait (worker-stop-never-waits-on-a-stuck-pass, server/teardown.ts): start-up and the work
|
|
1660
1688
|
// in flight may be stuck on a daemon or CLI that never answers. Work that ends inside the deadline is saved; what
|
|
1661
1689
|
// outlives it can't write, because the store closes before the lock is released.
|
|
1662
|
-
await stopWorker({ files: [contextRequests, reviewerStore, agentSettings, prWorkflow, queue], ready, hooks: hooksStarted ? () => agentHooks.stop() : undefined, actions, closeConnections, engine, store, inbox: inbox.store, unlock });
|
|
1690
|
+
await stopWorker({ files: [contextRequests, checkWatches, reviewerStore, agentSettings, prWorkflow, queue], ready, hooks: hooksStarted ? () => agentHooks.stop() : undefined, actions, closeConnections, engine, store, inbox: inbox.store, unlock });
|
|
1663
1691
|
})();
|
|
1664
1692
|
return stop;
|
|
1665
1693
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "paseo-follow-up",
|
|
3
3
|
"private": false,
|
|
4
|
-
"version": "2.4.0-beta.
|
|
4
|
+
"version": "2.4.0-beta.1",
|
|
5
5
|
"description": "Follows every workspace your coding agents work in until it's done: one list of what needs you.",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"files": [
|
|
@@ -41,6 +41,7 @@
|
|
|
41
41
|
"release:notes": "node scripts/release-notes.mjs",
|
|
42
42
|
"test:feeds": "node scripts/screenshots.mjs --only feeds --out .feeds-check",
|
|
43
43
|
"test:wait": "node scripts/check-wait.mjs",
|
|
44
|
+
"test:wait-checks": "node scripts/check-wait-for-checks.mjs",
|
|
44
45
|
"test:wait-live": "node scripts/check-wait.mjs --live",
|
|
45
46
|
"shots": "node scripts/screenshots.mjs",
|
|
46
47
|
"shots:readme": "sh scripts/readme-shots.sh",
|
package/server/agent-hook.mjs
CHANGED
|
@@ -13,7 +13,7 @@ const directory = dirname(fileURLToPath(import.meta.url));
|
|
|
13
13
|
/** 1.4.0-beta.2: launched with Follow-up's tools served by Paseo's MCP (follow_<name>), or the follow-up bridge (<name>). Agents opened before the upgrade carry no flag and keep the bridge names. */
|
|
14
14
|
let native = env("TOOLS") === "native";
|
|
15
15
|
// Tool names that read unambiguously in prose; kept identical to server/mcp.mjs's underscore names (a test checks it).
|
|
16
|
-
export const TOOL_NAMES = ["workspace_status", "sync_workspace", "enroll_workspace", "register_pr", "exclude_stack", "update_obligation", "acknowledge_batch", "ask_question", "record_answer", "withdraw_question", "set_spec", "link_item", "unlink_item", "link_items", "set_linked_items", "workspace_about", "agent_settings", "needs_you", "declare_done", "list_prs", "add_reviewers", "enable_merge_when_ready", "disable_merge_when_ready", "send_repairs", "set_auto_send", "clear_hold", "retry_batch", "inbox_list", "sign_off", "snooze_workspace", "set_finish_flags", "set_priorities", "agent_digest", "route_candidates", "send_to_agent", "start_workspace", "display_settings", "set_display", "follow_settings", "set_follow_settings", "project_settings", "set_project_tracking", "pr_workflow", "set_pr_workflow", "reviewer_settings", "reviewer_suggestions", "save_reviewers", "set_agent_setting", "set_wait_for_jobs", "onboarding_status", "onboarding_checks", "set_onboarding", "rank_status", "rerank_priorities", "overseer_status", "overseer_start", "overseer_restart", "overseer_ask", "inbox_brief", "brief_action", "queue_list", "queue_action", "inbox_act", "answer_question", "dismiss_question", "dismiss_item", "run_recovery", "set_workspace_spec", "set_task_trigger", "pr_controls", "browser_status", "trust_bypass_status", "release_notes", "updates_status", "check_updates", "set_updates", "install_update", "make_main_agent", "retry_move", "report_issue", "report_send", "ai_rename", "catch_up_deck", "context_requests", "ask_context", "context_reply"];
|
|
16
|
+
export const TOOL_NAMES = ["workspace_status", "sync_workspace", "enroll_workspace", "register_pr", "exclude_stack", "update_obligation", "acknowledge_batch", "ask_question", "record_answer", "withdraw_question", "set_spec", "link_item", "unlink_item", "link_items", "set_linked_items", "workspace_about", "agent_settings", "needs_you", "declare_done", "list_prs", "add_reviewers", "enable_merge_when_ready", "disable_merge_when_ready", "send_repairs", "set_auto_send", "clear_hold", "retry_batch", "inbox_list", "sign_off", "snooze_workspace", "set_finish_flags", "set_priorities", "agent_digest", "route_candidates", "send_to_agent", "start_workspace", "display_settings", "set_display", "follow_settings", "set_follow_settings", "project_settings", "set_project_tracking", "pr_workflow", "set_pr_workflow", "reviewer_settings", "reviewer_suggestions", "save_reviewers", "set_agent_setting", "set_wait_for_jobs", "onboarding_status", "onboarding_checks", "set_onboarding", "rank_status", "rerank_priorities", "overseer_status", "overseer_start", "overseer_restart", "overseer_ask", "inbox_brief", "brief_action", "queue_list", "queue_action", "inbox_act", "answer_question", "dismiss_question", "dismiss_item", "run_recovery", "set_workspace_spec", "set_task_trigger", "pr_controls", "browser_status", "trust_bypass_status", "release_notes", "updates_status", "check_updates", "set_updates", "install_update", "make_main_agent", "retry_move", "report_issue", "report_send", "ai_rename", "catch_up_deck", "context_requests", "ask_context", "context_reply", "wait_for_checks"];
|
|
17
17
|
const toolPattern = new RegExp(`(?<![\\w])(${TOOL_NAMES.join("|")})(?![\\w])`, "g");
|
|
18
18
|
/** Names Follow-up's tools the way this agent has them. */
|
|
19
19
|
export function named(text, isNative = native) { return isNative ? text.replace(toolPattern, "follow_$1") : text; }
|
|
@@ -124,6 +124,32 @@ export function batchParagraph(workflow) {
|
|
|
124
124
|
export const NO_REVIEW_MERGE = "This repository has no review: merge your own PR once CI is green, without asking the developer. Archiving remains the developer's action.";
|
|
125
125
|
/** Who merges, closing the batch paragraph: the developer (team review, unchanged text), or the agent in a No review repository. */
|
|
126
126
|
export const mergeLine = workflow => workflow?.noReview ? NO_REVIEW_MERGE : "Merging and archiving remain the developer's actions.";
|
|
127
|
+
/**
|
|
128
|
+
* Wait for checks (docs/wait-for-checks.md). One SessionStart line for root agents, and a PostToolUse nudge when a
|
|
129
|
+
* shell command polls GitHub for CI: said at most once per turn, never blocking (the-polling-nudge-never-blocks).
|
|
130
|
+
* The hook already runs on every PostToolUse (no matcher), so this costs no new process.
|
|
131
|
+
*/
|
|
132
|
+
export const checksLine = "To wait for CI, don't poll GitHub (gh pr checks --watch, gh run watch, sleep loops over gh): call wait_for_checks with the PR after pushing and end your turn; Follow-up messages you when the checks finish.";
|
|
133
|
+
export const pollNudge = "That command polls GitHub for CI, which spends the developer's shared GitHub budget. Stop it, call wait_for_checks with the PR (no prs = every open PR of this workspace) and end your turn: Follow-up messages you once when the checks finish, from reads it already makes. A single gh pr checks to look once is fine.";
|
|
134
|
+
const SHELL_TOOL = /(bash|shell|exec_command|write_stdin|monitor|terminal)/i;
|
|
135
|
+
const GH_QUERY = /\bgh\s+(?:pr\s+(?:checks|view|status)\b|run\s+(?:list|view)\b|api\b[^\n;|&]*(?:graphql|\/pulls\b|check-runs|check-suites|\/statuses\b|\/status\b|\/actions\/runs))/;
|
|
136
|
+
const GH_WATCH = /\bgh\s+(?:pr\s+checks\b[^\n;|&]*--watch\b|run\s+watch\b)/;
|
|
137
|
+
// A for loop over PRs (reading each one once) isn't polling; a wait between reads is.
|
|
138
|
+
const LOOP = /(?:^|[\s;&|({])(?:while|until)\b[\s\S]*?\bdo\b|\bsleep\s+\d|\bwatch\s+-n\b|\bsetInterval\b|\btime\.sleep\(/;
|
|
139
|
+
/** The text a tool call runs: every string in its input (Bash command, Codex cmd, Monitor's command, a script). */
|
|
140
|
+
function commandText(input) {
|
|
141
|
+
const out = [];
|
|
142
|
+
const walk = v => { if (typeof v === "string") out.push(v); else if (Array.isArray(v)) v.forEach(walk); else if (v && typeof v === "object") Object.values(v).forEach(walk); };
|
|
143
|
+
walk(input);
|
|
144
|
+
return out.join("\n").slice(0, 20_000);
|
|
145
|
+
}
|
|
146
|
+
/** Whether a shell tool call polls GitHub for CI: a watch command, or a loop or sleep around a gh status read. */
|
|
147
|
+
export function pollsGithub(tool, input) {
|
|
148
|
+
if (!SHELL_TOOL.test(String(tool ?? ""))) return false;
|
|
149
|
+
const text = commandText(input);
|
|
150
|
+
if (GH_WATCH.test(text)) return true;
|
|
151
|
+
return GH_QUERY.test(text) && LOOP.test(text);
|
|
152
|
+
}
|
|
127
153
|
const quote = value => "'" + value.replaceAll("'", "'\\''") + "'";
|
|
128
154
|
async function json(path) { return JSON.parse(await readFile(path, "utf8")); }
|
|
129
155
|
async function save(path, value) {
|
|
@@ -151,7 +177,7 @@ function paragraphs(lease, contributor, workflow) {
|
|
|
151
177
|
"When a decision needs the developer, call ask_question with a short title, the question, lettered options with what each means, and your recommendation; mark it big only when building ahead would leave this computer, set something others rely on, or most remaining work depends on it. Follow the question mode in its reply. Ask each decision once: asking it again returns the open question, and at a turn's end you point at it (needs_you questions=[\"Q<n>\"]) instead of restating it. Answers arrive as messages starting \"Follow-up answer Q<n>\" and are already recorded; several decisions from one card arrive together in one message, one line per decision, with skipped ones marked \"skipped\" and still open. An answer of Something else — \"…\" means none of your options: the quoted words are the developer's answer. Every card already offers Something else, so don't add an Other option. If the developer answers in chat, call record_answer (choice \"other\" with words when it matches none of your options). Withdraw questions that stop mattering. " + ENVELOPE_GUIDANCE,
|
|
152
178
|
linkInstruction,
|
|
153
179
|
"If you keep a Claude artifact (or doc) summarizing this workspace's goal, decisions and status, register its link once with set_spec after the first publish. Republish to the same URL; call set_spec again only if the link changes.",
|
|
154
|
-
"Keep actual follow-up tasks current with update_obligation: production behavior checks, migrations and decisions, with concise titles, PR dependencies and evidence. Do not add merge/approval/deploy checklist tasks. Deployment-dependent work waits for verified serving revisions and existing production permissions. A task waiting on a PR or another agent is status=waiting; blocked is only for the developer,
|
|
180
|
+
"Keep actual follow-up tasks current with update_obligation: production behavior checks, migrations and decisions, with concise titles, PR dependencies and evidence. Do not add merge/approval/deploy checklist tasks. Deployment-dependent work waits for verified serving revisions and existing production permissions. A task waiting on a PR or another agent is status=waiting; blocked is only for the developer. One decision, one card: ask it once with ask_question (task set to the task), then mark the task blocked with question=\"Q<n>\"; ask= is only for a decision you haven't asked. Once it is answered, act on the answer and move the task.",
|
|
155
181
|
"Stakeholder replies are follow-up too. When asked to update a requester, capture the original Slack threadUrl, recipient and explicit developer authorization in the task's communication field; referenced messages alone do not authorize posting. Use a concise progress task now and, when needed, a verify-and-reply task with purpose=verified after the relevant deployed PRs. Read existing thread replies and refresh evidence before posting; distinguish fixed, deployed and verified. Record the actual sent replyUrl and result before marking done. If posting is unavailable or its outcome is uncertain, keep the task blocked and check the thread before any retry; never claim a draft was sent. Auto authorizes delivery to you, not external messages. Communication-only requests do not authorize repairs, benchmarks, migrations or other production writes.",
|
|
156
182
|
"Tasks are manual unless explicitly scheduled with trigger={event:\"now\"|\"merge\"|\"deploy\",delayDays:0}. Only set a trigger from the developer\u2019s requested timing; never infer timing from a title or enable_follow_up alone. Merge/deploy triggers require owned afterPrs; delayDays=14 waits fourteen days after the last dependency event. Now requires no PR dependencies or delay. Deployment timing starts at the first verified fully serving observation and remains conservative when history is unknown. Preserve existing trigger fields on updates; trigger=null makes a task manual. Auto controls delivery, not timing or production permissions.",
|
|
157
183
|
batchParagraph(workflow) + " For post-deploy tasks, verify the currently serving revision contains every dependency and record behavioral results separately. Acknowledge the header's batch ID with acknowledge_batch before finishing: completed with the result, or blocked with the reason (humanOnly=true when only a person can move it, such as a stale review the reviewer must re-review or dismiss). Verify the entire goal and post-merge work before declare_done; acknowledge a completion batch first. " + mergeLine(workflow),
|
|
@@ -247,7 +273,7 @@ async function main() {
|
|
|
247
273
|
return;
|
|
248
274
|
}
|
|
249
275
|
const context = () => instructions(lease, contributor, workflow);
|
|
250
|
-
const sessionText = async () => [workspace ? context() : null, ...await nativeExtras(brief), ...await waitExtras()].filter(Boolean).join("\n\n");
|
|
276
|
+
const sessionText = async () => [workspace ? context() : null, ...await nativeExtras(brief), ...await waitExtras(), workspace || env("ROOT") === "1" ? named(checksLine) : null].filter(Boolean).join("\n\n");
|
|
251
277
|
const name = event.hook_event_name;
|
|
252
278
|
if (!["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"].includes(name)) return;
|
|
253
279
|
const session = createHash("sha256").update(String(event.session_id ?? agentId)).digest("hex").slice(0, 24);
|
|
@@ -272,8 +298,11 @@ async function main() {
|
|
|
272
298
|
if (name === "PostToolUse") {
|
|
273
299
|
// Said once per session per worker: the tools stay detached until the session reopens.
|
|
274
300
|
const notice = detached && turn?.detachedNotice !== instance.instance;
|
|
301
|
+
// Once per turn (the turn's start, or the session's when no prompt was seen), and never a block.
|
|
302
|
+
const turnId = turn?.startedAt || 0;
|
|
303
|
+
const polling = (workspace || env("ROOT") === "1") && turn?.pollNudged !== turnId && pollsGithub(event.tool_name, event.tool_input);
|
|
275
304
|
if (!workspace) {
|
|
276
|
-
if (notice) { await save(path, { ...turn, detachedNotice: instance.instance }); emit(detachedNotice); }
|
|
305
|
+
if (notice || polling) { await save(path, { ...turn, ...(notice ? { detachedNotice: instance.instance } : {}), ...(polling ? { pollNudged: turnId } : {}) }); emit([notice ? detachedNotice : null, polling ? named(pollNudge) : null].filter(Boolean).join("\n\n")); }
|
|
277
306
|
return;
|
|
278
307
|
}
|
|
279
308
|
const tool = String(event.tool_name ?? "");
|
|
@@ -286,8 +315,8 @@ async function main() {
|
|
|
286
315
|
// sync record the RPC handler wrote rather than tool names.
|
|
287
316
|
const now = Date.now();
|
|
288
317
|
const callStart = turn?.lastToolAt || turn?.startedAt || now;
|
|
289
|
-
await save(path, { ...turn, startedAt: turn?.startedAt ?? (dirty ? callStart : 0), stopped: turn?.stopped ?? false, ...(dirty ? { dirtyAt: callStart } : {}), quietRevision, lastToolAt: now, ...(notice ? { detachedNotice: instance.instance } : {}) });
|
|
290
|
-
const text = [upgrade ? quietInstruction : null, notice ? detachedNotice : null].filter(Boolean).join("\n\n");
|
|
318
|
+
await save(path, { ...turn, startedAt: turn?.startedAt ?? (dirty ? callStart : 0), stopped: turn?.stopped ?? false, ...(dirty ? { dirtyAt: callStart } : {}), quietRevision, lastToolAt: now, ...(notice ? { detachedNotice: instance.instance } : {}), ...(polling ? { pollNudged: turnId } : {}) });
|
|
319
|
+
const text = [upgrade ? quietInstruction : null, notice ? detachedNotice : null, polling ? named(pollNudge) : null].filter(Boolean).join("\n\n");
|
|
291
320
|
if (text) emit(text);
|
|
292
321
|
return;
|
|
293
322
|
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { WriteBehind } from "./write-behind";
|
|
5
|
+
import type { MessageQueue, Resolution } from "./message-queue";
|
|
6
|
+
import type { State, Workspace } from "../shared/model";
|
|
7
|
+
import { WATCHES_PER_AGENT, checkWatchFileSchema, coveredByRepair, watchVerdict, type CheckWatch, type Verdict } from "../shared/check-watch";
|
|
8
|
+
|
|
9
|
+
export const WATCH_FILE = "check-watches.json";
|
|
10
|
+
export const checksItemId = (w: Pick<CheckWatch, "agentId" | "id">) => `checks:${w.agentId}:${w.id}`;
|
|
11
|
+
|
|
12
|
+
/** What the channel needs to know about the agent when the message goes: nothing here loads it. */
|
|
13
|
+
export type WatchAgent = { status: string; archived: boolean; workspaceId: string | null } | null;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Wait for checks (docs/wait-for-checks.md; shared/check-watch.ts holds the rules). The watches live in memory and
|
|
17
|
+
* save behind the reply (an-ack-never-waits-on-the-disk). `evaluate` runs after each engine pass on the state that pass
|
|
18
|
+
* wrote, so a watch costs no GitHub read of its own (waiting-for-checks-adds-no-github-read): its PR only counts as
|
|
19
|
+
* due at the running-checks cadence (`watched`). A verdict becomes one `checks` message on the queue
|
|
20
|
+
* (a-message-is-saved-before-sent-and-arrives-once), sent only to an agent that is neither closed nor archived
|
|
21
|
+
* (a-watch-never-wakes-a-closed-agent), and never beside a repair that carries the same failure
|
|
22
|
+
* (a-waited-for-failure-is-sent-once).
|
|
23
|
+
*/
|
|
24
|
+
export class CheckWatches {
|
|
25
|
+
private value: CheckWatch[] | null = null;
|
|
26
|
+
readonly persist: WriteBehind<{ version: 1; watches: CheckWatch[] }>;
|
|
27
|
+
private queue: MessageQueue | null = null;
|
|
28
|
+
/** Fired verdicts (for tests and the docs' counts). */
|
|
29
|
+
readonly fired: { watch: CheckWatch; verdict: Verdict; sent: boolean; why: string }[] = [];
|
|
30
|
+
constructor(readonly directory: string, private deps: {
|
|
31
|
+
snapshot: () => Promise<State>;
|
|
32
|
+
/** When the PR's content last changed (or Follow-up first saw it), from the reads already made; null: unknown. */
|
|
33
|
+
quietSince?: (prKey: string) => number | null;
|
|
34
|
+
agent: (agentId: string) => Promise<WatchAgent>;
|
|
35
|
+
now?: () => number;
|
|
36
|
+
}) {
|
|
37
|
+
this.persist = new WriteBehind({ path: join(directory, WATCH_FILE), encode: v => JSON.stringify(v) });
|
|
38
|
+
}
|
|
39
|
+
private now(): number { return (this.deps.now ?? Date.now)(); }
|
|
40
|
+
async flush(): Promise<void> { await this.persist.flush(); }
|
|
41
|
+
private async load(): Promise<CheckWatch[]> {
|
|
42
|
+
if (this.value) return this.value;
|
|
43
|
+
let watches: CheckWatch[];
|
|
44
|
+
try { watches = checkWatchFileSchema.parse(JSON.parse(await readFile(join(this.directory, WATCH_FILE), "utf8"))).watches; }
|
|
45
|
+
catch { watches = []; } // A lost file costs the agent a call again, never a broken worker.
|
|
46
|
+
// A worker that stopped mid-answer left the flag on: the call it belonged to is gone, so the watch messages now.
|
|
47
|
+
this.value ??= watches.map(w => w.answering ? { ...w, answering: false } : w);
|
|
48
|
+
return this.value;
|
|
49
|
+
}
|
|
50
|
+
private save(watches: CheckWatch[]): void {
|
|
51
|
+
this.value = watches;
|
|
52
|
+
this.persist.set({ version: 1, watches });
|
|
53
|
+
}
|
|
54
|
+
async list(agentId?: string): Promise<CheckWatch[]> {
|
|
55
|
+
const all = await this.load();
|
|
56
|
+
return agentId ? all.filter(w => w.agentId === agentId) : all;
|
|
57
|
+
}
|
|
58
|
+
/** PR key → when its oldest watch began: github.ts reads it at the running-checks cadence, and once after that time. */
|
|
59
|
+
watched(): Map<string, number> {
|
|
60
|
+
const out = new Map<string, number>();
|
|
61
|
+
for (const w of this.value ?? []) { const at = Date.parse(w.createdAt); out.set(w.prKey, Math.min(out.get(w.prKey) ?? at, at)); }
|
|
62
|
+
return out;
|
|
63
|
+
}
|
|
64
|
+
/** One watch per agent and PR: asking again restarts its clock and keeps what it learned. */
|
|
65
|
+
async add(input: { agentId: string; workspaceId: string; prKey: string; url: string; ms: number }): Promise<CheckWatch> {
|
|
66
|
+
const watches = await this.load();
|
|
67
|
+
const at = new Date(this.now());
|
|
68
|
+
const existing = watches.find(w => w.agentId === input.agentId && w.prKey === input.prKey);
|
|
69
|
+
if (!existing && watches.filter(w => w.agentId === input.agentId).length >= WATCHES_PER_AGENT) throw new Error(`You already wait on ${WATCHES_PER_AGENT} PRs. End your turn; Follow-up messages you as each finishes.`);
|
|
70
|
+
const watch: CheckWatch = { id: existing?.id ?? randomUUID(), agentId: input.agentId, workspaceId: input.workspaceId, prKey: input.prKey, url: input.url,
|
|
71
|
+
createdAt: at.toISOString(), until: new Date(at.getTime() + input.ms).toISOString(), answering: true, runningHead: existing?.runningHead ?? null };
|
|
72
|
+
this.save([...watches.filter(w => w !== existing), watch]);
|
|
73
|
+
return watch;
|
|
74
|
+
}
|
|
75
|
+
/** Ends the tool call's hold: a verdict it reported itself ends the watch; otherwise the watch messages later. */
|
|
76
|
+
async answered(id: string, ended: boolean): Promise<void> {
|
|
77
|
+
const watches = await this.load();
|
|
78
|
+
const next = ended ? watches.filter(w => w.id !== id) : watches.map(w => w.id === id && w.answering ? { ...w, answering: false } : w);
|
|
79
|
+
if (next.length !== watches.length || next.some((w, i) => w !== watches[i])) this.save(next);
|
|
80
|
+
}
|
|
81
|
+
async cancel(agentId: string, prKey?: string): Promise<number> {
|
|
82
|
+
const watches = await this.load();
|
|
83
|
+
const next = watches.filter(w => !(w.agentId === agentId && (!prKey || w.prKey === prKey)));
|
|
84
|
+
if (next.length !== watches.length) this.save(next);
|
|
85
|
+
return watches.length - next.length;
|
|
86
|
+
}
|
|
87
|
+
/** The verdict for one watch now, from the stored PR (the tool's immediate answer). */
|
|
88
|
+
async check(watch: CheckWatch): Promise<{ fire: Verdict | null; next: CheckWatch }> {
|
|
89
|
+
const state = await this.deps.snapshot();
|
|
90
|
+
const w = state.workspaces.find(x => x.id === watch.workspaceId);
|
|
91
|
+
return watchVerdict(watch, w?.prs.find(p => p.key === watch.prKey), this.now(), this.deps.quietSince?.(watch.prKey) ?? null);
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* After an engine pass: every watch on those workspaces (all when `ids` is absent) against the state the pass left.
|
|
95
|
+
* Pure reads of the snapshot; a verdict saves one queue item and drops the watch. Watches whose tool call is still
|
|
96
|
+
* answering are left to it.
|
|
97
|
+
*/
|
|
98
|
+
async evaluate(ids?: ReadonlySet<string>): Promise<void> {
|
|
99
|
+
const watches = await this.load();
|
|
100
|
+
if (!watches.length) return;
|
|
101
|
+
const state = await this.deps.snapshot();
|
|
102
|
+
const now = this.now();
|
|
103
|
+
let next: CheckWatch[] | null = null;
|
|
104
|
+
for (const watch of watches) {
|
|
105
|
+
if (watch.answering || ids && !ids.has(watch.workspaceId)) continue;
|
|
106
|
+
const w = state.workspaces.find(x => x.id === watch.workspaceId);
|
|
107
|
+
const pr = w && w.enable_tracking && !w.archived ? w.prs.find(p => p.key === watch.prKey) : undefined;
|
|
108
|
+
const { fire, next: updated } = watchVerdict(watch, pr, now, this.deps.quietSince?.(watch.prKey) ?? null);
|
|
109
|
+
if (!fire && updated === watch) continue;
|
|
110
|
+
next ??= [...watches];
|
|
111
|
+
const index = next.indexOf(watch);
|
|
112
|
+
if (!fire) { next[index] = updated; continue; }
|
|
113
|
+
next.splice(index, 1);
|
|
114
|
+
await this.deliver(watch, fire, w);
|
|
115
|
+
}
|
|
116
|
+
if (next) this.save(next);
|
|
117
|
+
}
|
|
118
|
+
private async deliver(watch: CheckWatch, verdict: Verdict, w: Workspace | undefined): Promise<void> {
|
|
119
|
+
if (verdict.kind === "failed" && w && coveredByRepair(w, watch.agentId, watch.prKey)) { this.fired.push({ watch, verdict, sent: false, why: "repair" }); return; }
|
|
120
|
+
// Closed or archived: the watch ends with nothing sent (a-watch-never-wakes-a-closed-agent). Unknown keeps the
|
|
121
|
+
// message; the channel checks again when it goes.
|
|
122
|
+
const agent = await this.deps.agent(watch.agentId).catch(() => null);
|
|
123
|
+
if (agent && (agent.archived || agent.status === "closed")) { this.fired.push({ watch, verdict, sent: false, why: agent.archived ? "archived" : "closed" }); return; }
|
|
124
|
+
if (!this.queue) { this.fired.push({ watch, verdict, sent: false, why: "no queue" }); return; }
|
|
125
|
+
this.queue.enqueue({ id: checksItemId(watch), kind: "checks", key: watch.workspaceId, ref: { agentId: watch.agentId, workspaceId: watch.workspaceId, prKey: watch.prKey },
|
|
126
|
+
messageId: `checks-${watch.id}-${Date.parse(watch.createdAt).toString(36)}`, text: verdict.text, priority: "now", state: "queued" });
|
|
127
|
+
this.fired.push({ watch, verdict, sent: true, why: "queued" });
|
|
128
|
+
}
|
|
129
|
+
/** The queue's `checks` channel: the agent is resolved when the message goes, never woken from closed or archived. */
|
|
130
|
+
attachQueue(queue: MessageQueue): void {
|
|
131
|
+
this.queue = queue;
|
|
132
|
+
queue.register("checks", {
|
|
133
|
+
resolve: async (item): Promise<Resolution> => {
|
|
134
|
+
let agent: WatchAgent;
|
|
135
|
+
try { agent = await this.deps.agent(item.ref.agentId!); }
|
|
136
|
+
catch { return { defer: "Paseo unreachable" }; }
|
|
137
|
+
if (!agent || agent.archived) return { cancel: "The agent was archived, so the checks result wasn't sent." };
|
|
138
|
+
if (agent.status === "closed") return { cancel: "The agent was closed, so the checks result wasn't sent (Follow-up never reopens it for this)." };
|
|
139
|
+
if (item.state === "queued" && ["running", "initializing"].includes(agent.status)) return { defer: "waits for the agent's turn to end" };
|
|
140
|
+
return { target: { workspaceId: agent.workspaceId, recipients: [item.ref.agentId!] } };
|
|
141
|
+
},
|
|
142
|
+
project: async () => undefined,
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
}
|
package/server/engine.ts
CHANGED
|
@@ -14,6 +14,7 @@ import { applyDiscovery, interruptionHold, startsWithAutoSend, type DiscoveredWo
|
|
|
14
14
|
import { ACTIVE_SCOPE_MIGRATION, followsByDefault, migrateActiveScope } from "../shared/settings";
|
|
15
15
|
import { replyRecorded } from "../shared/communication";
|
|
16
16
|
import { DeliveryDeferred, ConversationGone } from "./delivery";
|
|
17
|
+
import type { CheckWatches } from "./check-watches";
|
|
17
18
|
import type { MessageQueue, Resolution, Target } from "./message-queue";
|
|
18
19
|
import { PASEO_UNREACHABLE, deliveryOf, type NewQueueItem, type QueueItem, type QueueItemInput } from "../shared/queue";
|
|
19
20
|
import { recordSnapshot } from "./deployment-anchor";
|
|
@@ -253,12 +254,12 @@ export class Engine {
|
|
|
253
254
|
// sends). Before 2.0.1-beta.2 it read nothing, so a stale PR error there outlived every Refresh.
|
|
254
255
|
const asleep = o.workspaceId ? current.workspaces.find(w => w.id === o.workspaceId && w.enable_tracking && !w.archived && w.dormant) : undefined;
|
|
255
256
|
if (asleep) await this.refreshPrs(asleep);
|
|
256
|
-
if (!active.length) { this.error = null; return; }
|
|
257
|
+
if (!active.length) { await this.afterPass(o.affected); this.error = null; return; }
|
|
257
258
|
// Busy workspaces keep every-tick PR reads: their agent may push or answer review at any moment.
|
|
258
259
|
const keys = (ws: Workspace[]) => new Set(ws.flatMap(w => w.prs.map(p => p.key)));
|
|
259
260
|
const hot = keys(active.filter(isHot));
|
|
260
261
|
const read = o.affected ? active.filter(w => o.affected!.has(w.id)) : active;
|
|
261
|
-
const observations = await this.github.observe(read.flatMap(w => w.prs), o.background || o.workspaceId ? { background: true, hot, fresh: keys(active.filter(w => w.id === o.workspaceId)) } : {});
|
|
262
|
+
const observations = await this.github.observe(read.flatMap(w => w.prs), o.background || o.workspaceId ? { background: true, hot, fresh: keys(active.filter(w => w.id === o.workspaceId)), watched: this.checkWatches?.watched() } : {});
|
|
262
263
|
// A nudge observes only its workspaces (a-nudge-costs-its-workspace); the timer's tick observes every active one.
|
|
263
264
|
for (const original of o.affected ? read : active) {
|
|
264
265
|
if (this.stopped) return;
|
|
@@ -376,8 +377,18 @@ export class Engine {
|
|
|
376
377
|
this.observedPass.set(original.id, { w: after, runtime: runtimeKey, at: untouched ? last!.at : this.now(), dueAt: nextDue(after, this.now()) });
|
|
377
378
|
await this.statusCheck(after, this.now(), runtimeKey).catch(() => undefined);
|
|
378
379
|
}
|
|
380
|
+
await this.afterPass(o.affected);
|
|
379
381
|
this.error = null;
|
|
380
382
|
}
|
|
383
|
+
/**
|
|
384
|
+
* Wait for checks (server/check-watches.ts): agents waiting on a PR's checks hear from the reads this pass just made,
|
|
385
|
+
* never from a read of their own (waiting-for-checks-adds-no-github-read). A nudge's pass judges only its workspaces.
|
|
386
|
+
*/
|
|
387
|
+
checkWatches: Pick<CheckWatches, "watched" | "evaluate"> | null = null;
|
|
388
|
+
private async afterPass(affected?: ReadonlySet<string>): Promise<void> {
|
|
389
|
+
if (!this.checkWatches || this.stopped) return;
|
|
390
|
+
await this.checkWatches.evaluate(affected).catch(error => console.warn(`[follow-up] couldn't check the waits for checks: ${error instanceof Error ? error.message : String(error)}`));
|
|
391
|
+
}
|
|
381
392
|
/**
|
|
382
393
|
* A nudge's discovery (a-nudge-costs-its-workspace): only the nudged workspaces and their dirty agents (the kept turn
|
|
383
394
|
* read, else a read of that agent), each applied with a one-workspace mutation. 2026-11-13 (run Y, the CI live shape): every turn end's nudge ran
|
package/server/github.ts
CHANGED
|
@@ -241,6 +241,17 @@ export class Github {
|
|
|
241
241
|
this.budgets.set(owner, { remaining: rate.remaining, resetAt: Date.parse(rate.resetAt) || this.now() + 3_600_000, ...(typeof rate.limit === "number" ? { limit: rate.limit } : {}) });
|
|
242
242
|
this.stats.points += Number(rate.cost) || 0;
|
|
243
243
|
}
|
|
244
|
+
/**
|
|
245
|
+
* A rateLimit another reader saw for this owner's account (PR statistics, server/pr-stats-gate.ts): it moves the same
|
|
246
|
+
* budget this poller reads, so a burst either one sees throttles both (`stats-feed-the-shared-budget`). Its cost is
|
|
247
|
+
* not counted in `stats.points`, which measures the poller's own reads.
|
|
248
|
+
*/
|
|
249
|
+
noteRateLimit(owner: string, rate: { remaining?: number; resetAt?: string; limit?: number }): void {
|
|
250
|
+
if (typeof rate.remaining !== "number") return;
|
|
251
|
+
this.budgets.set(owner, { remaining: rate.remaining, resetAt: Date.parse(rate.resetAt ?? "") || this.now() + 3_600_000, ...(typeof rate.limit === "number" ? { limit: rate.limit } : {}) });
|
|
252
|
+
}
|
|
253
|
+
/** GitHub refused another reader for the limit: nothing on this account is read until `resetAt`. */
|
|
254
|
+
noteLimited(owner: string, resetAt: number): void { this.outOfBudget(owner, { resetAt }); }
|
|
244
255
|
private outOfBudget(owner: string, error: unknown): void {
|
|
245
256
|
this.budgets.set(owner, { remaining: 0, resetAt: (error as { resetAt?: number }).resetAt ?? this.now() + 10 * 60_000 });
|
|
246
257
|
}
|
|
@@ -257,7 +268,7 @@ export class Github {
|
|
|
257
268
|
* per account for every such PR, and read in full only when the probe saw a change that matters (`probeVerdict`).
|
|
258
269
|
* A fresh request (Refresh, opening the panel) and a foreground read (agent tools, actions) read in full.
|
|
259
270
|
*/
|
|
260
|
-
async observe(prs: Pr[], o: { background?: boolean; fresh?: Set<string>; hot?: Set<string> } = {}): Promise<Map<string, Observation>> {
|
|
271
|
+
async observe(prs: Pr[], o: { background?: boolean; fresh?: Set<string>; hot?: Set<string>; watched?: ReadonlyMap<string, number> } = {}): Promise<Map<string, Observation>> {
|
|
261
272
|
const result = new Map<string, Observation>();
|
|
262
273
|
const repositories = [...new Set(prs.map(p => p.repo))];
|
|
263
274
|
const modes = new Map<string, PrWorkflow>();
|
|
@@ -282,7 +293,7 @@ export class Github {
|
|
|
282
293
|
if (tier === "reserve" && o.background && !o.fresh?.has(p.key)) return false;
|
|
283
294
|
if (!o.background || !this.last.has(p.key) || o.fresh?.has(p.key) || o.hot?.has(p.key)) return true;
|
|
284
295
|
const last = this.last.get(p.key)!;
|
|
285
|
-
return dueForRead({ snapshot: last.snapshot, error: p.error || last.error, changedAt: this.changedAt.get(p.key) ?? null, readAt: this.readAt.get(p.key) ?? 0, now: this.now(), tier, repoUrgent, since: this.changedAt.get(p.key) ?? this.seenAt.get(p.key) ?? null });
|
|
296
|
+
return dueForRead({ snapshot: last.snapshot, error: p.error || last.error, changedAt: this.changedAt.get(p.key) ?? null, readAt: this.readAt.get(p.key) ?? 0, now: this.now(), tier, repoUrgent, since: this.changedAt.get(p.key) ?? this.seenAt.get(p.key) ?? null, watchedSince: o.watched?.get(p.key) ?? null });
|
|
286
297
|
});
|
|
287
298
|
const dueKeys = new Set(due.map(p => p.key));
|
|
288
299
|
for (const p of targets) if (!dueKeys.has(p.key)) { this.stats.skipped++; result.set(p.key, finalMerged(p) ? { snapshot: { ...p.snapshot! }, error: null } : this.standIn(p, owner)); }
|
|
@@ -434,6 +445,8 @@ export class Github {
|
|
|
434
445
|
* While Follow-up holds back reads on this repository's account for the budget (the reserve or less), when they
|
|
435
446
|
* resume (GitHub's reset); null when reads run. Feeds the workspace's "GitHub budget low" line (Workspace.githubWait).
|
|
436
447
|
*/
|
|
448
|
+
/** When this PR's content last changed, else when this worker first read it; null before any read (wait for checks' settle rule). */
|
|
449
|
+
quietSince(key: string): number | null { return this.changedAt.get(key) ?? this.seenAt.get(key) ?? null; }
|
|
437
450
|
waitUntil(repo: string): number | null {
|
|
438
451
|
const budget = this.budgets.get(repo.split("/")[0]);
|
|
439
452
|
const tier = budgetTier(budget, this.now());
|