paseo-follow-up 2.3.0 → 2.4.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/client/brief.tsx +7 -5
  2. package/client/header.tsx +18 -9
  3. package/client/home-list.tsx +3 -3
  4. package/client/home.tsx +3 -2
  5. package/client/merge-button.tsx +1 -1
  6. package/client/stacks.tsx +24 -2
  7. package/index.client.tsx +1 -1
  8. package/index.server.ts +42 -7
  9. package/package.json +2 -1
  10. package/server/agent-actions.ts +4 -3
  11. package/server/agent-hook.mjs +35 -6
  12. package/server/browser-bridge.ts +20 -2
  13. package/server/check-watches.ts +145 -0
  14. package/server/engine.ts +13 -2
  15. package/server/github.ts +15 -2
  16. package/server/hook-source.ts +35 -6
  17. package/server/mcp-source.ts +8 -5
  18. package/server/mcp.mjs +8 -5
  19. package/server/obligations.ts +18 -2
  20. package/server/pr-actions.ts +17 -11
  21. package/server/pr-owner.ts +30 -13
  22. package/server/pr-stats-gate.ts +102 -0
  23. package/server/pr-stats-store.ts +196 -0
  24. package/server/pr-stats-sync.ts +228 -0
  25. package/server/questions.ts +35 -8
  26. package/server/ranker.ts +3 -2
  27. package/server/wait-for-checks.ts +108 -0
  28. package/shared/activity.ts +2 -2
  29. package/shared/attention.ts +88 -15
  30. package/shared/brief.ts +16 -0
  31. package/shared/chat.ts +1 -1
  32. package/shared/check-watch.ts +129 -0
  33. package/shared/contracts.ts +10 -3
  34. package/shared/errors.ts +34 -0
  35. package/shared/home.ts +51 -13
  36. package/shared/model.ts +17 -2
  37. package/shared/poll.ts +9 -2
  38. package/shared/pr-actions.ts +61 -3
  39. package/shared/pr-stats-records.ts +169 -0
  40. package/shared/questions.ts +75 -0
  41. package/shared/queue.ts +1 -1
  42. package/shared/ranker.ts +3 -2
  43. package/shared/scale.ts +24 -0
  44. package/shared/status-invariants.ts +39 -1
  45. package/shared/task-status.ts +9 -2
@@ -0,0 +1,228 @@
1
+ import { FLAG, PAGE_COMMENTS, PAGE_REVIEWS, PAGE_TIMELINE, parseStatsRecord, STATS_PAGE_MIN, STATS_PAGE_SIZE, withAllReviews, type StatsRecord } from "../shared/pr-stats-records";
2
+ import type { GithubApi } from "./github-api";
3
+ import type { GateReason, RateLimit, StatsGate } from "./pr-stats-gate";
4
+ import { STATS_RECORDS_MAX, type RepoStats, type StatsStore } from "./pr-stats-store";
5
+
6
+ /**
7
+ * PR statistics' sync (docs/pr-stats.md, design §2.3): two walks over one keyset-paged query, every request through
8
+ * the gate (`StatsGate`, invariant `stats-never-spend-below-low`).
9
+ *
10
+ * - **Incremental**: from the newest PR down until `updatedAt < highWater − OVERLAP_S` (clock skew and same-second
11
+ * updates), then `highWater` = the newest updatedAt seen. Usually one page. Cut short by the gate, it resumes from
12
+ * its cursor next run and only then moves `highWater`, so nothing updated in between is skipped.
13
+ * - **Backfill**: continues from its saved cursor until `updatedAt < now − window` (90 days by default), at most
14
+ * `BACKFILL_PAGES_PER_RUN` pages a run, recording how far back it reached (`coveredTo`).
15
+ *
16
+ * GitHub's cursors on `orderBy: UPDATED_AT` encode the sort key, so a PR updated mid-walk jumps to the front (the next
17
+ * incremental pass reads it) without shifting the rest. A 502 or RESOURCE_LIMITS answer halves the page for that
18
+ * repository until a page succeeds. A PR with more than PAGE_REVIEWS reviews gets one follow-up read for all of them,
19
+ * `REVIEWS_BATCH` PRs per query by alias. Records older than the window are dropped at the end of every run, and past
20
+ * `STATS_RECORDS_MAX` the oldest go first.
21
+ */
22
+ export const OVERLAP_S = 120;
23
+ export const BACKFILL_PAGES_PER_RUN = 20;
24
+ export const INCREMENTAL_PAGES_PER_RUN = 20;
25
+ export const REVIEWS_BATCH = 10;
26
+ /** Reviews a follow-up reads per PR (the page reads PAGE_REVIEWS). */
27
+ export const REVIEWS_FOLLOW_UP = 100;
28
+ /** Consecutive failed pages before a run gives up (each one halves the page first). */
29
+ const FAILURES_PER_RUN = 3;
30
+
31
+ const PR_FIELDS = `number title createdAt updatedAt closedAt mergedAt state isDraft additions deletions changedFiles
32
+ author{login __typename} baseRefName headRefName
33
+ reviews(first:${PAGE_REVIEWS}){totalCount nodes{author{login __typename} state submittedAt}}
34
+ comments(first:${PAGE_COMMENTS}){totalCount nodes{createdAt author{login __typename}}}
35
+ timelineItems(first:${PAGE_TIMELINE},itemTypes:[READY_FOR_REVIEW_EVENT,CONVERT_TO_DRAFT_EVENT,REVIEW_REQUESTED_EVENT,REVIEW_REQUEST_REMOVED_EVENT]){pageInfo{hasNextPage} nodes{__typename
36
+ ...on ReadyForReviewEvent{createdAt}
37
+ ...on ConvertToDraftEvent{createdAt}
38
+ ...on ReviewRequestedEvent{createdAt requestedReviewer{__typename ...on User{login} ...on Bot{login} ...on Team{slug}}}
39
+ ...on ReviewRequestRemovedEvent{createdAt requestedReviewer{__typename ...on User{login} ...on Bot{login} ...on Team{slug}}}}}`;
40
+ /** The page query (design §2.2, measured at 1 point per page of 25). No bodies, no comment text, no diff. */
41
+ export function statsPageQuery(first: number, withCursor: boolean): string {
42
+ return `query($owner:String!,$name:String!${withCursor ? ",$after:String!" : ""}){rateLimit{cost remaining resetAt limit}
43
+ repository(owner:$owner,name:$name){defaultBranchRef{name}
44
+ pullRequests(first:${first}${withCursor ? ",after:$after" : ""},orderBy:{field:UPDATED_AT,direction:DESC}){pageInfo{hasNextPage endCursor} nodes{${PR_FIELDS}}}}}`;
45
+ }
46
+ /** All reviews of up to REVIEWS_BATCH PRs, one alias each. */
47
+ export function statsReviewsQuery(numbers: number[]): string {
48
+ const prs = numbers.map((n, i) => `p${i}:pullRequest(number:${n}){number reviews(first:${REVIEWS_FOLLOW_UP}){nodes{author{login __typename} state submittedAt}}}`).join(" ");
49
+ return `query($owner:String!,$name:String!){rateLimit{cost remaining resetAt limit} repository(owner:$owner,name:$name){${prs}}}`;
50
+ }
51
+
52
+ type Node = Record<string, any>;
53
+ export type SyncResult = {
54
+ repo: string;
55
+ /** Pages and follow-ups read, and the points they cost. */
56
+ pages: number; cost: number;
57
+ /** Records added or changed. */
58
+ changed: number;
59
+ /** Why it stopped before it was done (the gate), or null. */
60
+ waiting: { reason: GateReason; until: number | null } | null;
61
+ error: string | null;
62
+ backfillDone: boolean;
63
+ };
64
+ type Page = { nodes: Node[]; hasNext: boolean; endCursor: string | null; defaultBranch: string | null };
65
+
66
+ const seconds = (iso: unknown) => typeof iso === "string" && Number.isFinite(Date.parse(iso)) ? Math.floor(Date.parse(iso) / 1000) : null;
67
+ const status = (error: unknown): number | null => { const s = (error as { status?: unknown })?.status; return typeof s === "number" ? s : null; };
68
+ /** A failure that a smaller page may get past: a timeout (502/504) or GitHub's RESOURCE_LIMITS_EXCEEDED. */
69
+ export function tooBig(error: unknown): boolean {
70
+ const s = status(error);
71
+ return s === 502 || s === 504 || /RESOURCE_LIMITS|timeout|timed out|abort/i.test(String((error as { message?: string })?.message ?? ""));
72
+ }
73
+ class GraphqlError extends Error { constructor(message: string, readonly status: number | null) { super(message); } }
74
+
75
+ export class StatsSync {
76
+ private now: () => number;
77
+ constructor(private o: { api: GithubApi; gate: StatsGate; store: StatsStore; now?: () => number; log?: (line: string) => void }) { this.now = o.now ?? Date.now; }
78
+
79
+ /**
80
+ * One run for a repository: the incremental walk, review follow-ups, then backfill pages while the gate allows.
81
+ * Never throws: a read error is stored on the repository (`meta.error`) and returned.
82
+ */
83
+ async run(repo: string, o: { backfillPages?: number; incrementalPages?: number } = {}): Promise<SyncResult> {
84
+ const stats = await this.o.store.open(repo);
85
+ const result: SyncResult = { repo, pages: 0, cost: 0, changed: 0, waiting: null, error: null, backfillDone: stats.meta.backfill.done };
86
+ const meta = () => stats.meta;
87
+ const set = (patch: Partial<RepoStats["meta"]>) => { stats.meta = { ...stats.meta, ...patch }; };
88
+ let failures = 0;
89
+ /** One page through the gate; null when the gate is closed or the run should stop. */
90
+ const page = async (after: string | null): Promise<Page | null> => {
91
+ while (true) {
92
+ const size = meta().page;
93
+ let answer;
94
+ try {
95
+ answer = await this.o.gate.run(repo.split("/")[0]!, async () => {
96
+ const body = await this.o.api.graphql(repo, statsPageQuery(size, after !== null), { owner: repo.split("/")[0]!, name: repo.split("/")[1]!, ...(after !== null ? { after } : {}) });
97
+ return { value: body, rate: body?.data?.rateLimit as RateLimit | undefined };
98
+ });
99
+ } catch (error) {
100
+ failures++;
101
+ if (tooBig(error) && failures < FAILURES_PER_RUN) { set({ page: Math.max(STATS_PAGE_MIN, Math.floor(size / 2)) }); continue; }
102
+ if (tooBig(error)) set({ page: Math.max(STATS_PAGE_MIN, Math.floor(size / 2)) });
103
+ this.fail(stats, error, result);
104
+ return null;
105
+ }
106
+ if (!answer.ok) { result.waiting = { reason: answer.reason, until: answer.until }; return null; }
107
+ const body = answer.value as Node;
108
+ result.pages++; result.cost += Number(body?.data?.rateLimit?.cost) || 0;
109
+ const errors: Node[] = Array.isArray(body?.errors) ? body.errors : [];
110
+ if (errors.some(e => e?.type === "RESOURCE_LIMITS_EXCEEDED") && size > STATS_PAGE_MIN && failures + 1 < FAILURES_PER_RUN) { failures++; set({ page: Math.max(STATS_PAGE_MIN, Math.floor(size / 2)) }); continue; }
111
+ const connection = body?.data?.repository?.pullRequests;
112
+ if (!connection) {
113
+ const notFound = body?.data && body.data.repository === null;
114
+ this.fail(stats, new GraphqlError(notFound ? "not found or no access" : errors[0]?.message ?? "GitHub returned no pull requests", notFound ? 404 : null), result);
115
+ return null;
116
+ }
117
+ // A page that succeeded at a smaller size: back to the full page for the next run.
118
+ if (size !== STATS_PAGE_SIZE) set({ page: STATS_PAGE_SIZE });
119
+ failures = 0;
120
+ return { nodes: Array.isArray(connection.nodes) ? connection.nodes.filter(Boolean) : [], hasNext: !!connection.pageInfo?.hasNextPage, endCursor: connection.pageInfo?.endCursor ?? null, defaultBranch: body.data.repository.defaultBranchRef?.name ?? null };
121
+ }
122
+ };
123
+ const take = (p: Page, from: number) => {
124
+ const records: StatsRecord[] = [];
125
+ for (const node of p.nodes) {
126
+ const u = seconds(node.updatedAt);
127
+ if (u === null || u < from) continue;
128
+ try { records.push(parseStatsRecord(node)); } catch { /* a PR without times can't be counted */ }
129
+ }
130
+ result.changed += this.o.store.merge(stats, records);
131
+ const pending = new Set(meta().pendingReviews);
132
+ for (const r of records) if ((r.fl ?? 0) & FLAG.reviewsTruncated) pending.add(r.n);
133
+ if (p.defaultBranch !== meta().defaultBranch && p.defaultBranch) set({ defaultBranch: p.defaultBranch });
134
+ set({ pendingReviews: [...pending] });
135
+ };
136
+ const windowStart = () => Math.floor(this.now() / 1000) - meta().windowDays * 86_400;
137
+
138
+ try {
139
+ // Incremental (once the backfill has set a high-water mark).
140
+ if (meta().highWater !== null) {
141
+ const stop = meta().highWater! - OVERLAP_S;
142
+ let after = meta().incremental?.after ?? null, high = meta().incremental?.high ?? meta().highWater!;
143
+ for (let n = 0; n < (o.incrementalPages ?? INCREMENTAL_PAGES_PER_RUN); n++) {
144
+ const p = await page(after);
145
+ if (!p) break;
146
+ take(p, Math.max(stop, windowStart()));
147
+ for (const node of p.nodes) high = Math.max(high, seconds(node.updatedAt) ?? 0);
148
+ const reached = p.nodes.some(node => (seconds(node.updatedAt) ?? 0) < stop);
149
+ if (reached || !p.hasNext || !p.endCursor) { set({ highWater: high, incremental: null }); after = null; break; }
150
+ after = p.endCursor; set({ incremental: { after, high } });
151
+ }
152
+ }
153
+ if (!result.error && !result.waiting) await this.followUps(repo, stats, result);
154
+ // Backfill.
155
+ if (!result.error && !result.waiting && !meta().backfill.done) {
156
+ for (let n = 0; n < (o.backfillPages ?? BACKFILL_PAGES_PER_RUN); n++) {
157
+ const backfill = meta().backfill;
158
+ const p = await page(backfill.after);
159
+ if (!p) break;
160
+ const from = windowStart();
161
+ take(p, from);
162
+ if (meta().highWater === null) set({ highWater: Math.max(0, ...p.nodes.map(node => seconds(node.updatedAt) ?? 0)) });
163
+ const oldest = Math.min(...p.nodes.map(node => seconds(node.updatedAt) ?? Infinity));
164
+ const done = !p.hasNext || !p.endCursor || oldest < from;
165
+ set({ backfill: { after: done ? null : p.endCursor, done, coveredTo: done ? from : Number.isFinite(oldest) ? oldest : backfill.coveredTo } });
166
+ if (done) break;
167
+ }
168
+ result.backfillDone = meta().backfill.done;
169
+ if (!result.error && !result.waiting) await this.followUps(repo, stats, result);
170
+ }
171
+ if (!result.error && !result.waiting) set({ waiting: null });
172
+ if (!result.error && result.pages > 0) set({ error: null });
173
+ } finally {
174
+ this.retain(stats);
175
+ if (result.waiting) set({ waiting: { reason: result.waiting.reason, until: result.waiting.until === null ? null : Math.floor(result.waiting.until / 1000) } });
176
+ set({ lastSyncAt: Math.floor(this.now() / 1000), lastCost: result.cost, lastPages: result.pages });
177
+ this.o.store.save(stats);
178
+ }
179
+ return result;
180
+ }
181
+
182
+ /** Reads all reviews of PRs whose reviews ran past the page, REVIEWS_BATCH per query, through the gate. */
183
+ private async followUps(repo: string, stats: RepoStats, result: SyncResult): Promise<void> {
184
+ while (stats.meta.pendingReviews.length) {
185
+ const batch = stats.meta.pendingReviews.slice(0, REVIEWS_BATCH);
186
+ let answer;
187
+ try {
188
+ answer = await this.o.gate.run(repo.split("/")[0]!, async () => {
189
+ const body = await this.o.api.graphql(repo, statsReviewsQuery(batch), { owner: repo.split("/")[0]!, name: repo.split("/")[1]! });
190
+ return { value: body, rate: body?.data?.rateLimit as RateLimit | undefined };
191
+ });
192
+ } catch (error) { this.fail(stats, error, result); return; }
193
+ if (!answer.ok) { result.waiting = { reason: answer.reason, until: answer.until }; return; }
194
+ const body = answer.value as Node;
195
+ result.pages++; result.cost += Number(body?.data?.rateLimit?.cost) || 0;
196
+ const updated: StatsRecord[] = [];
197
+ batch.forEach((n, i) => {
198
+ const record = stats.records.get(n), node = body?.data?.repository?.[`p${i}`];
199
+ if (record && Array.isArray(node?.reviews?.nodes)) updated.push(withAllReviews(record, node.reviews.nodes));
200
+ });
201
+ result.changed += this.o.store.merge(stats, updated);
202
+ // A PR that came back without reviews (deleted, no access) isn't asked about again.
203
+ stats.meta = { ...stats.meta, pendingReviews: stats.meta.pendingReviews.slice(batch.length) };
204
+ }
205
+ }
206
+
207
+ /** Drops records older than the window, and the oldest past STATS_RECORDS_MAX. */
208
+ private retain(stats: RepoStats): void {
209
+ const from = Math.floor(this.now() / 1000) - stats.meta.windowDays * 86_400;
210
+ for (const [n, r] of stats.records) if (r.u < from) stats.records.delete(n);
211
+ if (stats.records.size > STATS_RECORDS_MAX) {
212
+ const sorted = [...stats.records.values()].sort((a, b) => b.u - a.u);
213
+ for (const r of sorted.slice(STATS_RECORDS_MAX)) stats.records.delete(r.n);
214
+ stats.meta = { ...stats.meta, cappedTo: sorted[STATS_RECORDS_MAX - 1]!.u, backfill: { after: null, done: true, coveredTo: sorted[STATS_RECORDS_MAX - 1]!.u } };
215
+ }
216
+ const kept = new Set(stats.meta.pendingReviews.filter(n => stats.records.has(n)));
217
+ if (kept.size !== stats.meta.pendingReviews.length) stats.meta = { ...stats.meta, pendingReviews: [...kept] };
218
+ }
219
+
220
+ private fail(stats: RepoStats, error: unknown, result: SyncResult): void {
221
+ const e = error as { message?: string; rateLimited?: boolean; resetAt?: number };
222
+ if (e?.rateLimited) { result.waiting = { reason: "budget", until: e.resetAt ?? null }; return; }
223
+ const message = e?.message ?? String(error);
224
+ result.error = message;
225
+ stats.meta = { ...stats.meta, error: { message, status: status(error), at: Math.floor(this.now() / 1000) } };
226
+ (this.o.log ?? console.warn)(`[follow-up] PR stats: reading ${stats.meta.repo} failed: ${message}`);
227
+ }
228
+ }
@@ -2,7 +2,7 @@ import { DEVELOPER, actorBy, type Actor } from "../shared/actor";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { blockedOnDeveloper, type Workspace } from "../shared/model";
4
4
  import { followUpObligations } from "../shared/follow-up";
5
- import { DISMISS_REASON, OTHER, OTHER_LABEL, QUESTION_MODE_RULES, choiceError, findDismissedMatch, findOpenMatch, isDismissed, isOpen, isOther, nextQuestionId, validChoice, type Question, type QuestionMode } from "../shared/questions";
5
+ import { DISMISS_REASON, OTHER, currentQuestion, findTaskCover, OTHER_LABEL, QUESTION_MODE_RULES, choiceError, findDismissedMatch, findOpenMatch, isDismissed, isOpen, isOther, nextQuestionId, validChoice, type Question, type QuestionMode } from "../shared/questions";
6
6
 
7
7
  /** "other" and its label both mean Something else, so an agent recording "Something else" lands on the same answer. */
8
8
  const normalChoice = (choice: string) => [OTHER, OTHER_LABEL.toLowerCase()].includes(choice.trim().toLowerCase()) ? OTHER : choice.trim();
@@ -173,23 +173,33 @@ export const answerRecipients = (w: Workspace, q: Question): string[] => [...new
173
173
 
174
174
  /**
175
175
  * A task blocked on the developer (blocked with an `ask`) gets a question without options that links back to it and
176
- * asks exactly that. A task blocked on anything else (a PR, another agent) asks nothing: it shows as Blocked in Tasks.
177
- * When the task leaves blocked, stops asking, or asks something else, its open question closes (a new ask gets a new
178
- * question). Invariant a-question-always-asks-the-developer-something.
176
+ * asks exactly that, unless a question already asks it (one-decision-one-card): one it names ("Q1: may I …?", or
177
+ * update_obligation question="Q1"), one asked with `task` set to it, or an open one that reads the same
178
+ * (`findTaskCover`). The task then records that question (`coveredBy`) and shows as waiting on it, and an open card it
179
+ * made before closes as "Already asked as Q1." An answered question keeps covering it while the ask is unchanged: the
180
+ * agent has the answer and moves the task. A task blocked on anything else (a PR, another agent) asks nothing: it shows
181
+ * as Blocked in Tasks. When the task leaves blocked, stops asking, or asks something else, its open question closes (a
182
+ * new ask gets a new question). Invariant a-question-always-asks-the-developer-something.
179
183
  */
180
184
  export function syncTaskQuestions(w: Workspace, now: number): boolean {
181
185
  let changed = false;
182
186
  const at = new Date(now).toISOString();
183
187
  for (const o of followUpObligations(w)) {
188
+ const ask = blockedOnDeveloper(o) ? o.ask!.trim() : null;
189
+ const cover = ask ? taskCover(w, o) : null;
190
+ if ((cover?.id ?? undefined) !== o.coveredBy) {
191
+ if (cover) o.coveredBy = cover.id; else delete o.coveredBy;
192
+ changed = true;
193
+ }
184
194
  const linked = w.questions.filter(q => q.taskId === o.id && q.taskRevision !== null);
185
195
  let open = linked.find(isOpen);
186
- const ask = blockedOnDeveloper(o) ? o.ask!.trim() : null;
187
- if (open && open.question !== ask) {
188
- open.closed = { at, by: null, reason: o.status === "done" || o.status === "waived" ? `The task was ${o.status === "done" ? "completed" : "waived"}.`
196
+ if (open && (cover || open.question !== ask)) {
197
+ open.closed = { at, by: null, reason: cover ? `Already ${cover.answer ? "answered" : "asked"} as ${cover.id}.`
198
+ : o.status === "done" || o.status === "waived" ? `The task was ${o.status === "done" ? "completed" : "waived"}.`
189
199
  : o.status !== "blocked" ? "The task is no longer blocked." : ask ? "The task asks something else now." : "The task waits on something other than you." };
190
200
  open = undefined; changed = true;
191
201
  }
192
- if (ask && !open && !linked.some(q => q.taskRevision === o.revision && q.question === ask)) {
202
+ if (ask && !cover && !open && !linked.some(q => q.taskRevision === o.revision && q.question === ask)) {
193
203
  w.questions.push({ id: nextQuestionId(w.questions), title: o.title.slice(0, 120), question: ask, options: [], recommend: null, big: null,
194
204
  background: null, links: [], prKey: null, taskId: o.id, taskRevision: o.revision, askedBy: w.mainAgentId, askedAt: at, mode: "work-around", answer: null, closed: null, via: "task" });
195
205
  changed = true;
@@ -198,6 +208,23 @@ export function syncTaskQuestions(w: Workspace, now: number): boolean {
198
208
  return changed;
199
209
  }
200
210
 
211
+ /** The question covering a task blocked on the developer: the one it recorded while that still stands, else a fresh look. */
212
+ function taskCover(w: Workspace, o: Workspace["obligations"][number]): Question | null {
213
+ const kept = o.coveredBy ? currentQuestion(w.questions, o.coveredBy) : null;
214
+ if (kept && kept.taskRevision === null) return kept;
215
+ return findTaskCover(o, w.questions, w.mainAgentId);
216
+ }
217
+
218
+ /** What update_obligation tells the agent when its blocked task is covered by a question: no second card was made. */
219
+ export function coverNote(w: Workspace, taskId: string): string | null {
220
+ const o = w.obligations.find(o => o.id === taskId);
221
+ const q = o?.coveredBy ? w.questions.find(q => q.id === o.coveredBy) : null;
222
+ if (!o || !q || !blockedOnDeveloper(o)) return null;
223
+ if (isDismissed(q)) return dismissedInstruction(q);
224
+ if (q.answer) return `Already answered as ${q.id}: the developer decided, and the answer is in this chat as "Follow-up answer ${q.id} …". No new card was made. Act on that answer and move this task (working, waiting or done) instead of keeping it blocked on it.`;
225
+ return `Already asked as ${q.id}: the task shows as waiting on it and no second card was made. Its answer arrives as "Follow-up answer ${q.id} …". At the turn's end point at it with needs_you questions=["${q.id}"], don't restate it.`;
226
+ }
227
+
201
228
  type NeedsYouDecision = { question: string; options?: { label: string; consequence?: string }[]; recommend?: number };
202
229
  /** A stored question as a needs_you decision, so the brief shows it with its own id, options and recommendation. */
203
230
  export function decisionOf(q: Question): NeedsYouDecision {
package/server/ranker.ts CHANGED
@@ -15,6 +15,7 @@ import {
15
15
  } from "../shared/ranker";
16
16
  import type { Priority } from "../shared/priorities";
17
17
  import type { WorkstreamRow } from "../shared/overseer";
18
+ import { truncated } from "../shared/scale";
18
19
 
19
20
  import { ghAccounts, githubApi, type AccountReads } from "./github-api";
20
21
  const exec = promisify(execFile);
@@ -125,10 +126,10 @@ export function parseReviewRequests(stdout: string): RankReview[] {
125
126
  export const planReplySchema = z.object({
126
127
  title: z.string().trim().max(200).nullable().catch(null).default(null),
127
128
  // Items as objects, or plain lines (models sometimes flatten them); anything else is dropped, not fatal.
128
- items: z.array(z.union([
129
+ items: truncated(z.union([
129
130
  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([]) }),
130
131
  z.string().trim().min(1).max(300).transform(title => ({ level: "item", title, keys: title.match(/\b[A-Z][A-Z0-9]+-\d+\b/g) ?? [] })),
131
- ]).nullable().catch(null)).max(120).transform(items => items.filter((i): i is { level: string; title: string; keys: string[] } => !!i).slice(0, 80)),
132
+ ]).nullable().catch(null), 120).transform(items => items.filter((i): i is { level: string; title: string; keys: string[] } => !!i).slice(0, 80)),
132
133
  });
133
134
  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 ACME-123]}]}. Focus on this week; at most 60 items. Never include share keys, links or raw HTML.";
134
135
 
@@ -0,0 +1,108 @@
1
+ import { WATCH_DEFAULT_MS, parsePrRef } from "../shared/check-watch";
2
+ import type { State, Workspace } from "../shared/model";
3
+ import type { CheckWatches } from "./check-watches";
4
+
5
+ /** How long the tool waits for its own workspace's nudged read before it answers from what it has. */
6
+ export const ANSWER_READ_MS = 8_000;
7
+
8
+ type Input = { agentId: string; prs?: string[]; minutes?: number; cancel?: boolean };
9
+ type Deps = {
10
+ state: () => Promise<State>;
11
+ watches: Pick<CheckWatches, "add" | "answered" | "cancel" | "check">;
12
+ /** The engine's nudge of one workspace: its PRs read with the usual backoff (a watched PR is due once). */
13
+ nudge: (workspaceId: string) => Promise<void>;
14
+ hostVersion: () => Promise<string>;
15
+ /** The caller's workspace as Paseo knows it (for an untracked caller's wording only). */
16
+ callerWorkspace?: () => Promise<string | null>;
17
+ /** register_pr's own path, for the caller's PR that Follow-up doesn't follow yet. */
18
+ register?: (repo: string, number: number) => Promise<unknown>;
19
+ readMs?: number;
20
+ };
21
+ type Answer = { text: string; waiting: string[]; done: { pr: string; result: string; text: string }[]; notFollowed: string[] };
22
+
23
+ /** Paseo 0.17 serves subscribe_change_request; the version is the only sign (server_info has no feature flag for it). */
24
+ export function hostWatches(version: string): boolean {
25
+ const m = /^(\d+)\.(\d+)/.exec(version);
26
+ return !!m && (Number(m[1]) > 0 || Number(m[2]) >= 17);
27
+ }
28
+ export function unseenAdvice(version: string): string {
29
+ return hostWatches(version)
30
+ ? "Paseo can watch it instead: call subscribe_change_request with the PR's URL and end your turn; Paseo messages you when its checks finish."
31
+ : "End your turn and check it once later (a single gh pr checks), never in a loop.";
32
+ }
33
+ const ownerOf = (state: State, agentId: string): Workspace | undefined =>
34
+ state.workspaces.find(w => w.enable_tracking && !w.archived && (w.mainAgentId === agentId || w.contributorAgentIds?.includes(agentId)));
35
+ const open = (w: Workspace) => w.prs.filter(p => p.snapshot?.state !== "MERGED" && p.snapshot?.state !== "CLOSED");
36
+
37
+ /**
38
+ * wait_for_checks: one watch per PR, answered at once from Follow-up's own read of the caller's workspace (the engine's
39
+ * nudge: a probe for a PR read before), then one message after the turn when the checks finish
40
+ * (docs/wait-for-checks.md). Scoped to the caller's own workspace; PRs Follow-up can't see are named with the way on.
41
+ */
42
+ export async function waitForChecksAnswer(input: Input, deps: Deps): Promise<Answer> {
43
+ const state = await deps.state();
44
+ const w = ownerOf(state, input.agentId);
45
+ const refs = input.prs ?? [];
46
+ if (input.cancel) {
47
+ let n = 0;
48
+ if (!refs.length) n = await deps.watches.cancel(input.agentId);
49
+ else for (const ref of refs) { const key = keyFor(w, ref); if (key) n += await deps.watches.cancel(input.agentId, key); }
50
+ return { text: n ? `Stopped waiting on ${n} PR${n === 1 ? "" : "s"}.` : "You weren't waiting on any of those.", waiting: [], done: [], notFollowed: [] };
51
+ }
52
+ if (!w) {
53
+ const advice = unseenAdvice(await deps.hostVersion());
54
+ return { text: `Follow-up doesn't follow this workspace, so it can't tell you when checks finish. ${advice}`, waiting: [], done: [], notFollowed: refs.length ? refs : ["this workspace's PRs"] };
55
+ }
56
+ const notFollowed: string[] = [];
57
+ const reasons: string[] = [];
58
+ const keys: string[] = [];
59
+ if (!refs.length) keys.push(...open(w).map(p => p.key));
60
+ for (const ref of refs) {
61
+ const parsed = parsePrRef(ref);
62
+ if (!parsed) { notFollowed.push(ref); reasons.push(`"${ref}" isn't a PR URL, owner/repo#N or number.`); continue; }
63
+ if (parsed.forge === "other") { notFollowed.push(ref); continue; }
64
+ const matches = parsed.repo ? w.prs.filter(p => p.key.toLowerCase() === `${parsed.repo}#${parsed.number}`.toLowerCase()) : w.prs.filter(p => p.number === parsed.number);
65
+ if (matches.length === 1) { keys.push(matches[0].key); continue; }
66
+ if (!parsed.repo) { notFollowed.push(ref); reasons.push(matches.length ? `#${parsed.number} is ambiguous here; use owner/repo#${parsed.number}.` : `#${parsed.number} isn't one of this workspace's PRs.`); continue; }
67
+ // The caller's own PR, not registered yet: register it as register_pr would (its stack can be fixed later).
68
+ if (deps.register) {
69
+ try { await deps.register(parsed.repo, parsed.number); keys.push(`${parsed.repo}#${parsed.number}`); continue; }
70
+ catch (error) { reasons.push(`${parsed.repo}#${parsed.number}: ${error instanceof Error ? error.message : String(error)}`); }
71
+ }
72
+ notFollowed.push(ref);
73
+ }
74
+ const unique = [...new Set(keys)];
75
+ if (!unique.length) {
76
+ const advice = notFollowed.length ? ` ${unseenAdvice(await deps.hostVersion())}` : "";
77
+ return { text: (refs.length ? `Follow-up doesn't follow ${notFollowed.join(", ")}.${reasons.length ? " " + reasons.join(" ") : ""}` : "This workspace has no open PRs Follow-up follows. Register yours with register_pr, then call again.") + advice, waiting: [], done: [], notFollowed };
78
+ }
79
+ const ms = (input.minutes ?? WATCH_DEFAULT_MS / 60_000) * 60_000;
80
+ const urls = new Map((await deps.state()).workspaces.find(x => x.id === w.id)?.prs.map(p => [p.key, p.snapshot?.url ?? ""]) ?? []);
81
+ const watches = [];
82
+ for (const key of unique) watches.push(await deps.watches.add({ agentId: input.agentId, workspaceId: w.id, prKey: key, url: urls.get(key) ?? "", ms }));
83
+ // One read of this workspace's due PRs (each watched PR is due once after its wait began), bounded: past it the
84
+ // watch answers by message like any other.
85
+ let timer: ReturnType<typeof setTimeout> | undefined;
86
+ await Promise.race([deps.nudge(w.id).catch(() => undefined), new Promise<void>(resolve => { timer = setTimeout(resolve, deps.readMs ?? ANSWER_READ_MS); })]);
87
+ clearTimeout(timer);
88
+ const done: Answer["done"] = [];
89
+ const waiting: string[] = [];
90
+ for (const watch of watches) {
91
+ const { fire } = await deps.watches.check(watch).catch(() => ({ fire: null }));
92
+ await deps.watches.answered(watch.id, !!fire);
93
+ if (fire) done.push({ pr: watch.prKey, result: fire.kind, text: fire.text });
94
+ else waiting.push(watch.prKey);
95
+ }
96
+ const lines = [
97
+ ...done.map(d => d.text),
98
+ waiting.length ? `Waiting on ${waiting.join(", ")}. End your turn now: Follow-up sends you one message when the checks on the current head finish (or it merges, closes or conflicts), from the reads it already makes. Don't poll GitHub meanwhile.` : null,
99
+ notFollowed.length ? `Not followed by Follow-up: ${notFollowed.join(", ")}.${reasons.length ? " " + reasons.join(" ") : ""} ${unseenAdvice(await deps.hostVersion())}` : null,
100
+ ].filter(Boolean);
101
+ return { text: lines.join("\n"), waiting, done, notFollowed };
102
+ }
103
+ function keyFor(w: Workspace | undefined, ref: string): string | null {
104
+ const parsed = parsePrRef(ref);
105
+ if (!parsed) return null;
106
+ if (parsed.repo) return `${parsed.repo}#${parsed.number}`;
107
+ return w?.prs.find(p => p.number === parsed.number)?.key ?? null;
108
+ }
@@ -1,7 +1,7 @@
1
1
  import type { ListWorkspace as Workspace } from "./list";
2
2
  import { recoveryBatch } from "./follow-up";
3
3
  import { shortRefs } from "./attention";
4
- import { isGithubFlow } from "./pr-actions";
4
+ import { isGithubFlow, prRefs } from "./pr-actions";
5
5
  import { answerLabel, answerStatus, closedLine } from "./questions";
6
6
 
7
7
  export type ActivityTone = "merged" | "success" | "warning" | "danger" | "muted";
@@ -44,7 +44,7 @@ export function activity(w: Workspace): Activity[] {
44
44
  for (const a of w.prActions) {
45
45
  // Say a merge once: when every PR it merged has its own "#N merged" row, the action's "Merged …" row would repeat it.
46
46
  if (a.kind === "merge" && a.merge === "merged" && a.prs.every(key => { const s = w.prs.find(p => p.key === key)?.snapshot; return s?.state === "MERGED" && !!s.mergedAt; })) continue;
47
- const numbers = a.prs.map(key => `#${key.split("#")[1]}`).join(", ");
47
+ const numbers = prRefs(a.prs.map(key => key.split("#")[1]));
48
48
  const toggle = isGithubFlow(w.prs.find(p => p.key === a.prs[0])?.snapshot) ? "Auto-merge" : "Merge when ready";
49
49
  // The same outcome the button and toast said (mergeWords): Merged only when GitHub merged.
50
50
  const what = a.kind === "merge" ? a.merge === "merged" ? `Merged ${numbers}` : a.merge === "queued" ? `Queued ${numbers.split(", ")[0]} to merge` : `Merge requested for ${numbers}` : a.kind === "request_reviewers" ? `Reviewers requested on ${numbers}` : a.kind === "enable_mwr" ? `${toggle} on for ${numbers}` : `${toggle} off for ${numbers}`;