paseo-follow-up 2.2.0 → 2.2.1-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/server/engine.ts CHANGED
@@ -3,7 +3,7 @@ import { taskSchedule } from "../shared/task-trigger";
3
3
  import { STOP_WAIT_MS, settleWithin, type Deadline } from "./teardown";
4
4
  import { DEVELOPER, type Actor } from "../shared/actor";
5
5
  import { randomUUID } from "node:crypto";
6
- import { completionBlockers, completionCheck, completionGate, revokesDone, type CompletionGate, type Workspace, type State, type Batch } from "../shared/model";
6
+ import { completionBlockers, completionCheck, completionGate, revokesDone, type CompletionGate, type Workspace, type State, type Batch, type Task } from "../shared/model";
7
7
  import { Store } from "./store";
8
8
  import { Github } from "./github";
9
9
  import { batchPrompt, messageText, tasksFor, isRecovery, needsPrObservations, type TaskWording } from "./tasks";
@@ -19,12 +19,18 @@ import { PASEO_UNREACHABLE, deliveryOf, type NewQueueItem, type QueueItem, type
19
19
  import { recordSnapshot } from "./deployment-anchor";
20
20
  import { pruneUnsent } from "./batch-archive";
21
21
  import { holdSuperseded, liftHold } from "../shared/status";
22
- import { conditionId, isCapped, readSince, sendDecision, settleUnacknowledged, UNACKNOWLEDGED_MS } from "../shared/send-decision";
22
+ import { conditionId, isCapped, MAIN_WAIT, mootReason, personHeld, QUIET_WAIT, readSince, repairWait, sendDecision, settleUnacknowledged, stillApplies, stuckRepair, UNACKNOWLEDGED_MS, type MainWait } from "../shared/send-decision";
23
23
  import { isRepair } from "../shared/task-rows";
24
- export { settleUnacknowledged, UNACKNOWLEDGED_MS, NO_PROGRESS_CAP } from "../shared/send-decision";
24
+ export { settleUnacknowledged, UNACKNOWLEDGED_MS, NO_PROGRESS_CAP, repairWait, QUIET_WAIT } from "../shared/send-decision";
25
25
 
26
26
  export interface Runtime {
27
27
  busy: boolean; reason: string | null; archived: boolean; backgroundBusy?: boolean;
28
+ /**
29
+ * What the main agent itself is doing that holds a repair (Workspace.mainBusy, Q96 = A). `busy` and `backgroundBusy`
30
+ * are the whole workspace (Done, "all work finished"); only this decides a repair. Undefined: unknown, so a repair
31
+ * treats the workspace's busy as the main agent's (repairWait).
32
+ */
33
+ mainBusy?: MainWait | null;
28
34
  /** Live state of the agents working tasks name (Workspace.taskAgents). Undefined: unknown, so every line naming an agent says "Agent unavailable". */
29
35
  taskAgents?: Workspace["taskAgents"];
30
36
  guarded?: boolean; guardedInterruptionId?: string;
@@ -133,6 +139,9 @@ export class Engine {
133
139
  b.tasks = b.tasks.filter(t => t.kind !== "obligation" || eligible.some(e => e.key === t.key && e.fingerprint === t.fingerprint));
134
140
  if (!b.tasks.length) { b.state = "cancelled"; b.result = "No triggered task is due. Unscheduled work remains in Tasks."; }
135
141
  }
142
+ // A batch left blocked or unconfirmed by a release before a-batch-item-leaves-once-nothing-applies, whose PRs
143
+ // have since merged or changed, settles at start-up, dormant workspaces included (no tick observes those).
144
+ if (w.enable_tracking && !w.archived) settleMoot(w, eligible, this.now());
136
145
  for (const b of w.batches) if (isRecovery(b) && b.state === "pending" && !b.enable_manual_recovery) { b.state = "cancelled"; b.result = "Recovery is now optional. Run recovery when needed; registered work continues independently."; }
137
146
  if (["Recovery stopped or failed. Check the recovery agent before retrying.", "Recovery acknowledgment was refused. Check the identity error on this batch."].includes(w.hold ?? "")) w.hold = null;
138
147
  }
@@ -256,6 +265,7 @@ export class Engine {
256
265
  if (!untouched) await this.store.mutateWorkspace(original.id, w => {
257
266
  w.runtimeBusy = runtime.busy; w.runtimeReason = runtime.reason; w.taskAgents = runtime.taskAgents;
258
267
  w.backgroundBusy = runtime.backgroundBusy ?? false;
268
+ w.mainBusy = repairWait(runtime);
259
269
  if (runtime.mainTitle !== undefined && (w.mainAgentTitle ?? null) !== runtime.mainTitle) w.mainAgentTitle = runtime.mainTitle;
260
270
  if (runtime.gone && w.goneAgent?.agentId !== w.mainAgentId) w.goneAgent = { agentId: w.mainAgentId, at: new Date(this.now()).toISOString(), reason: runtime.gone };
261
271
  if (w.goneAgent?.agentId === w.mainAgentId) w.runtimeReason = GONE_REASON;
@@ -340,8 +350,8 @@ export class Engine {
340
350
  const heldItem = held && this.queue?.get(repairItemId(current.id, held.id));
341
351
  // An Auto send keeps its own pace (a refusal retries once per settle window: the-send-line-matches-the-send-decision);
342
352
  // only the developer's Send, or any repair waiting out a turn, goes on this tick.
343
- const due = heldItem?.state === "queued" && !!heldItem.reason && (heldItem.reason.startsWith("waits for the agent's turn") || !heldItem.ref.automatic && heldAgentSide(heldItem.reason));
344
- if (due && !runtime.busy && !runtime.backgroundBusy && !runtime.reason) await this.queue!.retry(heldItem!.id).catch(() => undefined);
353
+ const due = heldItem?.state === "queued" && !!heldItem.reason && (MAIN_WAITS.has(heldItem.reason) || !heldItem.ref.automatic && heldAgentSide(heldItem.reason));
354
+ if (due && !repairWait(runtime) && !runtime.reason) await this.queue!.retry(heldItem!.id).catch(() => undefined);
345
355
  current = findWorkspace(await this.store.snapshot(), original.id);
346
356
  const done = !current.archived && !!current.completion && completionBlockers(current, this.now()).length === 0;
347
357
  if (done || current.managedDoneLabel) {
@@ -524,7 +534,10 @@ export class Engine {
524
534
  try { runtime = await this.gateway.observe(w, true); }
525
535
  catch { return { defer: "Paseo unreachable" }; }
526
536
  if (runtime.archived) return { cancel: "The workspace was archived." };
527
- if (runtime.busy || runtime.backgroundBusy) return { defer: "waits for the agent's turn to end, so it isn't interrupted" };
537
+ // A repair waits only for the main agent itself (Q96 = A); the Done check waits for the whole workspace to be quiet.
538
+ if (completionCheck(b) && (runtime.busy || runtime.backgroundBusy)) return { defer: QUIET_WAIT };
539
+ const holds = repairWait(runtime);
540
+ if (holds) return { defer: MAIN_WAIT[holds] };
528
541
  if (runtime.reason) return { defer: runtime.reason };
529
542
  // The runtime read awaited Paseo: what the developer changed meanwhile (Auto off, a hold) still wins.
530
543
  const fresh = (await this.store.snapshot()).workspaces.find(x => x.id === w.id);
@@ -591,7 +604,7 @@ export class Engine {
591
604
  if (!b || this.queue?.get(repairItemId(w.id, b.id))) return [];
592
605
  if (!sendDecision({ ...w, sendWait: null }, this.now(), { settleMs: 0, batch: b }).send || this.autoSendsHeld()) return [];
593
606
  const runtime = await this.gateway.observe(w, true).catch(() => null);
594
- if (!runtime || runtime.busy || runtime.backgroundBusy || runtime.reason || runtime.archived) return [];
607
+ if (!runtime || repairWait(runtime) || runtime.reason || runtime.archived) return [];
595
608
  return [this.repairItem(w, b, true)];
596
609
  }
597
610
  /**
@@ -642,14 +655,22 @@ export class Engine {
642
655
  // One cap (Q49): a send that left a PR condition as it was, acknowledged or not, delivered nothing GitHub shows, so
643
656
  // the condition goes out again until it has gone out NO_PROGRESS_CAP times unchanged. An acknowledged one waits
644
657
  // for a GitHub read newer than the acknowledgment, so a fix GitHub hasn't shown yet is never sent twice.
645
- const delivered = new Set(w.batches.filter(b => ["sending", "sent", "completed", "blocked", "uncertain"].includes(b.state) && !(b.state === "completed" && b.unacknowledged))
658
+ // A stuck batch re-checks what it asked for like a queued one: once nothing still applies, it settles and leaves
659
+ // Needs you (a-batch-item-leaves-once-nothing-applies).
660
+ settleMoot(w, tasks, this.now());
661
+ // A human-only outcome isn't a delivery that awaits GitHub: its still-open conditions are held as "person" at once.
662
+ const delivered = new Set(w.batches.filter(b => ["sending", "sent", "completed", "blocked", "uncertain"].includes(b.state) && !(b.state === "completed" && (b.unacknowledged || b.humanOnly)))
646
663
  .flatMap(b => b.tasks.filter(t => b.state !== "completed" || !isRepair(t) || !readSince(w, t, b.settledAt)).map(conditionId)));
647
664
  const open = tasks.filter(t => !delivered.has(conditionId(t)));
648
665
  // One rule for every task in a message (Q49): a task the developer keeps for themselves, or a condition that went
649
666
  // out NO_PROGRESS_CAP times unchanged, stays out of it; only that task waits, the rest go out.
650
667
  const manual = new Set(w.manualTasks ?? []);
651
668
  const held: NonNullable<Workspace["heldTasks"]> = [];
652
- for (const t of open) if (t.kind !== "completion" && (manual.has(t.key) || isCapped(w, t))) held.push({ task: t, held: manual.has(t.key) ? "manual" : "capped" });
669
+ for (const t of open) {
670
+ if (t.kind === "completion") continue;
671
+ const why = manual.has(t.key) ? "manual" : personHeld(w, t) ? "person" : isCapped(w, t) ? "capped" : null;
672
+ if (why) held.push({ task: t, held: why });
673
+ }
653
674
  const fresh = open.filter(t => !held.some(h => h.task === t));
654
675
  if (held.length || w.heldTasks?.length) w.heldTasks = held;
655
676
  let pending = w.batches.find(b => b.state === "pending" && !isRecovery(b));
@@ -686,6 +707,7 @@ export class Engine {
686
707
  const w = ownedWorkspace(state, agentId, workspaceId);
687
708
  w.runtimeBusy = runtime.busy; w.runtimeReason = runtime.reason; w.taskAgents = runtime.taskAgents;
688
709
  w.backgroundBusy = runtime.backgroundBusy ?? false;
710
+ w.mainBusy = repairWait(runtime);
689
711
  if (runtime.archived) w.archived = true;
690
712
  for (const pr of w.prs) {
691
713
  const observation = observations.get(pr.key);
@@ -709,7 +731,13 @@ export class Engine {
709
731
  return { workspace: w, blockers, unconfirmed: gate.unconfirmed, alreadyDone, next: doneGuidance(gate, alreadyDone) };
710
732
  });
711
733
  }
712
- async acknowledge(agentId: string, batchId: string, outcome: "completed" | "blocked", result: string, workspaceId?: string): Promise<Workspace> {
734
+ /**
735
+ * Records an agent's outcome. `humanOnly` (with blocked): nothing is left for an agent, only a person can move what is
736
+ * still open. The batch settles completed and its still-open conditions wait as the developer's "person" tasks, a PR
737
+ * item, never "The tasks didn't finish" (a-human-only-outcome-is-a-human-item).
738
+ */
739
+ async acknowledge(agentId: string, batchId: string, outcome: "completed" | "blocked", result: string, workspaceId?: string, humanOnly?: boolean): Promise<Workspace> {
740
+ if (humanOnly && outcome !== "blocked") throw new Error("humanOnly goes with outcome \"blocked\": use it when nothing is left for an agent and only a person can move what is still open.");
713
741
  // Resolved on the snapshot, written to that one workspace (a-send-never-clones-the-whole-state), re-checked inside.
714
742
  const target = agentWorkspace(await this.store.snapshot(), agentId, "read", workspaceId);
715
743
  const w = await this.store.mutateWorkspace(target.id, w => {
@@ -719,7 +747,9 @@ export class Engine {
719
747
  if (!b || !["sending", "sent", "blocked", "uncertain"].includes(b.state)) throw new Error("Batch is not awaiting acknowledgment.");
720
748
  if ((b.recipientAgentId ?? w.mainAgentId) !== agentId) throw new Error(`Only the assigned agent can acknowledge this batch: expected agent ${b.recipientAgentId ?? w.mainAgentId}, received agent ${agentId}.`);
721
749
  if (outcome === "completed" && b.tasks.some(t => t.kind === "obligation" && w.obligations.some(o => o.id === t.target && o.communication && o.status !== "waived" && (o.status !== "done" || !replyRecorded(o.communication))))) throw new Error("Record the sent reply on each communication task before completing this batch, or acknowledge blocked with the posting/access reason.");
722
- b.state = outcome; b.result = result; b.acknowledgmentError = null; b.settledAt = new Date(this.now()).toISOString();
750
+ if (humanOnly && (isRecovery(b) || completionCheck(b))) throw new Error("humanOnly is for repair batches. Acknowledge this one blocked with the reason.");
751
+ b.state = humanOnly ? "completed" : outcome; b.result = result; b.acknowledgmentError = null; b.settledAt = new Date(this.now()).toISOString();
752
+ if (humanOnly) b.humanOnly = true; else delete b.humanOnly;
723
753
  if (outcome === "completed" && w.inventory) for (const task of b.tasks.filter(t => t.kind === "inventory"))
724
754
  w.inventory.syncedRevision = Math.max(w.inventory.syncedRevision, Number(task.fingerprint));
725
755
  return w;
@@ -753,6 +783,16 @@ function nextDue(w: Workspace, now: number): number {
753
783
 
754
784
  export type DoneResult = { workspace: Workspace; blockers: string[]; unconfirmed: string[]; alreadyDone: boolean; next: string };
755
785
  /** The declare_done reply in words: what's missing, who can move it, and whether calling again could help. */
786
+ /**
787
+ * Settles every stuck (blocked or unconfirmed) repair batch that no longer asks for anything (stillApplies over `open`,
788
+ * the tasks the PRs show now), with the reason and the blocker's own time kept for Activity. The same rule reconcile
789
+ * applies to a queued batch ("Conditions resolved before delivery"), so a stuck one never outlives what it was about.
790
+ */
791
+ function settleMoot(w: Workspace, open: readonly Task[], now: number): void {
792
+ for (const b of w.batches) if (stuckRepair(b) && !stillApplies(w, b, open)) {
793
+ b.state = "cancelled"; b.result = mootReason(w, b); b.settledAt ??= new Date(now).toISOString();
794
+ }
795
+ }
756
796
  /** Done answers every open Done check: a queued one is cancelled, a sent one counts as acknowledged. */
757
797
  function settleDoneChecks(w: Workspace, now: number): void {
758
798
  for (const b of w.batches.filter(b => completionCheck(b) && ["pending", "sending", "sent", "blocked", "uncertain"].includes(b.state))) {
@@ -811,5 +851,7 @@ export function agentWorkspace(state: State, agentId: string, access: "read" | "
811
851
  export const answerItemId = (workspaceId: string, q: Pick<Question, "id" | "answer">) => `answer:${workspaceId}:${q.id}:${q.answer?.delivery.messageId ?? ""}`;
812
852
  /** A batch's queue item: one per batch (a Retry makes a new batch, so a new item). */
813
853
  /** A repair's hold that only the agent's runtime can clear, so a tick that sees the agent free retries it. */
854
+ /** The main agent's own waits: a repair held by one goes on the tick that sees the main agent free. */
855
+ const MAIN_WAITS = new Set<string>(Object.values(MAIN_WAIT));
814
856
  export const heldAgentSide = (reason: string) => reason !== PASEO_UNREACHABLE && !reason.startsWith("waits for the last message") && !reason.startsWith("waits until GitHub answers");
815
857
  export const repairItemId = (workspaceId: string, batchId: string) => `repair:${workspaceId}:${batchId}`;
@@ -156,7 +156,7 @@ export const hookSource: string = [
156
156
  " \"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, with ask set to the question they must answer.\",",
157
157
  " \"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.\",",
158
158
  " \"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.\",",
159
- " batchParagraph(workflow) + \" For post-deploy tasks, verify the currently serving revision contains every dependency and record behavioral results separately. Acknowledge the header's batch ID with acknowledge_batch before finishing: completed with the result, or blocked with the reason. Verify the entire goal and post-merge work before declare_done; acknowledge a completion batch first. \" + mergeLine(workflow),",
159
+ " 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),",
160
160
  " \"Before ending this turn, reconcile the sidebar with what you actually did and call sync_workspace with a short summary, including when no changes are needed. Acknowledge any assigned batch. When the entire goal is fulfilled, use declare_done; otherwise preserve remaining work. Do not launch recovery, start queued repairs, merge, toggle merge-when-ready, or archive as part of this bookkeeping. Auto still governs separate follow-up sends. Subagents report to the main agent instead of claiming workspace ownership.\",",
161
161
  " `Prefer the native follow-up MCP tools. For a full historical record, use workspace_status with detail=full. CLI compatibility fallback: FOLLOW_UP_CLIENT_ENTRY=${quote(lease.clientEntry)} node ${quote(join(directory, \"mcp.mjs\"))} call <tool> '<json>' --compact. Omit --compact only when an existing script needs the full response. Never ask the developer to maintain the sidebar or run this bridge.`,",
162
162
  " ];",
@@ -27,7 +27,7 @@ export const mcpSource: string = [
27
27
  " [\"register_pr\", \"Register a PR produced by this workspace. Call after every submission. Register parents first; repeat to update its stack or parent after restacking. Supply a disposition for a deliberately closed PR. Set agentMerges: true when you merge this PR yourself (no human review): Follow-up then never asks the developer to add reviewers or merge it, and the workspace reads as waiting on you; set it false to hand the merge back. In a repository set to No review (set_pr_workflow review \\\"none\\\") every PR counts as agentMerges unless you set it false.\", \"follow.register-pr\", { repo: string, number: integer, stack: string, parentNumber: { type: [\"integer\", \"null\"], minimum: 1 }, disposition: string, agentMerges: boolean }, [\"repo\", \"number\", \"stack\"]],",
28
28
  " [\"exclude_stack\", \"Correct an unrelated stack registration. Preserve its PRs and requirements in an exclusion audit; future registration is blocked. reason must cite the scope/ownership evidence. obligationIds may include related tasks without PR dependencies. Keep external dependencies separate from owned work.\", \"follow.exclude-stack\", { stack: string, reason: string, obligationIds: array }, [\"stack\", \"reason\"]],",
29
29
  " [\"update_obligation\", \"Record concrete follow-up: verification, migrations, decisions or stakeholder replies. Never add approve/merge/deploy checklist tasks. afterPrs uses owner/repo#number keys. Tasks are manual unless explicitly scheduled with trigger={event:\\\"now\\\"|\\\"merge\\\"|\\\"deploy\\\",delayDays:0}. Only set a trigger from the developer’s requested timing; never infer timing from a title or enable_follow_up alone. Merge/deploy triggers require owned afterPrs; delayDays=14 waits fourteen days after the last dependency event. Now requires no PR dependencies or delay. Deployment timing starts at the first verified fully serving observation and remains conservative when history is unknown. Preserve existing trigger fields on updates; trigger=null makes a task manual. Auto controls delivery, not timing or production permissions. For Slack replies, communication records the original threadUrl, recipient, purpose (progress or verified), explicit developer authorization and sent replyUrl. Empty authorization never queues a reply; Auto does not authorize external posts. Use a verify-and-reply task after deployment for the final update. Read the thread first; mark blocked when posting is unavailable or uncertain, never treat a draft as sent. Done requires replyUrl and evidence; preserve fields when updating. status=working records you as the agent doing it; pass workingAgentId when another agent (your subagent) is.\", \"follow.obligation\", { id: string, workingAgentId: string, title: string, status: { type: \"string\", enum: [\"pending\", \"waiting\", \"working\", \"blocked\", \"done\", \"waived\"] }, afterPrs: array, dependencyStage: { type: \"string\", enum: [\"merged\", \"deployed\"] }, evidence: string, ask: { ...string, description: \"With blocked: the question the developer must answer (waiting on a PR or agent is status=waiting).\" }, enable_follow_up: boolean, communication, trigger }, [\"title\", \"status\"]],",
30
- " [\"acknowledge_batch\", \"Record a follow-up result. Complete only after verifying all tasks; blocked surfaces the reason to the developer. Always acknowledge before ending a repair turn. Keep the result within 2000 characters.\", \"follow.acknowledge\", { batchId: string, outcome: { type: \"string\", enum: [\"completed\", \"blocked\"] }, result: { ...string, maxLength: 2000 } }, [\"batchId\", \"outcome\", \"result\"]],",
30
+ " [\"acknowledge_batch\", \"Record a follow-up result. Complete only after verifying all tasks; blocked surfaces the reason to the developer. Blocked with humanOnly=true when nothing is left for an agent and only a person can move it (a reviewer must re-review or dismiss a stale review, access must be granted): the developer gets a PR item, not an agent failure. Always acknowledge before ending a repair turn. Keep the result within 2000 characters.\", \"follow.acknowledge\", { batchId: string, outcome: { type: \"string\", enum: [\"completed\", \"blocked\"] }, result: { ...string, maxLength: 2000 }, humanOnly: { type: \"boolean\" } }, [\"batchId\", \"outcome\", \"result\"]],",
31
31
  " [\"ask_question\", \"Ask the developer a decision you can't make yourself. Give a short title, the question, lettered options A, B, C… with what each means for them, and recommend the option you'd pick. Set big only when building ahead would send something off this computer, set something people or programs outside the repo rely on, or most remaining work would build on it. Link a PR (owner/repo#number) or task id when it is about one. The reply says the question mode and exactly what to do until the answer arrives. Asking something already open returns the open question (\\\"Already open as Q18\\\") instead of a second one; to change an open question's options, ask again with supersedes=\\\"Q18\\\". At the end of the turn point at it with needs_you questions=[\\\"Q18\\\"], don't restate it. URLs and owner/repo#123 in the question, background and options are clickable for the developer. Every card already ends with a built-in \\\"Something else\\\" choice where the developer writes their own answer; don't add an \\\"Other\\\" option yourself.\", \"follow.ask-question\", { title: { ...string, maxLength: 120 }, question: { ...string, maxLength: 2000 }, options: { type: \"array\", maxItems: 26, items: { type: \"object\", properties: { letter: { type: \"string\", pattern: \"^[A-Z]$\" }, label: { ...string, maxLength: 200 }, consequence: { ...string, maxLength: 600 } }, required: [\"letter\", \"label\"], additionalProperties: false } }, recommend: string, big: string, background: string, links: { type: \"array\", maxItems: 10, items: { type: \"object\", properties: { url: string, path: string, label: string }, additionalProperties: false } }, pr: string, task: string, supersedes: { type: \"string\", pattern: \"^Q\\\\d+$\" } }, [\"title\", \"question\"]],",
32
32
  " [\"record_answer\", \"Record the developer's answer when they answered a question in chat instead of in Follow-up. choice is an option letter, \\\"other\\\" when they chose none of your options (words is then required: their answer), or their short answer when there were no options; words is what they said.\", \"follow.record-answer\", { id: string, choice: string, words: string }, [\"id\", \"choice\"]],",
33
33
  " [\"context_reply\", \"Answer the developer's More context ask with the requestId it gave: { requestId, text }, plain words. Only when asked.\", \"follow.context-reply\", { requestId: { ...string, maxLength: 80 }, text: { ...string, minLength: 1, maxLength: 4000 } }, [\"requestId\", \"text\"]],",
@@ -54,7 +54,7 @@ export const mcpSource: string = [
54
54
  " [\"send_repairs\", \"Send a workspace's next message (its queued tasks) to its main agent now, like Send now. Only when the developer asked. batchId defaults to the queued one.\", \"follow.agent-act\", { workspace: string, batchId: string }, [\"workspace\"]],",
55
55
  " [\"set_auto_send\", \"Turn Auto-send on or off for a workspace, or for one task (task: its key), like its switch. Only when the developer asked.\", \"follow.agent-act\", { workspace: string, value: boolean, task: string }, [\"workspace\", \"value\"]],",
56
56
  " [\"clear_hold\", \"Resume Follow-up on a held workspace, like the Resume button. Only when the developer asked.\", \"follow.agent-act\", { workspace: string }, [\"workspace\"]],",
57
- " [\"retry_batch\", \"Retry like the Retry button: an uncertain message (batchId) or one capped task (task: its key). Only when the developer asked.\", \"follow.agent-act\", { workspace: string, batchId: string, task: string }, [\"workspace\"]],",
57
+ " [\"retry_batch\", \"Retry like the Retry button: an uncertain message (batchId), or one capped task or one task waiting on a person (task: its key; Send to agent). Only when the developer asked.\", \"follow.agent-act\", { workspace: string, batchId: string, task: string }, [\"workspace\"]],",
58
58
  " [\"track\", \"Follow a workspace again after the developer opted it out in Settings. Follow-up follows every workspace by default. Only when the developer asked.\", \"follow.agent-act\", { workspace: string }, [\"workspace\"]],",
59
59
  " [\"workspace_about\", \"Read a workspace's Summary: one sentence on what the workspace is for (a reminder, not a status), plus the Linear issues, PRs, Slack threads and docs found in its own text. Read-only unless refresh=true, which writes a new sentence like the panel's Rewrite; otherwise it writes one only when none is cached (up to ~90 s). workspaceId is a workspace id or exact title from list_prs.\", \"follow.agent-act\", { workspaceId: string, refresh: boolean }, [\"workspaceId\"]],",
60
60
  " [\"link_items\", \"Read any workspace's linked items: Linear issues, Slack threads, docs, artifacts (the spec among them) and GitHub issues, each with its origin (registered, manual, spec, published, extracted), plus what was removed. workspaceId is a workspace id from list_prs.\" + read, \"follow.agent-act\", { workspaceId: string }, [\"workspaceId\"]],",
@@ -258,7 +258,7 @@ export const mcpSource: string = [
258
258
  " if (type === \"string\" && (schema.minLength !== undefined && value.length < schema.minLength || schema.maxLength !== undefined && value.length > schema.maxLength)) throw new Error(`${path}: outside the allowed length.`);",
259
259
  "}",
260
260
  "function currentWork(w) {",
261
- " return { id: w.id, title: w.title, goal: w.goal, mainAgentId: w.mainAgentId, enable_tracking: w.enable_tracking, enable_auto_sends: w.enable_auto_sends, hold: w.hold, archived: w.archived, runtimeBusy: w.runtimeBusy, runtimeReason: w.runtimeReason, backgroundBusy: w.backgroundBusy, completion: w.completion,",
261
+ " return { id: w.id, title: w.title, goal: w.goal, mainAgentId: w.mainAgentId, enable_tracking: w.enable_tracking, enable_auto_sends: w.enable_auto_sends, hold: w.hold, archived: w.archived, runtimeBusy: w.runtimeBusy, runtimeReason: w.runtimeReason, backgroundBusy: w.backgroundBusy, mainBusy: w.mainBusy ?? null, completion: w.completion,",
262
262
  " prs: w.prs.map(p => ({ key: p.key, stack: p.stack, parent: p.parent, disposition: p.disposition, error: p.error, ...(p.snapshot ? { title: p.snapshot.title, state: p.snapshot.state, head: p.snapshot.head, draft: p.snapshot.draft, reviewDecision: p.snapshot.reviewDecision, conflict: p.snapshot.conflict, openThreads: p.snapshot.threads.length, failedChecks: p.snapshot.failedChecks, otherFailedChecks: p.snapshot.otherFailedChecks ?? [], deployment: p.snapshot.deployment } : {}) })),",
263
263
  " obligations: w.obligations.filter(o => ![\"done\", \"waived\"].includes(o.status)), completedObligations: w.obligations.filter(o => [\"done\", \"waived\"].includes(o.status)).length,",
264
264
  " openQuestions: (w.questions ?? []).filter(q => !q.answer && !q.closed).map(q => ({ id: q.id, title: q.title, question: q.question, options: q.options, recommend: q.recommend, big: q.big, mode: q.mode, askedBy: q.askedBy, taskId: q.taskId })),",
@@ -298,7 +298,7 @@ export const mcpSource: string = [
298
298
  " for (const resolve of candidates) try { return await import(resolve()); } catch {}",
299
299
  " throw new Error(\"Cannot load the installed Paseo client. Reload Follow-up to refresh its runtime connection.\");",
300
300
  "}",
301
- "const batchInstructionsMain = \"Follow-up batches contain a header with the batchId and ordered tasks. A batch can arrive as one part of a message, after an answer, separated by a line holding only ---; the part starts with its own header. Read workspace_status and refresh live conditions; skip resolved tasks. Process PRs bottom to top, one fully before the next, using the repository's /fix-pr and safe reparent workflow. Validate feedback, verify changes, submit with Graphite --publish, reply/resolve addressed threads and preserve uncommitted work. Post-deploy tasks require verified serving revisions and existing production permissions. Stakeholder update requests are follow-up tasks: retain the original thread, recipient and developer authorization in communication. Use current evidence, distinguish fixed/deployed/verified, and read existing replies before posting. Record the sent replyUrl; a draft or uncertain send stays blocked and must be checked before retrying. Auto authorizes agent delivery only. Acknowledge the header's batchId with acknowledge_batch before finishing (completed with the result, or blocked with the reason), before declare_done for completion batches. Declare Done only after the whole goal and post-merge work are verified. Leave merging and archiving to the developer.\";",
301
+ "const batchInstructionsMain = \"Follow-up batches contain a header with the batchId and ordered tasks. A batch can arrive as one part of a message, after an answer, separated by a line holding only ---; the part starts with its own header. Read workspace_status and refresh live conditions; skip resolved tasks. Process PRs bottom to top, one fully before the next, using the repository's /fix-pr and safe reparent workflow. Validate feedback, verify changes, submit with Graphite --publish, reply/resolve addressed threads and preserve uncommitted work. Post-deploy tasks require verified serving revisions and existing production permissions. Stakeholder update requests are follow-up tasks: retain the original thread, recipient and developer authorization in communication. Use current evidence, distinguish fixed/deployed/verified, and read existing replies before posting. Record the sent replyUrl; a draft or uncertain send stays blocked and must be checked before retrying. Auto authorizes agent delivery only. Acknowledge the header's batchId with acknowledge_batch before finishing (completed with the result, or blocked with the reason; add humanOnly=true when only a person can move it, such as a stale review the reviewer must re-review or dismiss), before declare_done for completion batches. Declare Done only after the whole goal and post-merge work are verified. Leave merging and archiving to the developer.\";",
302
302
  "/** A No review repository (Settings → PR workflow → Review): nobody else reviews, so the agent merges its own PRs. */",
303
303
  "const noReviewMerge = \"This repository has no review: merge your own PR once CI is green, without asking the developer. Leave archiving to the developer.\";",
304
304
  "/**",
package/server/mcp.mjs CHANGED
@@ -25,7 +25,7 @@ const tools = [
25
25
  ["register_pr", "Register a PR produced by this workspace. Call after every submission. Register parents first; repeat to update its stack or parent after restacking. Supply a disposition for a deliberately closed PR. Set agentMerges: true when you merge this PR yourself (no human review): Follow-up then never asks the developer to add reviewers or merge it, and the workspace reads as waiting on you; set it false to hand the merge back. In a repository set to No review (set_pr_workflow review \"none\") every PR counts as agentMerges unless you set it false.", "follow.register-pr", { repo: string, number: integer, stack: string, parentNumber: { type: ["integer", "null"], minimum: 1 }, disposition: string, agentMerges: boolean }, ["repo", "number", "stack"]],
26
26
  ["exclude_stack", "Correct an unrelated stack registration. Preserve its PRs and requirements in an exclusion audit; future registration is blocked. reason must cite the scope/ownership evidence. obligationIds may include related tasks without PR dependencies. Keep external dependencies separate from owned work.", "follow.exclude-stack", { stack: string, reason: string, obligationIds: array }, ["stack", "reason"]],
27
27
  ["update_obligation", "Record concrete follow-up: verification, migrations, decisions or stakeholder replies. Never add approve/merge/deploy checklist tasks. afterPrs uses owner/repo#number keys. Tasks are manual unless explicitly scheduled with trigger={event:\"now\"|\"merge\"|\"deploy\",delayDays:0}. Only set a trigger from the developer’s requested timing; never infer timing from a title or enable_follow_up alone. Merge/deploy triggers require owned afterPrs; delayDays=14 waits fourteen days after the last dependency event. Now requires no PR dependencies or delay. Deployment timing starts at the first verified fully serving observation and remains conservative when history is unknown. Preserve existing trigger fields on updates; trigger=null makes a task manual. Auto controls delivery, not timing or production permissions. For Slack replies, communication records the original threadUrl, recipient, purpose (progress or verified), explicit developer authorization and sent replyUrl. Empty authorization never queues a reply; Auto does not authorize external posts. Use a verify-and-reply task after deployment for the final update. Read the thread first; mark blocked when posting is unavailable or uncertain, never treat a draft as sent. Done requires replyUrl and evidence; preserve fields when updating. status=working records you as the agent doing it; pass workingAgentId when another agent (your subagent) is.", "follow.obligation", { id: string, workingAgentId: string, title: string, status: { type: "string", enum: ["pending", "waiting", "working", "blocked", "done", "waived"] }, afterPrs: array, dependencyStage: { type: "string", enum: ["merged", "deployed"] }, evidence: string, ask: { ...string, description: "With blocked: the question the developer must answer (waiting on a PR or agent is status=waiting)." }, enable_follow_up: boolean, communication, trigger }, ["title", "status"]],
28
- ["acknowledge_batch", "Record a follow-up result. Complete only after verifying all tasks; blocked surfaces the reason to the developer. Always acknowledge before ending a repair turn. Keep the result within 2000 characters.", "follow.acknowledge", { batchId: string, outcome: { type: "string", enum: ["completed", "blocked"] }, result: { ...string, maxLength: 2000 } }, ["batchId", "outcome", "result"]],
28
+ ["acknowledge_batch", "Record a follow-up result. Complete only after verifying all tasks; blocked surfaces the reason to the developer. Blocked with humanOnly=true when nothing is left for an agent and only a person can move it (a reviewer must re-review or dismiss a stale review, access must be granted): the developer gets a PR item, not an agent failure. Always acknowledge before ending a repair turn. Keep the result within 2000 characters.", "follow.acknowledge", { batchId: string, outcome: { type: "string", enum: ["completed", "blocked"] }, result: { ...string, maxLength: 2000 }, humanOnly: { type: "boolean" } }, ["batchId", "outcome", "result"]],
29
29
  ["ask_question", "Ask the developer a decision you can't make yourself. Give a short title, the question, lettered options A, B, C… with what each means for them, and recommend the option you'd pick. Set big only when building ahead would send something off this computer, set something people or programs outside the repo rely on, or most remaining work would build on it. Link a PR (owner/repo#number) or task id when it is about one. The reply says the question mode and exactly what to do until the answer arrives. Asking something already open returns the open question (\"Already open as Q18\") instead of a second one; to change an open question's options, ask again with supersedes=\"Q18\". At the end of the turn point at it with needs_you questions=[\"Q18\"], don't restate it. URLs and owner/repo#123 in the question, background and options are clickable for the developer. Every card already ends with a built-in \"Something else\" choice where the developer writes their own answer; don't add an \"Other\" option yourself.", "follow.ask-question", { title: { ...string, maxLength: 120 }, question: { ...string, maxLength: 2000 }, options: { type: "array", maxItems: 26, items: { type: "object", properties: { letter: { type: "string", pattern: "^[A-Z]$" }, label: { ...string, maxLength: 200 }, consequence: { ...string, maxLength: 600 } }, required: ["letter", "label"], additionalProperties: false } }, recommend: string, big: string, background: string, links: { type: "array", maxItems: 10, items: { type: "object", properties: { url: string, path: string, label: string }, additionalProperties: false } }, pr: string, task: string, supersedes: { type: "string", pattern: "^Q\\d+$" } }, ["title", "question"]],
30
30
  ["record_answer", "Record the developer's answer when they answered a question in chat instead of in Follow-up. choice is an option letter, \"other\" when they chose none of your options (words is then required: their answer), or their short answer when there were no options; words is what they said.", "follow.record-answer", { id: string, choice: string, words: string }, ["id", "choice"]],
31
31
  ["context_reply", "Answer the developer's More context ask with the requestId it gave: { requestId, text }, plain words. Only when asked.", "follow.context-reply", { requestId: { ...string, maxLength: 80 }, text: { ...string, minLength: 1, maxLength: 4000 } }, ["requestId", "text"]],
@@ -52,7 +52,7 @@ const actionTools = [
52
52
  ["send_repairs", "Send a workspace's next message (its queued tasks) to its main agent now, like Send now. Only when the developer asked. batchId defaults to the queued one.", "follow.agent-act", { workspace: string, batchId: string }, ["workspace"]],
53
53
  ["set_auto_send", "Turn Auto-send on or off for a workspace, or for one task (task: its key), like its switch. Only when the developer asked.", "follow.agent-act", { workspace: string, value: boolean, task: string }, ["workspace", "value"]],
54
54
  ["clear_hold", "Resume Follow-up on a held workspace, like the Resume button. Only when the developer asked.", "follow.agent-act", { workspace: string }, ["workspace"]],
55
- ["retry_batch", "Retry like the Retry button: an uncertain message (batchId) or one capped task (task: its key). Only when the developer asked.", "follow.agent-act", { workspace: string, batchId: string, task: string }, ["workspace"]],
55
+ ["retry_batch", "Retry like the Retry button: an uncertain message (batchId), or one capped task or one task waiting on a person (task: its key; Send to agent). Only when the developer asked.", "follow.agent-act", { workspace: string, batchId: string, task: string }, ["workspace"]],
56
56
  ["track", "Follow a workspace again after the developer opted it out in Settings. Follow-up follows every workspace by default. Only when the developer asked.", "follow.agent-act", { workspace: string }, ["workspace"]],
57
57
  ["workspace_about", "Read a workspace's Summary: one sentence on what the workspace is for (a reminder, not a status), plus the Linear issues, PRs, Slack threads and docs found in its own text. Read-only unless refresh=true, which writes a new sentence like the panel's Rewrite; otherwise it writes one only when none is cached (up to ~90 s). workspaceId is a workspace id or exact title from list_prs.", "follow.agent-act", { workspaceId: string, refresh: boolean }, ["workspaceId"]],
58
58
  ["link_items", "Read any workspace's linked items: Linear issues, Slack threads, docs, artifacts (the spec among them) and GitHub issues, each with its origin (registered, manual, spec, published, extracted), plus what was removed. workspaceId is a workspace id from list_prs." + read, "follow.agent-act", { workspaceId: string }, ["workspaceId"]],
@@ -256,7 +256,7 @@ function validate(value, schema, path = "arguments") {
256
256
  if (type === "string" && (schema.minLength !== undefined && value.length < schema.minLength || schema.maxLength !== undefined && value.length > schema.maxLength)) throw new Error(`${path}: outside the allowed length.`);
257
257
  }
258
258
  function currentWork(w) {
259
- return { id: w.id, title: w.title, goal: w.goal, mainAgentId: w.mainAgentId, enable_tracking: w.enable_tracking, enable_auto_sends: w.enable_auto_sends, hold: w.hold, archived: w.archived, runtimeBusy: w.runtimeBusy, runtimeReason: w.runtimeReason, backgroundBusy: w.backgroundBusy, completion: w.completion,
259
+ return { id: w.id, title: w.title, goal: w.goal, mainAgentId: w.mainAgentId, enable_tracking: w.enable_tracking, enable_auto_sends: w.enable_auto_sends, hold: w.hold, archived: w.archived, runtimeBusy: w.runtimeBusy, runtimeReason: w.runtimeReason, backgroundBusy: w.backgroundBusy, mainBusy: w.mainBusy ?? null, completion: w.completion,
260
260
  prs: w.prs.map(p => ({ key: p.key, stack: p.stack, parent: p.parent, disposition: p.disposition, error: p.error, ...(p.snapshot ? { title: p.snapshot.title, state: p.snapshot.state, head: p.snapshot.head, draft: p.snapshot.draft, reviewDecision: p.snapshot.reviewDecision, conflict: p.snapshot.conflict, openThreads: p.snapshot.threads.length, failedChecks: p.snapshot.failedChecks, otherFailedChecks: p.snapshot.otherFailedChecks ?? [], deployment: p.snapshot.deployment } : {}) })),
261
261
  obligations: w.obligations.filter(o => !["done", "waived"].includes(o.status)), completedObligations: w.obligations.filter(o => ["done", "waived"].includes(o.status)).length,
262
262
  openQuestions: (w.questions ?? []).filter(q => !q.answer && !q.closed).map(q => ({ id: q.id, title: q.title, question: q.question, options: q.options, recommend: q.recommend, big: q.big, mode: q.mode, askedBy: q.askedBy, taskId: q.taskId })),
@@ -296,7 +296,7 @@ async function loadClient() {
296
296
  for (const resolve of candidates) try { return await import(resolve()); } catch {}
297
297
  throw new Error("Cannot load the installed Paseo client. Reload Follow-up to refresh its runtime connection.");
298
298
  }
299
- const batchInstructionsMain = "Follow-up batches contain a header with the batchId and ordered tasks. A batch can arrive as one part of a message, after an answer, separated by a line holding only ---; the part starts with its own header. Read workspace_status and refresh live conditions; skip resolved tasks. Process PRs bottom to top, one fully before the next, using the repository's /fix-pr and safe reparent workflow. Validate feedback, verify changes, submit with Graphite --publish, reply/resolve addressed threads and preserve uncommitted work. Post-deploy tasks require verified serving revisions and existing production permissions. Stakeholder update requests are follow-up tasks: retain the original thread, recipient and developer authorization in communication. Use current evidence, distinguish fixed/deployed/verified, and read existing replies before posting. Record the sent replyUrl; a draft or uncertain send stays blocked and must be checked before retrying. Auto authorizes agent delivery only. Acknowledge the header's batchId with acknowledge_batch before finishing (completed with the result, or blocked with the reason), before declare_done for completion batches. Declare Done only after the whole goal and post-merge work are verified. Leave merging and archiving to the developer.";
299
+ const batchInstructionsMain = "Follow-up batches contain a header with the batchId and ordered tasks. A batch can arrive as one part of a message, after an answer, separated by a line holding only ---; the part starts with its own header. Read workspace_status and refresh live conditions; skip resolved tasks. Process PRs bottom to top, one fully before the next, using the repository's /fix-pr and safe reparent workflow. Validate feedback, verify changes, submit with Graphite --publish, reply/resolve addressed threads and preserve uncommitted work. Post-deploy tasks require verified serving revisions and existing production permissions. Stakeholder update requests are follow-up tasks: retain the original thread, recipient and developer authorization in communication. Use current evidence, distinguish fixed/deployed/verified, and read existing replies before posting. Record the sent replyUrl; a draft or uncertain send stays blocked and must be checked before retrying. Auto authorizes agent delivery only. Acknowledge the header's batchId with acknowledge_batch before finishing (completed with the result, or blocked with the reason; add humanOnly=true when only a person can move it, such as a stale review the reviewer must re-review or dismiss), before declare_done for completion batches. Declare Done only after the whole goal and post-merge work are verified. Leave merging and archiving to the developer.";
300
300
  /** A No review repository (Settings → PR workflow → Review): nobody else reviews, so the agent merges its own PRs. */
301
301
  const noReviewMerge = "This repository has no review: merge your own PR once CI is green, without asking the developer. Leave archiving to the developer.";
302
302
  /**
@@ -34,7 +34,9 @@ export function activity(w: Workspace): Activity[] {
34
34
  if (!b.sentAt) continue;
35
35
  const n = plural(b.tasks.length, "task");
36
36
  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 });
37
- 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) });
37
+ // A human-only outcome (Batch.humanOnly) isn't finished work: it waits on a person.
38
+ if (b.settledAt && b.state === "completed" && b.humanOnly) rows.push({ key: `done:${b.id}`, at: b.settledAt, icon: "UserRound", tone: "warning", text: `${n} ${b.tasks.length === 1 ? "waits" : "wait"} on a person, not the agent`, detail: b.result || null, took: duration(b.sentAt, b.settledAt) });
39
+ else 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) });
38
40
  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) });
39
41
  }
40
42
  for (const p of w.prs) if (p.snapshot?.state === "MERGED" && p.snapshot.mergedAt)
@@ -3,7 +3,7 @@ import { deliveryStatus } from "./queue";
3
3
  import { sentence } from "./errors";
4
4
  import { blockedOnDeveloper, completionCheck, liveWorkingTask, statusKnown, summary, type Task, type Status } from "./model";
5
5
  import type { ListBatch as Batch, ListPr as Pr, ListWorkspace as Workspace } from "./list";
6
- import { IDLE_REASON, NO_PROGRESS_CAP } from "./send-decision";
6
+ import { IDLE_REASON, MAIN_WAIT, NO_PROGRESS_CAP, QUIET_WAIT, mainWait } from "./send-decision";
7
7
  import { workingLine } from "./task-status";
8
8
  import { followUpObligations, recoveryBatch } from "./follow-up";
9
9
  import { orderedStacks, prLink, settledForDisplay, type PrLink } from "./presentation";
@@ -96,7 +96,11 @@ export const workflowReady = (pr: Pr) => isGithubFlow(pr.snapshot) ? mergeBlocke
96
96
  /** Why a pending batch cannot be sent right now, or null when Send is available. Mirrors the server's guards. */
97
97
  export function sendBlocker(w: Workspace, batch: Batch): string | null {
98
98
  if (w.hold) return "Resume follow-up first";
99
- if (w.runtimeBusy) return "Sends after the agent's current turn";
99
+ // The Done check waits for the whole workspace; a repair only for the main agent's own wait (Q96 = A), said in the
100
+ // send decision's words.
101
+ if (completionCheck(batch) && (w.runtimeBusy || w.backgroundBusy)) return capitalize(QUIET_WAIT);
102
+ const main = mainWait(w);
103
+ if (main) return capitalize(MAIN_WAIT[main]);
100
104
  if (w.runtimeReason) return w.runtimeReason;
101
105
  if (w.batches.some(other => other.id !== batch.id && ["sending", "sent", "blocked", "uncertain"].includes(other.state))) return "Another batch is still open";
102
106
  return null;
@@ -107,6 +111,12 @@ type NeedItemBase =
107
111
  | { kind: "retry"; key: string; batchId: string; title: string; detail: string; exhausted: boolean }
108
112
  /** One task that went out NO_PROGRESS_CAP times with no change (Q49): Retry sends that task again; the rest of the queue moves on. */
109
113
  | { kind: "capped"; key: string; taskKey: string; title: string; detail: string }
114
+ /**
115
+ * A task the agent said only a person can move (Batch.humanOnly): the developer's, never an agent failure
116
+ * (a-human-only-outcome-is-a-human-item). `review`: a review only its reviewer can change, so the item asks for a
117
+ * re-review (the PR sheet's reviewers). Send to agent hands it back (retryTask, the retry_batch tool).
118
+ */
119
+ | { kind: "person"; key: string; taskKey: string; prKey: string | null; review: boolean; title: string; detail: string }
110
120
  /** `finish`: the Done check. It never auto-sends, so it always waits on you. */
111
121
  | { kind: "send"; key: string; batchId: string; title: string; tasks: string[]; blocker: string | null; finish?: true }
112
122
  | { kind: "decision"; key: string; obligationId: string; title: string; detail: string }
@@ -129,6 +139,11 @@ const capitalize = (s: string) => s[0].toUpperCase() + s.slice(1);
129
139
  /** The Needs-you Send while Auto is off: how much waits and why, never the workspace's title (say it once, Q51). */
130
140
  export const autoOffLine = (n: number) => `${plural(n, "task")} ready · auto-send is off here`;
131
141
  export const agentName = (w: Pick<Workspace, "mainAgentTitle">) => w.mainAgentTitle?.trim() || "the main agent";
142
+ /** A person task's Needs-you title: whom it waits on, never "didn't finish". */
143
+ export function personTitle(t: Pick<Task, "kind" | "title">, number?: number): string {
144
+ if (number === undefined) return `${t.title}: waits on a person, not the agent`;
145
+ return t.kind === "review" ? `#${number} waits on its reviewer` : `#${number} waits on a person, not the agent`;
146
+ }
132
147
  /** A capped task's Needs-you title: what is still wrong, in plain words. */
133
148
  export function cappedTitle(t: Pick<Task, "kind" | "target" | "title">): string {
134
149
  const pr = `#${t.target.split("#")[1] ?? t.target}`;
@@ -192,6 +207,12 @@ function computeNeedsYou(w: Workspace, now: number): NeedItem[] {
192
207
  for (const h of (w.heldTasks ?? []).filter(h => h.held === "capped"))
193
208
  items.push({ kind: "capped", key: `capped:${h.task.key}`, taskKey: h.task.key, title: cappedTitle(h.task), ...linkFor(h.task.target),
194
209
  detail: `Sent ${NO_PROGRESS_CAP} times and GitHub shows no change. Check ${agentName(w)}'s chat, then retry.` });
210
+ for (const h of (w.heldTasks ?? []).filter(h => h.held === "person")) {
211
+ const why = [...w.batches].reverse().find(b => b.humanOnly && b.state === "completed" && b.tasks.some(t => t.key === h.task.key))?.result;
212
+ const pr = w.prs.find(p => p.key === h.task.target);
213
+ items.push({ kind: "person", key: `person:${h.task.key}`, taskKey: h.task.key, prKey: pr?.key ?? null, review: h.task.kind === "review", title: personTitle(h.task, pr?.number), ...linkFor(h.task.target),
214
+ detail: why || `${capitalize(agentName(w))} says nothing is left for an agent here.` });
215
+ }
195
216
  for (const a of w.prActions.filter(a => a.state === "uncertain")) {
196
217
  const numbers = a.prs.map(key => `#${key.split("#")[1]}`).join(", ");
197
218
  items.push({ kind: "check", key: `check:${a.id}`, actionId: a.id, ...(a.prs.length === 1 ? linkFor(a.prs[0]) : {}), title: `Check the ${a.kind === "merge" ? "merge" : a.kind === "request_reviewers" ? "reviewer request" : "merge-when-ready change"} on ${numbers}`, detail: a.result });
@@ -295,7 +316,9 @@ export function headline(w: Workspace, now = Date.now()): HeadlinePart[] {
295
316
  else parts.push({ text: `${bar.merged} of ${plural(bar.total, "PR")} merged` });
296
317
  const need = needsYou(w, now).length;
297
318
  if (need) parts.push({ text: `${need} need${need === 1 ? "s" : ""} you`, tone: "warning" });
298
- const repair = w.prs.filter(needsRepair).length;
319
+ // A PR whose only open condition waits on a person (a-human-only-outcome-is-a-human-item) isn't the agent's to fix.
320
+ const personOnly = (p: Pr) => !p.snapshot?.conflict && !p.snapshot?.failedChecks?.length && !!w.heldTasks?.some(h => h.held === "person" && h.task.target === p.key);
321
+ const repair = w.prs.filter(p => needsRepair(p) && !personOnly(p)).length;
299
322
  if (repair) parts.push({ text: `${repair} to fix`, tone: "danger" });
300
323
  return parts;
301
324
  }
@@ -328,7 +351,8 @@ export function liveLine(w: Workspace, now = Date.now()): { icon: LiveIcon; text
328
351
  if (w.runtimeReason) return { icon: "waiting", text: w.runtimeReason, since: null };
329
352
  // Queued work, in the same words as the agent card and Home (shared/status.ts). Repairs you send by hand live in Needs you.
330
353
  if (view?.phase === "queued" && (view.kind === "finish" || w.enable_auto_sends)) return { icon: "waiting", text: view.line, since: view.batch.createdAt };
331
- if (w.runtimeBusy) return { icon: "spinner", text: "Main agent is working", since: null };
354
+ // Say who: the main agent only when it is its own turn (Q96 = A), never for a subagent at work beside an idle main.
355
+ if (w.runtimeBusy) return { icon: "spinner", text: mainWait(w) === "turn" ? "Main agent is working" : "Agents in this workspace are working", since: null };
332
356
  // A working task spins only while its recorded agent is running (invariant `a-task-only-says-working-when-its-agent-is`).
333
357
  // Otherwise it says what the task row says: "<agent> idle", "<agent> closed", "Agent unavailable" or "In progress", with no spinner.
334
358
  const live = liveWorkingTask(w);
@@ -205,7 +205,7 @@ export function statsOf(s: Session): SessionStats {
205
205
  * anywhere presets. Paseo takes Shift+? (its shortcuts dialog) and Escape (interrupt agent) when focus is outside a
206
206
  * field, which is exactly when these fire, so the sheet is S and leaving is X.
207
207
  */
208
- export type CatchUpAction = "pick" | "own" | "send" | "skip" | "skip-workspace" | "back" | "more" | "chip" | "ask" | "note" | "later" | "chat" | "rail" | "rail-up" | "rail-down" | "keys" | "leave";
208
+ export type CatchUpAction = "pick" | "own" | "send" | "skip" | "skip-workspace" | "back" | "more" | "chip" | "ask" | "note" | "later" | "chat" | "rail" | "rail-up" | "rail-down" | "keys" | "leave" | "dictate";
209
209
  /**
210
210
  * a-move-bar-action-opens-in-view: where each move-bar action opens what it opens, so its result is where the eye
211
211
  * already is and never appended below the fold. `sheet`: drawn in the phone's dock, above the bar, kept above the
@@ -225,7 +225,8 @@ export const MOVE_OPENS: Readonly<Record<"more" | "later" | "note" | "chat" | "r
225
225
  /** A key as this platform spells it: ⌘ on a Mac, Ctrl elsewhere (as the Send button's own hint reads). */
226
226
  export const keyLabel = (key: string, mac: boolean) => mac ? key : key.replace("⌘", "Ctrl ");
227
227
 
228
- export const CATCH_UP_KEYS: readonly { key: string; what: string; action: CatchUpAction; combos: readonly string[]; when?: "more" | "rail" }[] = [
228
+ export const CATCH_UP_KEYS: readonly { key: string; what: string; action: CatchUpAction; combos: readonly string[]; when?: "more" | "rail";
229
+ /** Listed only on a host that has it: V is Paseo's dictation, on a Paseo with usePaseoDictation. */ needs?: "dictation" }[] = [
229
230
  { key: "A–H", what: "Pick an option", action: "pick", combos: ["A", "B", "C", "D", "E", "F", "G", "H"] },
230
231
  { key: "W", what: "Write your own answer", action: "own", combos: ["W"] },
231
232
  { key: "⌘↵", what: "Send", action: "send", combos: ["Cmd+Enter", "Ctrl+Enter"] },
@@ -236,6 +237,7 @@ export const CATCH_UP_KEYS: readonly { key: string; what: string; action: CatchU
236
237
  { key: "1–4", what: "Pick a More context ask", action: "chip", combos: ["Digit"], when: "more" },
237
238
  { key: "⌘↵", what: "Ask the agent", action: "ask", combos: ["Cmd+Enter", "Ctrl+Enter"], when: "more" },
238
239
  { key: "N", what: "Add a note", action: "note", combos: ["N"] },
240
+ { key: "V", what: "Dictate your answer, and stop", action: "dictate", combos: ["V"], needs: "dictation" },
239
241
  { key: "L", what: "Later", action: "later", combos: ["L"] },
240
242
  { key: "O", what: "Open chat", action: "chat", combos: ["O"] },
241
243
  { key: "R", what: "Go to the queue, and back", action: "rail", combos: ["R"] },
@@ -267,7 +269,7 @@ export function catchUpKey(e: KeyPress, at: { typing: boolean; inMore: boolean;
267
269
  if (e.shift || e.key.length !== 1) return null;
268
270
  const k = e.key.toLowerCase();
269
271
  if (/^[a-h]$/.test(k)) return { action: "pick", arg: k.toUpperCase() };
270
- const byLetter: Record<string, CatchUpAction> = { w: "own", j: "skip", k: "back", m: "more", n: "note", l: "later", o: "chat", r: "rail", s: "keys", x: "leave" };
272
+ const byLetter: Record<string, CatchUpAction> = { w: "own", j: "skip", k: "back", m: "more", n: "note", l: "later", o: "chat", r: "rail", s: "keys", x: "leave", v: "dictate" };
271
273
  return byLetter[k] ? { action: byLetter[k] } : null;
272
274
  }
273
275
 
@@ -46,7 +46,7 @@ export const enrollRpc = defineRpc({ name: "follow.enroll", input: z.strictObjec
46
46
  export const registerPrRpc = defineRpc({ name: "follow.register-pr", input: z.strictObject({ agentId: idSchema, repo: z.string().regex(/^[\w.-]+\/[\w.-]+$/), number: z.number().int().positive(), stack: textSchema, parentNumber: z.number().int().positive().nullable().optional(), disposition: z.string().max(2000).optional(), agentMerges: z.boolean().optional() }), output: workspaceSchema });
47
47
  export const obligationRpc = defineRpc({ name: "follow.obligation", input: z.strictObject({ agentId: idSchema, workingAgentId: idSchema.optional(), id: idSchema.optional(), title: textSchema, status: z.enum(["pending", "waiting", "working", "blocked", "done", "waived"]), afterPrs: z.array(idSchema).optional(), dependencyStage: z.enum(["merged", "deployed"]).optional(), evidence: z.string().max(4000).optional(), ask: z.string().trim().min(1).max(1000).optional(), enable_follow_up: z.boolean().optional(), communication: agentCommunicationSchema.optional(), trigger: taskTriggerSchema.strict().nullable().optional() }), output: workspaceSchema.extend({ updatedObligationId: idSchema }) });
48
48
  export const declareDoneRpc = defineRpc({ name: "follow.done", input: z.strictObject({ agentId: idSchema, summary: textSchema }), output: z.object({ workspace: workspaceSchema, blockers: z.array(z.string()), unconfirmed: z.array(z.string()).default([]), alreadyDone: z.boolean().default(false), next: z.string().default("") }) });
49
- export const acknowledgeRpc = defineRpc({ name: "follow.acknowledge", input: z.strictObject({ agentId: idSchema, batchId: idSchema, outcome: z.enum(["completed", "blocked"]), result: textSchema }), output: workspaceSchema });
49
+ export const acknowledgeRpc = defineRpc({ name: "follow.acknowledge", input: z.strictObject({ agentId: idSchema, batchId: idSchema, outcome: z.enum(["completed", "blocked"]), result: textSchema, /** With blocked: only a person can move what is still open (Batch.humanOnly). */ humanOnly: z.boolean().optional() }), output: workspaceSchema });
50
50
  export const controlRpc = defineRpc({ name: "follow.control", input: z.object({ workspaceId: idSchema, enable_auto_sends: z.boolean().optional(), clearHold: z.boolean().optional(), retryBatchId: idSchema.optional(), /** Retry one capped task (Q49): its key. */ retryTask: z.string().max(400).optional(), /** Auto per task: a task key and whether Follow-up sends it. */ taskAuto: z.object({ key: z.string().max(400), auto: z.boolean() }).optional(), /** The developer's "Make main agent": one of the workspace's other root agents. */ mainAgentId: idSchema.optional(),
51
51
  /** Later on a workspace-only Needs-you row; null is Bring back now. */ snooze: z.object({ until: z.string().trim().min(1).max(200) }).nullable().optional() }), output: workspaceSchema });
52
52
  export const refreshRpc = defineRpc({ name: "follow.refresh", input: z.object({ workspaceId: idSchema.optional() }), output: z.object({ ok: z.boolean() }) });
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Dictation in an answer field (dictated-text-lands-in-the-field): the host's usePaseoDictation (Paseo's
3
+ * plugin API, when the host has it) turns speech into text, and the text goes into the same field the keyboard
4
+ * writes to, at the caret, editable, never sent by itself. Pure, so the state machine is tested without a host.
5
+ */
6
+
7
+ /** Paseo's PluginDictation, mirrored: the installed SDK may predate it. */
8
+ export type HostDictationStatus = "idle" | "listening" | "transcribing";
9
+ export type HostDictation = {
10
+ readonly unavailable: { readonly reason: "disconnected" | "not_ready"; readonly message: string | null } | null;
11
+ readonly status: HostDictationStatus;
12
+ readonly volume: number;
13
+ readonly error: string | null;
14
+ start(): Promise<void>;
15
+ stop(): Promise<void>;
16
+ cancel(): Promise<void>;
17
+ };
18
+ export type UseHostDictation = (options: { onText(text: string): void }) => HostDictation;
19
+
20
+ /** The host's hook, or null when this Paseo has none: then there is no mic, no hint and no space for one. */
21
+ export function hostDictationHook(client: unknown): UseHostDictation | null {
22
+ const hook = client && typeof client === "object" ? (client as { usePaseoDictation?: unknown }).usePaseoDictation : undefined;
23
+ return typeof hook === "function" ? hook as UseHostDictation : null;
24
+ }
25
+
26
+ export type MicState = "unavailable" | "idle" | "listening" | "transcribing";
27
+ export type MicView = {
28
+ state: MicState;
29
+ icon: string;
30
+ /** The button's accessible name and desktop tooltip. */
31
+ label: string;
32
+ /** One line under the field, or null. `tone` colors it. */
33
+ line: string | null;
34
+ tone: "muted" | "live" | "danger";
35
+ /** The button does nothing while the words are being written. */
36
+ disabled: boolean;
37
+ };
38
+
39
+ export const DICTATE_KEY = "V";
40
+
41
+ /** What the mic shows. `explain`: the developer pressed an unavailable mic, so it says why (never silently nothing). */
42
+ export function micView(d: Pick<HostDictation, "unavailable" | "status" | "error">, o: { explain?: boolean; key?: boolean } = {}): MicView {
43
+ const k = o.key ? ` (${DICTATE_KEY})` : "";
44
+ if (d.unavailable && d.status === "idle") {
45
+ const why = d.unavailable.reason === "disconnected" ? "the host is offline"
46
+ : d.unavailable.message?.trim() || "set up speech-to-text in Paseo's settings";
47
+ return { state: "unavailable", icon: "MicOff", label: "Dictation isn't available", line: o.explain ? `Can't dictate: ${lower(why)}` : null, tone: "muted", disabled: false };
48
+ }
49
+ if (d.status === "listening") return { state: "listening", icon: "Square", label: `Stop dictating${k}`, line: `Listening · Stop${o.key ? ` (${DICTATE_KEY})` : ""} adds it to your answer`, tone: "live", disabled: false };
50
+ if (d.status === "transcribing") return { state: "transcribing", icon: "Mic", label: "Writing down what you said", line: "Writing it down…", tone: "muted", disabled: true };
51
+ return { state: "idle", icon: "Mic", label: `Dictate${k}`, line: d.error ? `Couldn't dictate: ${denied(d.error) ? "microphone access is blocked. Allow it for Paseo in your settings" : lower(d.error)}` : null, tone: "danger", disabled: false };
52
+ }
53
+ const denied = (error: string) => /permission|denied|not ?allowed/i.test(error);
54
+ const lower = (s: string) => {
55
+ const t = s.trim().replace(/[.\s]+$/, "");
56
+ return /^[A-Z][a-z]/.test(t) ? t[0].toLowerCase() + t.slice(1) : t;
57
+ };
58
+
59
+ /**
60
+ * Put dictated text where the caret is (replacing a selection), with one space between it and the words around it,
61
+ * within the field's length limit. Returns the new words and where the caret goes (after the inserted text).
62
+ */
63
+ export function insertDictated(words: string, text: string, selection?: { start: number; end: number } | null, maxLength = 2000): { words: string; caret: number } {
64
+ const said = text.replace(/\s+/g, " ").trim();
65
+ const start = Math.max(0, Math.min(selection?.start ?? words.length, words.length));
66
+ const end = Math.max(start, Math.min(selection?.end ?? start, words.length));
67
+ if (!said) return { words, caret: end };
68
+ const before = words.slice(0, start); const after = words.slice(end);
69
+ const lead = before && !/\s$/.test(before) ? " " : "";
70
+ const trail = after && !/^[\s.,;:!?)]/.test(after) ? " " : "";
71
+ const room = maxLength - before.length - after.length - lead.length - trail.length;
72
+ if (room <= 0) return { words, caret: end };
73
+ const fit = said.slice(0, room);
74
+ return { words: before + lead + fit + trail + after, caret: before.length + lead.length + fit.length };
75
+ }
@@ -178,6 +178,7 @@ export function workspaceHeadline(items: NeedItem[]): Headline | null {
178
178
  case "hold": return { key: "blocked", label: "On hold", line: top.detail || top.title, source: "workspace" };
179
179
  case "retry": return { key: "blocked", label: "Tasks stuck", line: top.title, source: "workspace" };
180
180
  case "capped": return { key: "blocked", label: "Task unchanged", line: top.title, source: "workspace" };
181
+ case "person": return { key: "blocked", label: top.review ? "Waits on reviewer" : "Waits on a person", line: top.title, source: "workspace" };
181
182
  case "check": return { key: "blocked", label: "Check PR", line: top.title, source: "workspace" };
182
183
  case "message": return { key: "blocked", label: "Message not sent", line: top.title, source: "workspace" };
183
184
  case "answer": return top.waiting ? { key: "decision", label: "Send answer", line: top.title, source: "workspace" } : { key: "blocked", label: "Check answer", line: top.title, source: "workspace" };
package/shared/model.ts CHANGED
@@ -102,6 +102,12 @@ export const batchSchema = z.object({
102
102
  refusal: z.object({ reason: z.string(), at: z.string() }).nullable().optional(),
103
103
  /** The agent's turn ended without acknowledge_batch; Follow-up settled it from GitHub instead (settleUnacknowledged). */
104
104
  unacknowledged: z.boolean().optional(),
105
+ /**
106
+ * The agent acknowledged it blocked with nothing left for an agent: only a person can move what is still open (a
107
+ * reviewer re-reviews or dismisses a stale review, access is granted). Settled completed, and its still-open
108
+ * conditions wait as the developer's held "person" tasks (invariant a-human-only-outcome-is-a-human-item).
109
+ */
110
+ humanOnly: z.boolean().optional(),
105
111
  });
106
112
  export const workspaceSchema = z.object({
107
113
  id: idSchema, title: textSchema, goal: textSchema, mainAgentId: idSchema,
@@ -132,6 +138,15 @@ export const workspaceSchema = z.object({
132
138
  sendWait: z.enum(["unloaded", "setup"]).nullable().optional(),
133
139
  updatedAt: z.string(), managedDoneLabel: z.boolean(),
134
140
  runtimeReason: z.string().nullable(), runtimeBusy: z.boolean(), backgroundBusy: z.boolean().default(false),
141
+ /**
142
+ * What the main agent itself is doing that holds a repair (Q96 = A, invariant a-repair-goes-to-a-free-main-agent): its
143
+ * own turn, its own background job while Wait for background jobs is on, a permission prompt or question, a Session
144
+ * Guard pause or a compaction. Set with runtimeBusy, by the same read
145
+ * (server/daemon.ts observe). runtimeBusy and backgroundBusy stay the whole workspace (Done, "all work finished");
146
+ * other agents and subagents never land here. Absent (a record no refresh has read yet): unknown, so the send
147
+ * decision treats the workspace's busy as the main agent's (Unknown is not off).
148
+ */
149
+ mainBusy: z.enum(["turn", "jobs", "permission", "guard", "compacting"]).nullable().optional(),
135
150
  /** Live state of the agents this workspace's working tasks name, refreshed with runtimeBusy from Paseo's agent list
136
151
  * (metadata only). Every surface that says a task's agent is working reads this, never the stored status alone. */
137
152
  taskAgents: z.record(z.string(), z.object({ title: z.string().nullable(), state: z.enum(["working", "idle", "closed", "archived"]) })).optional(),
@@ -158,8 +173,8 @@ export const workspaceSchema = z.object({
158
173
  undelivered: z.array(z.object({ id: z.string().max(400), agentId: idSchema, agentTitle: z.string().nullable(), state: z.enum(["queued", "failed"]), reason: z.string().nullable(), since: z.string() })).max(20).optional(),
159
174
  /** The main agent's title from Paseo, for "Next message to <title>". Absent: "the main agent". */
160
175
  mainAgentTitle: z.string().nullable().optional(),
161
- /** Open tasks kept out of the next message (reconcile): capped (sent NO_PROGRESS_CAP times unchanged) or manual (Auto off for that task). */
162
- heldTasks: z.array(z.object({ task: taskSchema, held: z.enum(["capped", "manual"]) })).optional(),
176
+ /** Open tasks kept out of the next message (reconcile): capped (sent NO_PROGRESS_CAP times unchanged), manual (Auto off for that task) or person (the agent said only a person can move it: Batch.humanOnly). */
177
+ heldTasks: z.array(z.object({ task: taskSchema, held: z.enum(["capped", "manual", "person"]) })).optional(),
163
178
  /** Task keys the developer keeps for themselves: never auto-sent (shared/send-decision.ts). */
164
179
  manualTasks: z.array(z.string()).optional(),
165
180
  /** Per condition ("<key>:<fingerprint>"), the unacknowledged sends counted when the developer pressed Retry. */
@@ -266,7 +281,7 @@ export function summary(w: ListWorkspace, now = Date.now()): { status: Status; l
266
281
  const batch = w.batches.find(b => !recoveryBatch(b) && ["pending", "sending", "sent"].includes(b.state) && !(b.state === "pending" && completionCheck(b)));
267
282
  if (batch) return { status: batch.state === "pending" ? "active" : "handling", label: batch.state === "pending" ? w.enable_auto_sends ? "Auto queued" : "Ready to send" : "Agent handling", reason: `${batch.tasks.length} follow-up task${batch.tasks.length === 1 ? "" : "s"} ${batch.state === "pending" ? "queued" : batch.recipientAgentId && batch.recipientAgentId !== w.mainAgentId ? "sent to the recovery agent" : "sent to the main agent"}` };
268
283
  const live = liveWorkingTask(w);
269
- if (w.runtimeBusy || live) return { status: "handling", label: "Agent handling", reason: live?.title ?? "The main agent is working" };
284
+ if (w.runtimeBusy || live) return { status: "handling", label: "Agent handling", reason: live?.title ?? (w.mainBusy === null ? "Agents in this workspace are working" : "The main agent is working") };
270
285
  if (w.prs.some(pr => !statusKnown(pr))) return { status: "waiting", label: "Waiting", reason: "PR status unavailable; refresh will retry" };
271
286
  const pending = obligations.find(o => !["done", "waived"].includes(o.status));
272
287
  if (pending) return { status: pending.status === "waiting" ? "waiting" : "active", label: pending.status === "waiting" ? "Waiting" : "Active", reason: pending.title };