paseo-follow-up 0.3.6 → 0.4.0

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 (63) hide show
  1. package/OVERVIEW.md +19 -7
  2. package/README.md +70 -79
  3. package/THIRD_PARTY_NOTICES.md +33 -0
  4. package/assets/LICENSE.lucide +43 -0
  5. package/assets/icon.png +0 -0
  6. package/assets/icon.svg +1 -0
  7. package/client/button-visibility.ts +2 -1
  8. package/client/chat.tsx +163 -0
  9. package/client/display.tsx +12 -17
  10. package/client/header.tsx +92 -0
  11. package/client/keys.ts +3 -0
  12. package/client/kit.tsx +119 -0
  13. package/client/large.tsx +58 -0
  14. package/client/live.tsx +159 -0
  15. package/client/motion.tsx +93 -0
  16. package/client/needs-you.tsx +121 -0
  17. package/client/overview.tsx +111 -16
  18. package/client/panel.tsx +257 -68
  19. package/client/pr-controls.tsx +50 -33
  20. package/client/pr-sheet.tsx +63 -0
  21. package/client/questions.tsx +307 -0
  22. package/client/settings.tsx +55 -20
  23. package/client/spec.tsx +113 -0
  24. package/client/stacks.tsx +128 -0
  25. package/client/tasks.tsx +113 -22
  26. package/client/theme.ts +69 -0
  27. package/docs/screenshots/follow-up-chat.png +0 -0
  28. package/docs/screenshots/follow-up-hero.png +0 -0
  29. package/docs/screenshots/follow-up-large.png +0 -0
  30. package/docs/screenshots/follow-up-mobile.png +0 -0
  31. package/docs/screenshots/follow-up-overview.png +0 -0
  32. package/docs/screenshots/follow-up-pill.png +0 -0
  33. package/docs/screenshots/follow-up-pr.png +0 -0
  34. package/docs/screenshots/follow-up-questions.png +0 -0
  35. package/docs/screenshots/follow-up-states.png +0 -0
  36. package/index.client.tsx +47 -16
  37. package/index.server.ts +53 -0
  38. package/package.json +4 -2
  39. package/paseo-plugin.json +11 -3
  40. package/server/agent-hook.mjs +2 -0
  41. package/server/daemon.ts +37 -6
  42. package/server/discovery.ts +6 -3
  43. package/server/engine.ts +39 -0
  44. package/server/hook-source.ts +1 -1
  45. package/server/mcp-source.ts +1 -1
  46. package/server/mcp.mjs +12 -2
  47. package/server/questions.ts +112 -0
  48. package/server/spec.ts +102 -0
  49. package/shared/activity.ts +56 -0
  50. package/shared/attention.ts +212 -0
  51. package/shared/chat.ts +130 -0
  52. package/shared/contracts.ts +21 -0
  53. package/shared/display.ts +2 -1
  54. package/shared/errors.ts +5 -0
  55. package/shared/model.ts +10 -0
  56. package/shared/pr-actions.ts +8 -1
  57. package/shared/questions.ts +123 -0
  58. package/shared/spec.ts +46 -0
  59. package/skills/follow-through/SKILL.md +4 -0
  60. package/client/components.tsx +0 -58
  61. package/client/navigation.tsx +0 -23
  62. package/docs/screenshots/follow-up-settings.png +0 -0
  63. package/docs/screenshots/follow-up-workspace.png +0 -0
package/server/spec.ts ADDED
@@ -0,0 +1,102 @@
1
+ import type { Workspace } from "../shared/model";
2
+ import { MAX_ARTIFACTS, isClaudeArtifact, validSpecUrl, type Artifact } from "../shared/spec";
3
+
4
+ type Entry = { item: unknown; timestamp?: string };
5
+ const publishReceipt = /^(?:Published \S.*? at|Created a new Artifact at) (https:\/\/claude\.ai\/(?:code\/)?artifact\/[\w-]+)(?=[\s(.,]|$)/;
6
+
7
+ function resultText(output: unknown): string | null {
8
+ if (typeof output === "string") return output;
9
+ if (Array.isArray(output)) {
10
+ const text = output.map(part => (part && typeof part === "object" && typeof (part as { text?: unknown }).text === "string" ? (part as { text: string }).text : "")).join("");
11
+ return text || null;
12
+ }
13
+ if (output && typeof output === "object" && typeof (output as { text?: unknown }).text === "string") return (output as { text: string }).text;
14
+ return null;
15
+ }
16
+
17
+ function titleFrom(input: Record<string, unknown>): string | null {
18
+ if (typeof input.title === "string" && input.title.trim()) return input.title.trim().slice(0, 120);
19
+ const path = typeof input.file_path === "string" ? input.file_path : null;
20
+ const base = path?.split(/[\\/]/).pop()?.replace(/\.(?:html?|md)$/i, "").replace(/[-_]+/g, " ").trim();
21
+ if (!base || /^(?:index|page|artifact)$/i.test(base)) return null;
22
+ return (base[0].toUpperCase() + base.slice(1)).slice(0, 120);
23
+ }
24
+
25
+ /**
26
+ * Claude artifacts this session published, from completed Artifact tool receipts only. Reads, lists,
27
+ * quickstarts and asset uploads also mention artifact links and never count; neither do links in chat.
28
+ */
29
+ export function publishedArtifacts(entries: readonly Entry[], agentId: string): Artifact[] {
30
+ const found = new Map<string, Artifact>();
31
+ for (const entry of entries) {
32
+ const v = entry.item as { type?: string; name?: string; status?: string; error?: unknown; detail?: { type?: string; input?: unknown; output?: unknown } } | null;
33
+ if (!v || v.type !== "tool_call" || v.name !== "Artifact" || v.status !== "completed" || v.error) continue;
34
+ const input = (v.detail?.input && typeof v.detail.input === "object" ? v.detail.input : {}) as Record<string, unknown>;
35
+ if ((input.action ?? "publish") !== "publish" || input.asset === true) continue;
36
+ const match = publishReceipt.exec(resultText(v.detail?.output)?.trimStart() ?? "");
37
+ if (!match || !isClaudeArtifact(match[1])) continue;
38
+ const at = typeof entry.timestamp === "string" ? entry.timestamp : null;
39
+ const previous = found.get(match[1]);
40
+ found.set(match[1], {
41
+ url: match[1], title: titleFrom(input) ?? previous?.title ?? null, by: agentId,
42
+ firstAt: previous?.firstAt ?? at, lastAt: at ?? previous?.lastAt ?? null, publishes: (previous?.publishes ?? 0) + 1,
43
+ });
44
+ }
45
+ return [...found.values()];
46
+ }
47
+
48
+ const later = (a: string | null, b: string | null) => (a ?? "").localeCompare(b ?? "");
49
+
50
+ /** Keeps the workspace's artifact list current. Newer scans replace what they cover; others stay. */
51
+ export function mergeArtifacts(w: Workspace, scanned: Artifact[], now = Date.now()): boolean {
52
+ const byUrl = new Map<string, Artifact>();
53
+ for (const a of scanned) {
54
+ const seen = byUrl.get(a.url);
55
+ byUrl.set(a.url, seen ? { ...seen, publishes: seen.publishes + a.publishes, title: seen.title ?? a.title, firstAt: [seen.firstAt, a.firstAt].filter(Boolean).sort()[0] ?? null, lastAt: [seen.lastAt, a.lastAt].sort(later).at(-1) ?? null, by: a.by === w.mainAgentId ? a.by : seen.by } : a);
56
+ }
57
+ const next = [...byUrl.values(), ...w.artifacts.filter(a => !byUrl.has(a.url))]
58
+ .sort((a, b) => later(b.lastAt, a.lastAt)).slice(0, MAX_ARTIFACTS);
59
+ const changed = JSON.stringify(next) !== JSON.stringify(w.artifacts);
60
+ w.artifacts = next;
61
+ return chooseDetectedSpec(w, now) || changed;
62
+ }
63
+
64
+ /**
65
+ * When neither the developer nor the main agent chose a spec, the main agent's most republished
66
+ * artifact is the spec (a spec gets updated; one-off pages don't), newest first on ties.
67
+ */
68
+ export function chooseDetectedSpec(w: Workspace, now = Date.now()): boolean {
69
+ if (w.spec && w.spec.source !== "detected") return false;
70
+ const ranked = [...w.artifacts].sort((a, b) =>
71
+ Number(b.by === w.mainAgentId) - Number(a.by === w.mainAgentId) || b.publishes - a.publishes || later(b.lastAt, a.lastAt));
72
+ const best = ranked[0];
73
+ if (!best) return false;
74
+ if (w.spec?.url === best.url && w.spec.title === best.title) return false;
75
+ w.spec = { url: best.url, title: best.title, source: "detected", by: best.by, at: best.lastAt ?? new Date(now).toISOString() };
76
+ return true;
77
+ }
78
+
79
+ /** set_spec from the main agent. A link the developer set or removed stays theirs. */
80
+ export function agentSetSpec(w: Workspace, agentId: string, url: string, title: string | undefined, now: number): { applied: boolean; message: string } {
81
+ if (w.mainAgentId !== agentId) throw new Error("Only this workspace's main agent can set the spec link.");
82
+ const valid = validSpecUrl(url);
83
+ if (!valid) throw new Error("Use the spec's full https:// link, such as the Claude artifact URL from your publish result.");
84
+ if (w.spec?.source === "developer") return { applied: false, message: w.spec.url ? "The developer chose this workspace's spec link in Follow-up, so it stays. Nothing to do." : "The developer removed the spec link in Follow-up, so it stays off. Nothing to do." };
85
+ w.spec = { url: valid, title: title?.trim().slice(0, 120) || w.artifacts.find(a => a.url === valid)?.title || null, source: "agent", by: agentId, at: new Date(now).toISOString() };
86
+ return { applied: true, message: "Spec link saved. It shows in Follow-up's header. Keep republishing to the same URL; call set_spec again only if the link changes." };
87
+ }
88
+
89
+ /** The developer sets, removes, or hands the link back to agents and detection. */
90
+ export function developerSetSpec(w: Workspace, input: { action: "set"; url: string; title?: string | null } | { action: "remove" } | { action: "reset" }, now: number): void {
91
+ const at = new Date(now).toISOString();
92
+ if (input.action === "set") {
93
+ const url = validSpecUrl(input.url);
94
+ if (!url) throw new Error("Enter a full https:// link.");
95
+ w.spec = { url, title: input.title?.trim().slice(0, 120) || w.artifacts.find(a => a.url === url)?.title || null, source: "developer", by: null, at };
96
+ } else if (input.action === "remove") {
97
+ w.spec = { url: null, title: null, source: "developer", by: null, at };
98
+ } else {
99
+ w.spec = null;
100
+ chooseDetectedSpec(w, now);
101
+ }
102
+ }
@@ -0,0 +1,56 @@
1
+ import type { Workspace } from "./model";
2
+ import { recoveryBatch } from "./follow-up";
3
+ import { shortRefs } from "./attention";
4
+
5
+ export type ActivityTone = "merged" | "success" | "warning" | "danger" | "muted";
6
+ export type Activity = { key: string; at: string; icon: string; tone: ActivityTone; text: string; detail: string | null; took: string | null };
7
+
8
+ const plural = (n: number, one: string) => `${n} ${one}${n === 1 ? "" : "s"}`;
9
+ /** "12m", "1h 05m", "3d": how long something took, for the activity log. */
10
+ export function duration(from: string | null | undefined, to: string | null | undefined): string | null {
11
+ const ms = Date.parse(to ?? "") - Date.parse(from ?? "");
12
+ if (!Number.isFinite(ms) || ms < 0) return null;
13
+ const m = Math.round(ms / 60_000);
14
+ if (m < 1) return "under a minute";
15
+ if (m < 60) return `${m}m`;
16
+ const h = Math.floor(m / 60);
17
+ if (h < 24) return m % 60 ? `${h}h ${m % 60}m` : `${h}h`;
18
+ return `${Math.floor(h / 24)}d`;
19
+ }
20
+
21
+ /**
22
+ * What happened in this workspace, newest first, from what Follow-up already stores: repairs sent
23
+ * and finished (with how long they took), PR merges, merge and reviewer actions, questions and Done.
24
+ */
25
+ export function activity(w: Workspace): Activity[] {
26
+ const rows: Activity[] = [];
27
+ for (const b of w.batches) {
28
+ if (recoveryBatch(b)) {
29
+ if (b.sentAt) rows.push({ key: `recovery:${b.id}`, at: b.settledAt ?? b.sentAt, icon: "History", tone: b.state === "completed" ? "success" : b.state === "sent" ? "muted" : "warning", text: b.state === "completed" ? "Recovery finished" : b.state === "sent" ? "Recovery started" : "Recovery needs a check", detail: b.result || null, took: b.settledAt ? duration(b.sentAt, b.settledAt) : null });
30
+ continue;
31
+ }
32
+ if (!b.sentAt) continue;
33
+ const n = plural(b.tasks.length, "repair");
34
+ rows.push({ key: `sent:${b.id}`, at: b.sentAt, icon: "Send", tone: "muted", text: `Sent ${n} to the main agent`, detail: b.tasks.map(t => shortRefs(t.title, w)).join(" · "), took: null });
35
+ if (b.settledAt && b.state === "completed") rows.push({ key: `done:${b.id}`, at: b.settledAt, icon: "Wrench", tone: "success", text: `Main agent finished ${n}`, detail: b.result || null, took: duration(b.sentAt, b.settledAt) });
36
+ else if (b.settledAt && ["blocked", "cancelled"].includes(b.state)) rows.push({ key: `stopped:${b.id}`, at: b.settledAt, icon: "OctagonAlert", tone: b.state === "blocked" ? "danger" : "muted", text: b.state === "blocked" ? `${n} didn't finish` : `${n} cancelled`, detail: b.result || null, took: duration(b.sentAt, b.settledAt) });
37
+ }
38
+ for (const p of w.prs) if (p.snapshot?.state === "MERGED" && p.snapshot.mergedAt)
39
+ rows.push({ key: `merged:${p.key}`, at: p.snapshot.mergedAt, icon: "GitMerge", tone: "merged", text: `#${p.number} merged`, detail: p.snapshot.title, took: null });
40
+ for (const a of w.prActions) {
41
+ const numbers = a.prs.map(key => `#${key.split("#")[1]}`).join(", ");
42
+ const what = a.kind === "merge" ? `Merge requested for ${numbers}` : a.kind === "request_reviewers" ? `Reviewers requested on ${numbers}` : a.kind === "enable_mwr" ? `Merge when ready on for ${numbers}` : `Merge when ready off for ${numbers}`;
43
+ rows.push({ key: `action:${a.id}`, at: a.createdAt, icon: a.kind === "request_reviewers" ? "UserPlus" : "GitMerge", tone: a.state === "failed" ? "danger" : a.state === "uncertain" ? "warning" : "muted", text: what, detail: a.state === "submitted" ? null : a.result || null, took: null });
44
+ }
45
+ for (const q of w.questions ?? []) {
46
+ const ref = `${q.id} · ${q.title}`;
47
+ rows.push({ key: `asked:${q.id}`, at: q.askedAt, icon: "MessageCircleQuestion", tone: "warning", text: ref, detail: "Asked", took: null });
48
+ if (q.answer) {
49
+ const option = q.options.find(o => o.letter === q.answer!.choice);
50
+ rows.push({ key: `answered:${q.id}`, at: q.answer.at, icon: "MessageCircleReply", tone: "success", text: ref, detail: `${q.answer.by === "agent" ? "Answered in chat" : "Answered"}: ${q.answer.choice}${option ? ` · ${option.label}` : ""}`, took: duration(q.askedAt, q.answer.at) });
51
+ }
52
+ if (q.closed) rows.push({ key: `withdrawn:${q.id}`, at: q.closed.at, icon: "MessageCircleOff", tone: "muted", text: ref, detail: `Withdrawn: ${q.closed.reason}`, took: null });
53
+ }
54
+ if (w.completion) rows.push({ key: "done", at: w.completion.declaredAt, icon: "CircleCheck", tone: "success", text: "Main agent declared Done", detail: null, took: null });
55
+ return rows.filter(r => Number.isFinite(Date.parse(r.at))).sort((a, b) => Date.parse(b.at) - Date.parse(a.at) || a.key.localeCompare(b.key));
56
+ }
@@ -0,0 +1,212 @@
1
+ import { summary, type Batch, type Pr, type Workspace, type Status } from "./model";
2
+ import { followUpObligations, recoveryBatch } from "./follow-up";
3
+ import { orderedStacks, settledForDisplay } from "./presentation";
4
+ import { graphiteReady, prActionBlocks } from "./pr-actions";
5
+ import { defaultReviewers, noReviewers } from "./reviewers";
6
+ import { isOpen as questionOpen, questionState, type QuestionState } from "./questions";
7
+
8
+ /** One colour language for the stack bar, rail nodes and overview bars. */
9
+ export type PrTone = "merged" | "approved" | "danger" | "warning" | "pending" | "draft" | "closed" | "unknown";
10
+
11
+ export function prTone(pr: Pr): PrTone {
12
+ const s = pr.snapshot;
13
+ if (pr.error || !s?.complete) return "unknown";
14
+ if (s.state === "MERGED") return "merged";
15
+ if (s.state === "CLOSED") return "closed";
16
+ if (s.conflict || s.failedChecks.length) return "danger";
17
+ if (s.threads.length || s.reviewDecision === "CHANGES_REQUESTED" || s.otherFailedChecks?.length) return "warning";
18
+ if (s.draft) return "draft";
19
+ return s.reviewDecision === "APPROVED" ? "approved" : "pending";
20
+ }
21
+
22
+ /** PRs that still need repairs from the agent: conflicts, required checks or review feedback. */
23
+ export function needsRepair(pr: Pr): boolean {
24
+ const s = pr.snapshot;
25
+ return !pr.error && !!s?.complete && s.state === "OPEN" && !s.draft && (s.conflict || s.failedChecks.length > 0 || s.threads.length > 0 || s.reviewDecision === "CHANGES_REQUESTED");
26
+ }
27
+
28
+ function depth(prs: Pr[], p: Pr, seen = new Set<string>()): number {
29
+ if (seen.has(p.key)) return 0;
30
+ seen.add(p.key);
31
+ const parent = prs.find(x => x.key === p.parent);
32
+ return parent ? depth(prs, parent, seen) + 1 : 0;
33
+ }
34
+ /** Parents before children, then by number: the order a stack merges in. */
35
+ export function stackOrder(prs: Pr[]): Pr[] {
36
+ return [...prs].sort((a, b) => depth(prs, a) - depth(prs, b) || a.number - b.number);
37
+ }
38
+
39
+ export type Segment = { key: string; number: number; stack: string; tone: PrTone };
40
+ /** The header bar: one segment per PR in active stacks, or every PR once everything has settled. */
41
+ export function stackBar(w: Pick<Workspace, "prs">): { segments: Segment[]; merged: number; total: number } {
42
+ const stacks = orderedStacks(w.prs);
43
+ const active = stacks.filter(s => !s.prs.every(settledForDisplay));
44
+ const shown = (active.length ? active : stacks).flatMap(s => stackOrder(s.prs));
45
+ return {
46
+ segments: shown.map(p => ({ key: p.key, number: p.number, stack: p.stack, tone: prTone(p) })),
47
+ merged: shown.filter(p => p.snapshot?.state === "MERGED").length,
48
+ total: shown.length,
49
+ };
50
+ }
51
+
52
+ const pendingSends = (w: Workspace) => w.batches.filter(b => !recoveryBatch(b) && b.state === "pending");
53
+ const openBatches = (w: Workspace) => w.batches.filter(b => !recoveryBatch(b) && ["sending", "sent", "blocked", "uncertain"].includes(b.state));
54
+ const QUEUED = ["QUEUED_TO_MERGE", "WAITING_TO_MERGE", "REBASING", "HANDED_OFF_TO_EXTERNAL_MERGE_QUEUE"];
55
+
56
+ /** Snapshot-only merge readiness. Pr controls add the browser's live "merging" read on top. */
57
+ export function mergeReady(pr: Pr, w: Pick<Workspace, "prActions">, now = Date.now()): boolean {
58
+ const s = pr.snapshot;
59
+ const queued = QUEUED.includes(s?.graphiteMergeStatus ?? "");
60
+ const recentlySubmitted = w.prActions.some(a => a.kind === "merge" && a.state === "submitted" && a.heads[pr.key] === s?.head && now - Date.parse(a.createdAt) < 30_000);
61
+ return !pr.error && !!s?.complete && s.state === "OPEN" && s.reviewDecision === "APPROVED" && !s.draft && !s.conflict && !s.failedChecks.length && !s.checksPending && !queued && !recentlySubmitted;
62
+ }
63
+ export const mergeQueued = (pr: Pr) => QUEUED.includes(pr.snapshot?.graphiteMergeStatus ?? "");
64
+
65
+ /** Why a pending batch cannot be sent right now, or null when Send is available. Mirrors the server's guards. */
66
+ export function sendBlocker(w: Workspace, batch: Batch): string | null {
67
+ if (w.hold) return "Resume follow-up first";
68
+ if (w.runtimeBusy) return "Sends after the agent's current turn";
69
+ if (w.runtimeReason) return w.runtimeReason;
70
+ if (w.batches.some(other => other.id !== batch.id && ["sending", "sent", "blocked", "uncertain"].includes(other.state))) return "Another batch is still open";
71
+ return null;
72
+ }
73
+
74
+ export type NeedItem =
75
+ | { kind: "hold"; key: string; title: string; detail: string }
76
+ | { kind: "retry"; key: string; batchId: string; title: string; detail: string; exhausted: boolean }
77
+ | { kind: "send"; key: string; batchId: string; title: string; tasks: string[]; blocker: string | null }
78
+ | { kind: "decision"; key: string; obligationId: string; title: string; detail: string }
79
+ | { kind: "question"; key: string; questionId: string; title: string; detail: string; state: QuestionState; big: string | null }
80
+ | { kind: "answer"; key: string; questionId: string; title: string; detail: string }
81
+ | { kind: "check"; key: string; actionId: string; title: string; detail: string }
82
+ | { kind: "merge"; key: string; prKey: string; number: number; title: string; detail: string }
83
+ | { kind: "reviewers"; key: string; prKey: string; number: number; title: string; detail: string };
84
+
85
+ const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
86
+
87
+ /** Everything waiting on the developer, most urgent first. Each item has exactly one action. */
88
+ export function needsYou(w: Workspace, now = Date.now()): NeedItem[] {
89
+ if (!w.enable_tracking || w.archived) return [];
90
+ const items: NeedItem[] = [];
91
+ const questions = w.questions ?? [];
92
+ // A question that stopped the agent outranks everything: nothing moves until it's answered.
93
+ const open = questions.filter(questionOpen);
94
+ for (const q of open.filter(q => questionState(q) === "stopped")) items.push({ kind: "question", key: `question:${q.id}`, questionId: q.id, title: `${q.id} · ${q.title}`, detail: q.question, state: "stopped", big: q.big });
95
+ if (w.hold) items.push({ kind: "hold", key: "hold", title: "Follow-up is paused", detail: w.hold });
96
+ for (const b of w.batches.filter(b => !recoveryBatch(b) && ["blocked", "uncertain"].includes(b.state))) {
97
+ items.push({ kind: "retry", key: `retry:${b.id}`, batchId: b.id, exhausted: b.attempts >= 3,
98
+ title: b.state === "uncertain" ? "Check whether the repairs arrived" : "The repairs didn't finish",
99
+ detail: b.result || (b.state === "uncertain" ? "Delivery wasn't confirmed." : "The main agent reported a blocker.") });
100
+ }
101
+ for (const a of w.prActions.filter(a => a.state === "uncertain")) {
102
+ const numbers = a.prs.map(key => `#${key.split("#")[1]}`).join(", ");
103
+ items.push({ kind: "check", key: `check:${a.id}`, actionId: a.id, title: `Check the ${a.kind === "merge" ? "merge" : a.kind === "request_reviewers" ? "reviewer request" : "merge-when-ready change"} on ${numbers}`, detail: a.result });
104
+ }
105
+ // Answers Paseo didn't confirm need a look before anything is sent again.
106
+ for (const q of questions.filter(q => q.answer?.delivery.state === "unconfirmed"))
107
+ items.push({ kind: "answer", key: `answer:${q.id}`, questionId: q.id, title: `Check that the agent got your ${q.id} answer`, detail: q.answer!.delivery.reason ?? "Paseo didn't confirm the message." });
108
+ for (const q of open.filter(q => questionState(q) !== "stopped")) items.push({ kind: "question", key: `question:${q.id}`, questionId: q.id, title: `${q.id} · ${q.title}`, detail: q.question, state: questionState(q), big: q.big });
109
+ // A blocked task is a question once the server mirrors it; until then it still shows as a decision.
110
+ for (const o of followUpObligations(w).filter(o => o.status === "blocked" && !questions.some(q => q.taskId === o.id && q.taskRevision !== null)))
111
+ items.push({ kind: "decision", key: `decision:${o.id}`, obligationId: o.id, title: o.title, detail: o.evidence });
112
+ if (!w.enable_auto_sends) for (const b of pendingSends(w)) {
113
+ items.push({ kind: "send", key: `send:${b.id}`, batchId: b.id, tasks: b.tasks.map(t => t.title), blocker: sendBlocker(w, b),
114
+ title: `${plural(b.tasks.length, "repair")} ready for the main agent` });
115
+ }
116
+ const blocking = (pr: Pr) => w.prActions.some(a => prActionBlocks(a, [pr.key]));
117
+ for (const pr of stackOrder(w.prs)) {
118
+ // Only offer Merge here when Graphite agrees; otherwise the PR sheet explains what is missing.
119
+ if (mergeReady(pr, w, now) && graphiteReady(pr.snapshot?.graphiteMergeStatus) && !blocking(pr)) items.push({ kind: "merge", key: `merge:${pr.key}`, prKey: pr.key, number: pr.number, title: `#${pr.number} is approved`, detail: pr.snapshot!.title });
120
+ else if (noReviewers(pr) && !pr.snapshot!.draft && defaultReviewers(pr.repo).length && !blocking(pr)) items.push({ kind: "reviewers", key: `reviewers:${pr.key}`, prKey: pr.key, number: pr.number, title: `#${pr.number} has no reviewers`, detail: pr.snapshot!.title });
121
+ }
122
+ return items;
123
+ }
124
+
125
+ export type HeadlinePart = { text: string; tone?: "warning" | "danger" | "success" };
126
+ /** "2 of 6 PRs merged, 3 need you, 1 to fix": counts that say where the work stands. */
127
+ export function headline(w: Workspace, now = Date.now()): HeadlinePart[] {
128
+ const bar = stackBar(w);
129
+ const parts: HeadlinePart[] = [];
130
+ const state = summary(w, now);
131
+ if (state.status === "done") return [{ text: `Done · ${plural(w.prs.length, "PR")} shipped`, tone: "success" }];
132
+ if (!bar.total) parts.push({ text: "No PRs registered yet" });
133
+ else if (bar.merged === bar.total) parts.push({ text: bar.total === 1 ? "PR merged" : `All ${bar.total} PRs merged` });
134
+ else parts.push({ text: `${bar.merged} of ${plural(bar.total, "PR")} merged` });
135
+ const need = needsYou(w, now).length;
136
+ if (need) parts.push({ text: `${need} need${need === 1 ? "s" : ""} you`, tone: "warning" });
137
+ const repair = w.prs.filter(needsRepair).length;
138
+ if (repair) parts.push({ text: `${repair} to fix`, tone: "danger" });
139
+ return parts;
140
+ }
141
+
142
+ export type LiveIcon = "spinner" | "done" | "paused" | "waiting" | "alert" | "idle";
143
+ /** What is happening right now, in one line, with the time it started when known. */
144
+ export function liveLine(w: Workspace, now = Date.now()): { icon: LiveIcon; text: string; since: string | null } {
145
+ const state = summary(w, now);
146
+ if (state.status === "done") return { icon: "done", text: "Ready to archive", since: w.completion?.declaredAt ?? null };
147
+ if (w.hold) return { icon: "paused", text: "Paused until you resume", since: w.interruption?.at ?? null };
148
+ const stopped = (w.questions ?? []).filter(questionOpen).find(q => questionState(q) === "stopped");
149
+ if (stopped) return { icon: "paused", text: `Main agent stopped until you answer ${stopped.id}`, since: stopped.askedAt };
150
+ const sent = openBatches(w).find(b => ["sending", "sent"].includes(b.state));
151
+ if (sent) {
152
+ const who = sent.recipientAgentId && sent.recipientAgentId !== w.mainAgentId ? "Recovery agent" : "Main agent";
153
+ return { icon: "spinner", text: `${who} is working on ${plural(sent.tasks.length, "repair")}`, since: sent.activityAt ?? sent.sentAt };
154
+ }
155
+ if (w.runtimeReason) return { icon: "waiting", text: w.runtimeReason, since: null };
156
+ const pending = pendingSends(w)[0];
157
+ if (pending && w.enable_auto_sends) return { icon: "waiting", text: `${plural(pending.tasks.length, "repair")} queued · sends when the agent is idle`, since: pending.createdAt };
158
+ if (w.runtimeBusy) return { icon: "spinner", text: "Main agent is working", since: null };
159
+ const working = followUpObligations(w).find(o => o.status === "working");
160
+ if (working) return { icon: "spinner", text: working.title, since: null };
161
+ if (w.prs.some(p => p.error || !p.snapshot?.complete)) return { icon: "alert", text: "Some PR status is unavailable · retrying", since: null };
162
+ if (w.prs.some(p => p.snapshot?.state === "OPEN" && p.snapshot.checksPending)) return { icon: "waiting", text: "Checks are running", since: null };
163
+ if (w.prs.some(p => p.snapshot?.state === "OPEN")) return { icon: "waiting", text: "Waiting on review and merges", since: null };
164
+ return { icon: "idle", text: "Waiting for the main agent to declare Done", since: null };
165
+ }
166
+
167
+ /** The composer pill: absent unless something needs the developer. */
168
+ export function pillFor(w: Workspace, now = Date.now()): { label: string; urgent: boolean; count: number } | null {
169
+ const items = needsYou(w, now);
170
+ if (!items.length) return null;
171
+ const urgent = items.some(i => i.kind === "hold" || i.kind === "retry" || i.kind === "check" || i.kind === "answer" || i.kind === "question" && i.state === "stopped");
172
+ if (items.length > 1) return { label: items.every(i => i.kind === "question") ? `${items.length} questions` : `${items.length} need you`, urgent, count: items.length };
173
+ const [item] = items;
174
+ const label = item.kind === "send" ? `Send ${plural(item.tasks.length, "repair")}` : item.kind === "merge" ? `Merge #${item.number}` : item.kind === "reviewers" ? `Reviewers for #${item.number}` : item.kind === "hold" ? "Follow-up paused" : item.kind === "decision" ? "Decision needed" : item.kind === "question" ? `Question ${item.questionId}` : item.kind === "answer" ? `Check ${item.questionId} answer` : item.kind === "retry" ? "Repairs blocked" : "Check PR action";
175
+ return { label, urgent, count: 1 };
176
+ }
177
+
178
+ export const statusGroups: { status: Status; title: string; short: string }[] = [
179
+ { status: "needs-you", title: "Needs you", short: "Needs you" },
180
+ { status: "handling", title: "Agent working", short: "Working" },
181
+ { status: "waiting", title: "Waiting", short: "Waiting" },
182
+ { status: "active", title: "In progress", short: "In progress" },
183
+ { status: "done", title: "Done · ready to archive", short: "Done" },
184
+ ];
185
+
186
+ /** Overview grouping: anything with a developer action counts as Needs you, even when the agent is busy. */
187
+ export function overviewStatus(w: Workspace, now = Date.now()): Status {
188
+ const status = summary(w, now).status;
189
+ if (status === "done") return status;
190
+ return needsYou(w, now).length ? "needs-you" : status;
191
+ }
192
+
193
+ export function ago(iso: string | null | undefined, now = Date.now()): string {
194
+ const at = iso ? Date.parse(iso) : NaN;
195
+ if (!Number.isFinite(at)) return "";
196
+ const s = Math.max(0, Math.round((now - at) / 1000));
197
+ if (s < 45) return "just now";
198
+ const m = Math.round(s / 60);
199
+ if (m < 60) return `${m}m ago`;
200
+ const h = Math.floor(m / 60);
201
+ if (h < 24) return m % 60 && h < 6 ? `${h}h ${m % 60}m ago` : `${h}h ago`;
202
+ const d = Math.floor(h / 24);
203
+ return d < 30 ? `${d}d ago` : new Date(at).toLocaleDateString([], { month: "short", day: "numeric" });
204
+ }
205
+
206
+ /** "Fix checks on acme/app#4" reads as "Fix checks on #4" when the workspace only has one repository. */
207
+ export function shortRefs(text: string, w: Pick<Workspace, "prs">): string {
208
+ const repos = new Set(w.prs.map(p => p.repo));
209
+ if (repos.size !== 1) return text;
210
+ const [repo] = repos;
211
+ return text.split(`${repo}#`).join("#");
212
+ }
package/shared/chat.ts ADDED
@@ -0,0 +1,130 @@
1
+ import { z } from "zod";
2
+
3
+ /** Follow-up's own messages and tool calls, recognised in agent chats so they render as compact rows. */
4
+ export const FOLLOW_TOOLS = ["workspace_status", "sync_workspace", "enroll_workspace", "register_pr", "exclude_stack", "update_obligation", "acknowledge_batch", "declare_done", "ask_question", "record_answer", "withdraw_question", "set_spec"] as const;
5
+ export type FollowTool = (typeof FOLLOW_TOOLS)[number];
6
+
7
+ /** Claude records mcp__follow-through__register_pr; Codex records follow-through.register_pr. */
8
+ export function followToolName(name: string): FollowTool | null {
9
+ const match = /^(?:mcp__)?follow-through(?:__|\.|\/|:)([a-z_]+)$/.exec(name);
10
+ return match && (FOLLOW_TOOLS as readonly string[]).includes(match[1]) ? match[1] as FollowTool : null;
11
+ }
12
+
13
+ /** The CLI fallback agents run when MCP is unavailable: node …/follow-through/mcp.mjs call <tool> '<json>'. */
14
+ export function followShellCall(command: string): { tool: FollowTool; input: Record<string, unknown> } | null {
15
+ const match = /plugin-data\/follow-through\/mcp\.mjs['"]?\s+call\s+([a-z_]+)(?:\s+'((?:[^']|'"'"')*)')?/.exec(command);
16
+ if (!match || !(FOLLOW_TOOLS as readonly string[]).includes(match[1])) return null;
17
+ let input: Record<string, unknown> = {};
18
+ try { const parsed = JSON.parse((match[2] ?? "{}").replace(/'"'"'/g, "'")); if (record(parsed)) input = parsed; } catch {}
19
+ return { tool: match[1] as FollowTool, input };
20
+ }
21
+
22
+ export const batchCardSchema = z.object({ kind: z.enum(["batch", "recovery"]), tasks: z.array(z.string()), text: z.string() });
23
+ export type BatchCard = z.infer<typeof batchCardSchema>;
24
+
25
+ /** A repair batch or recovery brief that Follow-up sent as a user message. */
26
+ export function parseBatchPrompt(text: string): BatchCard | null {
27
+ const batch = /^(?:Workspace follow-through batch|Follow-through batch) \S+\n\n([\s\S]+)$/.exec(text.trim());
28
+ if (batch) {
29
+ const tasks = batch[1].split("\n").map(line => /^\d+\.\s+(.+)$/.exec(line.trim())?.[1]).filter((t): t is string => !!t);
30
+ return tasks.length ? { kind: "batch", tasks, text } : null;
31
+ }
32
+ if (/^Follow-through recovery \S+/.test(text.trim())) return { kind: "recovery", tasks: [], text };
33
+ return null;
34
+ }
35
+
36
+ export const toolRowSchema = z.object({
37
+ tool: z.enum(FOLLOW_TOOLS),
38
+ state: z.enum(["running", "done", "failed", "canceled"]),
39
+ line: z.string(),
40
+ tone: z.enum(["muted", "warning", "danger", "success"]),
41
+ more: z.string().nullable(),
42
+ done: z.object({ summary: z.string() }).nullable(),
43
+ });
44
+ export type ToolRow = z.infer<typeof toolRowSchema>;
45
+
46
+ function record(value: unknown): value is Record<string, unknown> {
47
+ return typeof value === "object" && value !== null && !Array.isArray(value);
48
+ }
49
+ /** Text from Claude's { output } / { content: [{ text }] } shapes or Codex's MCP result. */
50
+ export function readText(value: unknown): string | undefined {
51
+ if (value === null || value === undefined) return "";
52
+ if (typeof value === "string") return value;
53
+ if (Array.isArray(value)) {
54
+ const parts = value.map(part => typeof part === "string" ? part : record(part) && typeof part.text === "string" ? part.text : undefined);
55
+ return parts.every(p => p !== undefined) ? parts.join("\n") : undefined;
56
+ }
57
+ if (!record(value)) return undefined;
58
+ const key = ["output", "content", "text", "message", "result"].find(name => name in value);
59
+ return key ? readText(value[key]) : undefined;
60
+ }
61
+ function json(text: string | undefined): Record<string, unknown> | null {
62
+ if (!text) return null;
63
+ try { const value = JSON.parse(text); return record(value) ? value : null; } catch { return null; }
64
+ }
65
+ const str = (value: unknown) => typeof value === "string" ? value : typeof value === "number" ? String(value) : "";
66
+ const firstLine = (text: string) => text.split("\n").map(l => l.trim()).find(Boolean) ?? "";
67
+ const specHost = (url: string) => { try { return new URL(url).host.replace(/^www\./, ""); } catch { return url; } };
68
+ const prKey = (key: string) => key.includes("#") ? `#${key.split("#")[1]}` : key;
69
+
70
+ const RUNNING: Record<FollowTool, string> = {
71
+ workspace_status: "Reading Follow-up status…", sync_workspace: "Syncing Follow-up…", enroll_workspace: "Updating the goal…",
72
+ register_pr: "Registering a PR…", exclude_stack: "Excluding a stack…", update_obligation: "Updating a task…",
73
+ acknowledge_batch: "Reporting repair results…", declare_done: "Checking whether the work is done…",
74
+ ask_question: "Asking you a question…", record_answer: "Recording your answer…", withdraw_question: "Withdrawing a question…", set_spec: "Saving the spec link…",
75
+ };
76
+ const NAMES: Record<FollowTool, string> = {
77
+ workspace_status: "Follow-up status", sync_workspace: "Follow-up sync", enroll_workspace: "Goal update", register_pr: "PR registration",
78
+ exclude_stack: "Stack exclusion", update_obligation: "Task update", acknowledge_batch: "Repair report", declare_done: "Done check",
79
+ ask_question: "Question", record_answer: "Answer record", withdraw_question: "Question withdrawal", set_spec: "Spec link",
80
+ };
81
+
82
+ /** One line for a finished Follow-up tool call, plus the text it opens to. */
83
+ export function toolRow(tool: FollowTool, status: "running" | "completed" | "failed" | "canceled", input: Record<string, unknown>, output: string | undefined, error?: string): ToolRow {
84
+ const base = { tool, done: null, more: null, tone: "muted" as const };
85
+ if (status === "running") return { ...base, state: "running", line: RUNNING[tool] };
86
+ if (status === "canceled") return { ...base, state: "canceled", line: `${NAMES[tool]} canceled` };
87
+ if (status === "failed") return { ...base, state: "failed", tone: "danger", line: firstLine(error ?? "") || `${NAMES[tool]} failed`, more: error?.trim() || null };
88
+ const result = json(output);
89
+ const more = output?.trim() || null;
90
+ switch (tool) {
91
+ case "workspace_status": return { ...base, state: "done", line: "Read Follow-up status", more };
92
+ case "sync_workspace": return { ...base, state: "done", line: str(input.summary) ? `Synced Follow-up · ${firstLine(str(input.summary))}` : "Synced Follow-up", more: str(input.summary) || more };
93
+ case "enroll_workspace": return { ...base, state: "done", line: `Goal: ${firstLine(str(input.goal) || str(result?.goal))}`, more };
94
+ case "register_pr": {
95
+ const repo = str(input.repo), number = str(input.number), parent = input.parentNumber ? ` on #${str(input.parentNumber)}` : "";
96
+ return { ...base, state: "done", line: `Registered ${repo ? `${repo.split("/")[1]} ` : ""}#${number}${input.stack ? ` in ${str(input.stack)}` : ""}${parent}`, more };
97
+ }
98
+ case "exclude_stack": return { ...base, state: "done", tone: "warning", line: `Excluded stack ${str(input.stack)}`, more: str(input.reason) || more };
99
+ case "update_obligation": {
100
+ const status = str(input.status);
101
+ const verb = status === "done" ? "Task done" : status === "waived" ? "Task waived" : status === "blocked" ? "Task needs a decision" : input.id ? "Task updated" : "Task added";
102
+ const after = Array.isArray(input.afterPrs) && input.afterPrs.length ? ` · after ${input.afterPrs.map(k => prKey(str(k))).join(", ")}` : "";
103
+ return { ...base, state: "done", tone: status === "blocked" ? "warning" : "muted", line: `${verb}: ${firstLine(str(input.title))}${after}`, more: str(input.evidence) || more };
104
+ }
105
+ case "acknowledge_batch": {
106
+ const blocked = input.outcome === "blocked";
107
+ return { ...base, state: "done", tone: blocked ? "warning" : "muted", line: `${blocked ? "Repairs blocked" : "Repairs finished"} · ${firstLine(str(input.result))}`, more: str(input.result) || more };
108
+ }
109
+ case "ask_question": {
110
+ const question = record(result?.question) ? result!.question as Record<string, unknown> : null;
111
+ const id = str(question?.id);
112
+ return { ...base, state: "done", tone: "warning", line: `${id ? `${id} · ` : ""}${firstLine(str(input.title) || str(question?.title))} · asked`, more: [str(input.question), str(result?.instruction)].filter(Boolean).join("\n\n") || more };
113
+ }
114
+ case "record_answer": return { ...base, state: "done", line: `${str(input.id)} · answer recorded: ${firstLine(str(input.choice))}`, more: str(input.words) || more };
115
+ case "withdraw_question": return { ...base, state: "done", line: `${str(input.id)} · withdrawn: ${firstLine(str(input.reason))}`, more };
116
+ case "set_spec": {
117
+ const kept = result?.applied === false;
118
+ return { ...base, state: "done", line: kept ? "Spec link kept · the developer chose it" : `Spec link: ${firstLine(str(input.title)) || specHost(str(input.url))}`, more: str(result?.message) || more };
119
+ }
120
+ case "declare_done": {
121
+ const blockers = Array.isArray(result?.blockers) ? result!.blockers.map(str).filter(Boolean) : [];
122
+ const completion = record(result?.completion) ? str(result!.completion.summary) : record(record(result?.workspace) ? (result!.workspace as Record<string, unknown>).completion : null) ? str(((result!.workspace as Record<string, unknown>).completion as Record<string, unknown>).summary) : "";
123
+ if (blockers.length) return { ...base, state: "done", tone: "warning", line: `Not done yet · ${blockers.length} blocker${blockers.length === 1 ? "" : "s"}`, more: blockers.map(b => `• ${b}`).join("\n") };
124
+ return { ...base, state: "done", tone: "success", line: "Declared done", more, done: { summary: completion || str(input.summary) } };
125
+ }
126
+ }
127
+ }
128
+
129
+ export const answerCardSchema = z.object({ id: z.string(), title: z.string(), choice: z.string(), label: z.string().nullable(), words: z.string().nullable(), text: z.string() });
130
+ export type AnswerCard = z.infer<typeof answerCardSchema>;
@@ -4,6 +4,8 @@ import { z } from "zod";
4
4
  import { idSchema, textSchema, workspaceSchema } from "./model";
5
5
  import { communicationSchema } from "./communication";
6
6
  import { taskTriggerSchema } from "./task-trigger";
7
+ import { QUESTION_MODES, questionSchema } from "./questions";
8
+ import { specSchema } from "./spec";
7
9
  import { actionPlanSchema, actionResultSchema, browserCommandSchema, browserExchangeSchema, browserPrSchema, browserStatusSchema, prActionKind } from "./pr-actions";
8
10
 
9
11
  const agentCommunicationSchema = z.strictObject({
@@ -44,3 +46,22 @@ export const taskTriggerRpc = defineRpc({ name: "follow.set-task-trigger", input
44
46
 
45
47
  // Narrow integration: no inventory, messages, paths, or credentials cross this RPC.
46
48
  export const prOwnerRpc = defineRpc({ name: "follow.pr-owner", input: z.strictObject({ repo: z.string().regex(/^[\w.-]+\/[\w.-]+$/), number: z.number().int().positive() }), output: z.object({ owner: z.object({ workspaceId: idSchema, agentId: idSchema }).nullable() }) });
49
+
50
+ // Questions. Agents ask, record an answer given in chat, or withdraw; the developer answers from the UI.
51
+ const optionInput = z.strictObject({ letter: z.string().regex(/^[A-Z]$/), label: z.string().trim().min(1).max(200), consequence: z.string().trim().max(600).optional() });
52
+ const linkInput = z.strictObject({ url: z.string().url().optional(), path: z.string().trim().min(1).max(1000).optional(), label: z.string().trim().max(200).optional() });
53
+ export const askQuestionRpc = defineRpc({ name: "follow.ask-question", input: z.strictObject({
54
+ agentId: idSchema, title: z.string().trim().min(1).max(120), question: z.string().trim().min(1).max(2000),
55
+ options: z.array(optionInput).max(26).optional(), recommend: z.string().trim().max(200).optional(), big: z.string().trim().max(300).optional(),
56
+ background: z.string().trim().max(4000).optional(), links: z.array(linkInput).max(10).optional(),
57
+ pr: z.string().trim().max(200).optional(), task: idSchema.optional(),
58
+ }), output: z.object({ workspaceId: idSchema, question: questionSchema, mode: z.enum(QUESTION_MODES), instruction: z.string() }) });
59
+ export const recordAnswerRpc = defineRpc({ name: "follow.record-answer", input: z.strictObject({ agentId: idSchema, id: z.string().regex(/^Q\d+$/), choice: z.string().trim().min(1).max(200), words: z.string().trim().max(2000).optional() }), output: z.object({ workspaceId: idSchema, question: questionSchema }) });
60
+ export const withdrawQuestionRpc = defineRpc({ name: "follow.withdraw-question", input: z.strictObject({ agentId: idSchema, id: z.string().regex(/^Q\d+$/), reason: z.string().trim().min(1).max(500) }), output: z.object({ workspaceId: idSchema, question: questionSchema }) });
61
+ export const answerQuestionRpc = defineRpc({ name: "follow.answer-question", input: z.object({ workspaceId: idSchema, questionId: z.string().regex(/^Q\d+$/), choice: z.string().trim().min(1).max(200), words: z.string().trim().max(2000).optional(), action: z.enum(["send", "copy", "resend"]) }), output: z.object({ workspace: workspaceSchema, question: questionSchema }) });
62
+ export const setSpecRpc = defineRpc({ name: "follow.set-spec", input: z.strictObject({ agentId: idSchema, url: z.string().trim().min(1).max(2000), title: z.string().trim().max(120).optional() }), output: z.object({ workspaceId: idSchema, spec: specSchema.nullable(), applied: z.boolean(), message: z.string() }) });
63
+ export const workspaceSpecRpc = defineRpc({ name: "follow.workspace-spec", input: z.discriminatedUnion("action", [
64
+ z.object({ workspaceId: idSchema, action: z.literal("set"), url: z.string().trim().min(1).max(2000), title: z.string().trim().max(120).nullable().optional() }),
65
+ z.object({ workspaceId: idSchema, action: z.literal("remove") }),
66
+ z.object({ workspaceId: idSchema, action: z.literal("reset") }),
67
+ ]), output: workspaceSchema });
package/shared/display.ts CHANGED
@@ -5,7 +5,8 @@ export const displayPreferences = defineSettings({
5
5
  id: "display",
6
6
  scope: "host",
7
7
  version: 1,
8
- schema: z.object({ enable_header_button: z.boolean().default(true), showSidebar: z.boolean().default(true) }),
8
+ // Fields only ever gain defaults, so documents saved by older versions keep parsing unchanged.
9
+ schema: z.object({ enable_header_button: z.boolean().default(true), showSidebar: z.boolean().default(true), enable_composer_pill: z.boolean().default(true) }),
9
10
  });
10
11
 
11
12
  export const displayRpc = settingsRpc(displayPreferences.id);
@@ -0,0 +1,5 @@
1
+ /** RPC errors arrive as "Request failed: <reason> requestType=… code=…"; people only need the reason. */
2
+ export function errorText(error: unknown): string {
3
+ const raw = error instanceof Error ? error.message : String(error ?? "");
4
+ return raw.replace(/^Request failed:\s*/i, "").replace(/\s*requestType=\S+.*$/s, "").trim() || "Something went wrong. Try again.";
5
+ }
package/shared/model.ts CHANGED
@@ -2,6 +2,8 @@ import { z } from "zod";
2
2
  import { followUpObligations, deployed, recoveryBatch } from "./follow-up";
3
3
  import { communicationSchema, replyRecorded } from "./communication";
4
4
  import { taskTriggerSchema } from "./task-trigger";
5
+ import { isOpen as questionOpen, questionSchema } from "./questions";
6
+ import { artifactSchema, specSchema } from "./spec";
5
7
 
6
8
  export const textSchema = z.string().trim().min(1).max(2000);
7
9
  export const idSchema = z.string().min(1).max(200);
@@ -66,6 +68,11 @@ export const workspaceSchema = z.object({
66
68
  updatedAt: z.string(), managedDoneLabel: z.boolean(),
67
69
  runtimeReason: z.string().nullable(), runtimeBusy: z.boolean(), backgroundBusy: z.boolean().default(false),
68
70
  interruption: z.object({ turnId: z.string().nullable(), at: z.string(), kind: z.enum(["canceled", "failed"]), guardPauseId: z.string().optional() }).optional(),
71
+ // Added with questions; older saved states parse with none.
72
+ questions: z.array(questionSchema).default([]),
73
+ // Added with spec links; older saved states parse with none.
74
+ spec: specSchema.nullable().default(null),
75
+ artifacts: z.array(artifactSchema).default([]),
69
76
  inventory: z.object({
70
77
  revision: z.number().int().positive(), syncedRevision: z.number().int().nonnegative(),
71
78
  candidates: z.array(idSchema), historyComplete: z.boolean(), historyError: z.string().nullable(),
@@ -96,6 +103,7 @@ export function completionBlockers(w: Workspace, now = Date.now()): string[] {
96
103
  blockers.push(...followUpObligations(w).filter(o => o.status === "done" && o.communication && !replyRecorded(o.communication)).map(o => `Record the sent reply for ${o.title}`));
97
104
  if (w.batches.some(b => !recoveryBatch(b) && ["pending", "sending", "sent", "blocked", "uncertain"].includes(b.state))) blockers.push("Finish outstanding follow-up batches");
98
105
  if (w.prActions.some(a => ["sending", "uncertain"].includes(a.state))) blockers.push("Check the outstanding PR action");
106
+ blockers.push(...(w.questions ?? []).filter(questionOpen).map(q => `Answer or withdraw ${q.id} (${q.title})`));
99
107
  if (w.hold) blockers.push(w.hold);
100
108
  if (w.runtimeBusy) blockers.push("Wait for active agent work to finish");
101
109
  if (w.backgroundBusy) blockers.push("Wait for active background agents to finish");
@@ -108,6 +116,8 @@ export function summary(w: Workspace, now = Date.now()): { status: Status; label
108
116
  if (w.hold) return { status: "needs-you", label: "Needs you", reason: w.hold };
109
117
  const blocked = w.batches.find(b => !recoveryBatch(b) && ["blocked", "uncertain"].includes(b.state));
110
118
  if (blocked) return { status: "needs-you", label: "Needs you", reason: blocked.result || "Follow-up needs a decision" };
119
+ const question = (w.questions ?? []).find(questionOpen);
120
+ if (question) return { status: "needs-you", label: "Needs you", reason: `${question.id}: ${question.title}` };
111
121
  const obligation = obligations.find(o => o.status === "blocked");
112
122
  if (obligation) return { status: "needs-you", label: "Needs you", reason: obligation.title };
113
123
  if (w.completion && completionBlockers(w, now).length === 0) return { status: "done", label: "Done", reason: w.completion.summary };
@@ -32,6 +32,13 @@ export function downstack(prs: Pr[], target: string): Pr[] {
32
32
  return selected.reverse();
33
33
  }
34
34
 
35
+ export const GRAPHITE_READY = ["READY_TO_MERGE", "READY_TO_MERGE_AS_STACK", "READY_TO_MERGE_WITHOUT_CI", "READY_TO_MERGE_AS_STACK_WITHOUT_CI"];
36
+ export const graphiteReady = (status: string | null | undefined) => GRAPHITE_READY.includes(status ?? "");
37
+ /** Says why Graphite won't merge yet and what to do about it. */
38
+ export function graphiteBlocker(status: string | null | undefined): string {
39
+ if (!status) return "Graphite hasn't reported this PR ready to merge. Check the Graphite CLI sign-in on the daemon host, or open the PR in Graphite.";
40
+ return `Graphite says: ${status.toLowerCase().replace(/__/g, ": ").replace(/_/g, " ")}`;
41
+ }
35
42
  export function mergeBlockers(pr: Pr): string[] {
36
43
  const s = pr.snapshot;
37
44
  if (pr.error || !s?.complete) return ["Refresh PR status"];
@@ -42,7 +49,7 @@ export function mergeBlockers(pr: Pr): string[] {
42
49
  if (s.conflict) blockers.push("Merge conflicts");
43
50
  if (s.failedChecks.length) blockers.push("Required checks failed");
44
51
  if (s.checksPending) blockers.push("Required checks pending");
45
- if (!["READY_TO_MERGE", "READY_TO_MERGE_AS_STACK", "READY_TO_MERGE_WITHOUT_CI", "READY_TO_MERGE_AS_STACK_WITHOUT_CI"].includes(s.graphiteMergeStatus ?? "")) blockers.push("Graphite is not ready to merge");
52
+ if (!graphiteReady(s.graphiteMergeStatus)) blockers.push(graphiteBlocker(s.graphiteMergeStatus));
46
53
  return blockers;
47
54
  }
48
55