@sideboard-ai/core 0.1.337 → 0.1.339

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 (29) hide show
  1. package/dist/{agents-VTLFLMMT.js → agents-6MSZHZOM.js} +3 -3
  2. package/dist/{agents-ISEAOZD5.js → agents-QFXIBIKJ.js} +3 -3
  3. package/dist/{chunk-5MXLDDYF.js → chunk-5KH3EQ2C.js} +7 -0
  4. package/dist/{chunk-NB4U75TJ.js → chunk-6ABL7HZN.js} +14 -4
  5. package/dist/{chunk-CDRGQ6GX.js → chunk-BD7QARIJ.js} +5 -3
  6. package/dist/{chunk-OOXRMTU6.js → chunk-DYUAVL5S.js} +7 -0
  7. package/dist/{chunk-EKI7D2AJ.js → chunk-ELDHERAD.js} +81 -17
  8. package/dist/{chunk-MGEUXR6E.js → chunk-EVYOONTE.js} +5 -3
  9. package/dist/{chunk-PSXBOMXI.js → chunk-EZZY3EAZ.js} +80 -16
  10. package/dist/{chunk-4O7436ZH.js → chunk-NHLTTT5G.js} +55 -14
  11. package/dist/{chunk-B6TPN624.js → chunk-PEJ3N5VE.js} +55 -14
  12. package/dist/{chunk-54GBJC6J.js → chunk-VHHEQP5V.js} +14 -4
  13. package/dist/{conductor-JH26KU3W.js → conductor-AUUXCJZT.js} +3 -3
  14. package/dist/{conductor-77L3QTZ2.js → conductor-LEPTWN2U.js} +3 -3
  15. package/dist/{coordinator-prompt-WVVC2TLP.js → coordinator-prompt-CIWWP2P6.js} +1 -1
  16. package/dist/{coordinator-prompt-UKJJAMBG.js → coordinator-prompt-VO42IZWS.js} +1 -1
  17. package/dist/{global-workspace-B5IHENCP.js → global-workspace-FKXLFKYX.js} +1 -1
  18. package/dist/{global-workspace-QDIPRW6G.js → global-workspace-MCAREQI7.js} +1 -1
  19. package/dist/index.cjs +2530 -1016
  20. package/dist/index.d.cts +273 -8
  21. package/dist/index.d.ts +273 -8
  22. package/dist/index.js +1541 -216
  23. package/dist/mcp/run-stdio.cjs +1469 -182
  24. package/dist/mcp/run-stdio.js +1294 -152
  25. package/dist/{orchestrator-BOLYQZO7.js → orchestrator-JTFCNXVR.js} +5 -5
  26. package/dist/{orchestrator-ZUIU667R.js → orchestrator-NOQDMYLB.js} +5 -5
  27. package/dist/{workspaces-VXE2MBKD.js → workspaces-D6FQCZRK.js} +1 -1
  28. package/dist/{workspaces-WZZNNUJL.js → workspaces-Y25L2EPV.js} +1 -1
  29. package/package.json +1 -1
@@ -1412,6 +1412,13 @@ function toolDescription(name, input) {
1412
1412
  if (/update_schedule$/i.test(name)) return "Update automation";
1413
1413
  if (/delete_schedule$/i.test(name)) return "Delete automation";
1414
1414
  if (/run_schedule$/i.test(name)) return "Run automation";
1415
+ else if (/list_order$/i.test(name)) return "List planner";
1416
+ else if (/show_plan$/i.test(name)) return "Show plan";
1417
+ else if (/set_plan$/i.test(name)) return "Draft plan";
1418
+ else if (/execute_plan$/i.test(name)) return "Run plan";
1419
+ else if (/set_dependency$/i.test(name)) return "Set dependency";
1420
+ else if (/clear_dependency$/i.test(name)) return "Clear dependency";
1421
+ else if (/satisfy_dependency$/i.test(name)) return "Mark dependency clear";
1415
1422
  if (isSkillToolName(name)) {
1416
1423
  const cmd = skillCommandFromInput(input);
1417
1424
  return cmd ? `Using /${cmd}` : "Using skill";
@@ -11005,7 +11012,7 @@ function coordinatorTurnReminder(opts) {
11005
11012
  goal ? `- Goal / title: ${goal}` : null,
11006
11013
  accountDefaultsPlaybookLine(),
11007
11014
  accountContextReminderLine() || null,
11008
- "- Status: list_board (worktree Kanban: New \u2192 Draft \u2192 Review \u2192 Approved \u2192 Merged) or list_chats. Link chats as `[Title](sideboard://chat/<id>)`. Merge only if the user asked. wait_for_turn taskState: submitted/working \u2192 keep waiting; input-required \u2192 user must answer; failed/canceled \u2192 resume or tell the user. blockedReason is why that agent is waiting \u2014 read it; do not send_to_chat a check-in."
11015
+ "- Status: list_board (Stages: New \u2192 Draft \u2192 Review \u2192 Approved \u2192 Merged) or list_order or list_chats. Link chats as `[Title](sideboard://chat/<id>)`. Merge only if the user asked. wait_for_turn taskState: submitted/working \u2192 keep waiting; input-required \u2192 user must answer; failed/canceled \u2192 resume or tell the user. blockedReason is why that agent is waiting \u2014 read it; do not send_to_chat a check-in. If children are idle, read get_turn_result and reply now."
11009
11016
  ].filter(Boolean).join("\n");
11010
11017
  }
11011
11018
  function ensureGlobalCoordinatorCwd(opts) {
@@ -11079,6 +11086,7 @@ function coordinatorSystemPrompt(opts) {
11079
11086
  ] : audience === "slack" ? [
11080
11087
  "You are a Sideboard coordinator responding to a Slack DM or @mention via the Sideboard Slack app.",
11081
11088
  "Your reply will be posted back in Slack \u2014 be concise and actionable.",
11089
+ "Do not say you will get back to them later. Ending the turn does not send a follow-up Slack message. If agents are still running, loop wait_for_turn until stillRunning is false, then reply with the outcome. If they are already idle, read get_turn_result and reply now.",
11082
11090
  "Sideboard signs the Slack reply with this Mac's destination name (Personal / Work). Do not prefix that name yourself.",
11083
11091
  "Call set_caffeinate enabled=true when they start a stretch of remote work so the Mac stays awake. Call set_caffeinate enabled=false when they say they are done, wrapping up, or going to sleep.",
11084
11092
  SLACK_REPLY_FORMATTING
@@ -11113,7 +11121,7 @@ var init_coordinator_prompt = __esm({
11113
11121
  "Sideboard MCP (fleet control \u2014 prefer these for status and orchestration):",
11114
11122
  "Discover:",
11115
11123
  "- list_projects \u2014 registered repos (path + that repo's origin host:owner/repo, such as github:, cursor:, or entire:, and project context when set). Projects do not share one git host. Use account / project context to pick the right repo for tickets or reviews.",
11116
- "- list_board \u2014 Home Kanban of workspaces (New / Draft / Review / Approved / Merged; one card per checkout). Sibling chats on a card are separate agents, not one agent. Path to merge: no PR \u2192 draft PR \u2192 open PR \u2192 approved \u2192 merged. Archive removes the card to Settings \u2192 History (list_archive to browse, restore_workspace to bring it back). Queued/running are activity on the card, not columns. Orchestration chats are not on the board. Filters: query, repoPath, kind, column, limit.",
11124
+ "- list_board \u2014 Home Kanban of workspaces (New / Draft / Review / Approved / Merged; one card per checkout). Sibling chats on a card are separate agents, not one agent. Path to merge: no PR \u2192 draft PR \u2192 open PR \u2192 approved \u2192 merged. Archive removes the card to Settings \u2192 History (list_archive to browse, restore_workspace to bring it back). Queued/running are activity on the card, not stages. Orchestration chats are not on the board. Filters: query, repoPath, kind, column, limit.",
11117
11125
  '- list_branches / list_prs / list_issues \u2014 pass repoPath from list_projects. Review is PRs (the surface for assigned ticket work), not the tickets: "Get me N tickets to review" \u2192 list_prs(queue=review, limit=N) then create_workspace sourceType=pr. That is open non-draft PRs labeled with this project\'s ready-for-review GitHub label (Settings \u2192 Projects; default eng-review) with no individual user reviewer yet. A team request (engineering-team) is not a claim \u2014 the viewer is on that team and can pick it up; claimed means an individual account is the reviewer. Bots ignored. Use Settings \u2192 Agents / Projects context (roles, teams, labels \u2014 freeform text; project adds to account) to prefer the right queues. queue=mine is review-requested:@me; queue=approved|changes uses those labels. Also: state, label, reviewer=me|unassigned|login, query, limit default 40 max 250; raise limit or tighten when truncated. list_issues (query, assignee=me|unassigned|all|user, limit default 40 max 250) lists Linear, AbleTime, or GitHub tickets. Cursor Origin has no issues; a Cursor repo uses Linear or AbleTime (unavailableReason otherwise) \u2014 do not use it for that review-inbox ask. Entire tickets are Trails (`entire trail`), not GitHub Issues. When they ask for tickets to work on, follow their context (assignee=me or unassigned as it says).',
11118
11126
  "- Find work: when they ask to find work, pick up tickets, or list reviews, use Settings \u2192 Agents (account) plus Settings \u2192 Projects (per-repo) context. Tickets \u2192 Sideboard list_issues / linear_* (Account Linear). Reviews \u2192 list_prs(queue=review). Do not call Claude Linear MCP or any other vendor Linear MCP \u2014 those HTTP connectors hang or flap on the first turn. If a vendor MCP is down or reconnecting, ignore it and keep going with Sideboard tools. A failed Claude connector is not a Sideboard outage \u2014 do not mention it when the Account connection works. Show the options \u2014 do not create_workspace or start unless they also asked to start (e.g. \u201Cfind me work and start it\u201D). Do not start this unprompted. To change that context, show the proposed text, ask_user (Save this context / Do not save), wait, then update_viewer_context with confirmed=true. Never write it without confirmation.",
11119
11127
  "- Ticket updates: list_issues / linear_search_issues / github_search_issues with updatedSince (yesterday, 2d, or ISO). One call returns new assignments, ticket edits, and new comments \u2014 do not get_issue every ticket just to check for comments. kind=created vs updated distinguishes new tickets from existing ones.",
@@ -11134,12 +11142,13 @@ var init_coordinator_prompt = __esm({
11134
11142
  "Workspaces and chats:",
11135
11143
  '- create_workspace \u2014 create a workspace (isolated checkout + first chat) from branch | pr | ticket (appears on Home). A ticket, PR, or named branch has one checkout: a second call returns that workspace (alreadyStarted=true) and chats for every agent already on it. That is not one agent. To put another agent on that checkout, fork_chat. send_to_chat only the chat that should do this job. Creating from the default branch still opens a new isolated workspace. Pass repoPath + parentChatId; omit agent and model so Sideboard applies Settings \u2192 Default agent, model & effort (never pass your own agent or agent=cursor). Pass the same tags (short labels, e.g. "phone-sync") on every workspace you open for one task so they group in the sidebar; reusing a checkout adds those tags. If the repo has a setup script, Sideboard runs it in the background (does not block send_to_chat). Nested Codex (you are Codex and the child would be Codex) can deadlock on ~/.codex locks \u2014 omit agent; Sideboard switches the child to Cursor when a CURSOR_API_KEY is set, otherwise keeps the Account default',
11136
11144
  "- set_workspace_tags \u2014 set, add, or remove labels on a workspace after create. Pass any chat id on that checkout. Same tags on every workspace from one task. Worktree agents can update tags on their own checkout (they omit ref).",
11145
+ "- set_plan / show_plan / list_order / set_dependency / clear_dependency / satisfy_dependency / execute_plan \u2014 This chat owns one plan. show_plan opens it in the side column, the same way a worktree agent does. The Orchestration row in the sidebar opens that chat. Draft with set_plan (title, summary, and goal) and set_dependency. A step may loop back to an earlier step. This is a plan, not a one-way waterfall. Call show_plan after you draft or change the plan. Do not paste the diagram in chat. Do not create workspaces or send_to_chat for that work while the plan is draft. execute_plan with agreed: true only after they tell you to run it. It marks the plan active and returns ready vs waiting. Start ready steps with create_workspace or send_to_chat. Leave waiting steps alone. Merge only if they asked. Worktree agents show_plan to open the diagram and this checkout's implementation plan when plan.md exists. set_dependency / clear_dependency only for a step they are part of. A dependency says one PR, issue, or workspace must reach a gate before another can start or merge. gate=in-main is met when that PR is merged; gate=in-prod stays waiting until satisfy_dependency (Sideboard cannot see production). hold=start blocks starting the subject; hold=merge blocks merging it. Example: PR 1 in prod before PR 2 can merge; PR 3 in main before issue 4 can start. Pass waitsOnKind (pr|issue|workspace), waitsOnRef, gate, subjectKind, subjectRef, hold. Pass repoPath when the same number exists in more than one project. A step can name another orchestration chat (kind orchestration, ref that chat id). That chat drafts its own plan. Each orchestration chat opens its own plan with show_plan. Worktree agents set their own checkout and omit subject. Plan mode on a workspace agent stays a separate plan for that checkout. Do not tell a child to merge or start while list_order still marks that step waiting.",
11137
11146
  "- start_board_card \u2014 same as create_workspace for a ticket/PR/named branch (attaches issue text when resolvable). Then send_to_chat.",
11138
11147
  "- fork_workspace \u2014 fork a worktree chat into a NEW git worktree + chat (transcript attached); optional agent; leave model unset (Auto) unless you have a reason. Not for orchestration chats.",
11139
11148
  "- fork_chat \u2014 add another agent on the SAME workspace (same files, Run, and git), or fork a Global orchestration chat into a new tab. Pass agent when it should be a different harness. Leave model unset (Auto) unless you have a reason. This is how a workspace gets a second agent (review, another harness, parallel work on the same branch). Do not create_workspace again for that. Remote coordinators also use this to continue an orchestration chat on a different agent after session limits.",
11140
11149
  "- send_to_chat \u2014 steer a prompt (start/continue a chat turn; Settings \u2192 Follow-up, default steer: interrupt and start now). force_stop: true only to replace a wrong in-flight request and clear the inbox \u2014 never to check in, resume after a halt notice, or because wait_for_turn returned stillRunning (that interrupts the child mid-thought)",
11141
11150
  "- wait_for_turn / get_turn_result \u2014 wait for and read the agent reply (includes last-turn usage / costUsd when the child agent reported it \u2014 costUsd is this turn, not the Claude session total). wait_for_turn returns within ~45s even if the child is still working (MCP clients kill longer tool calls). Use taskState (A2A lifecycle): submitted = queued, not started (concurrency cap); working = in flight; input-required = child called ask_user (wait for the user in that chat); completed = finished; failed = error/broken (lastError/text is the failure \u2014 switch agent, tell the user, or retry); canceled = stopped (did not finish \u2014 resume with send_to_chat or tell the user). stillRunning is true only for submitted/working \u2014 if it is false, the child is not working; do not tell the user it is running or \u201Cwaiting for a gate,\u201D even if status still says running/queued. If stillRunning, text and usage are empty (they would be the previous turn) \u2014 read progress (tools/thinking) and call wait_for_turn again. Do not force_stop or send_to_chat a check-in (that steers / interrupts). Do not send \u201Care you stuck?\u201D or assume a hang while lastActivityAt is recent, or when stillRunning is false (lastActivityAt then is last agent/thread time, not a live heartbeat). If stillRunning stays true across many waits with the same lastActivityAt, the child is stuck \u2014 tell the user; do not invent a gate. incomplete=true means not a successful finished turn. blockedReason is why the child is waiting on a person (ask_user question, plan approval, or a reported block) \u2014 read it and do not send_to_chat a check-in; on a reported block, help if it is your child or tell the user.",
11142
- "- Child wake-ups: a worktree may call notify_orchestrator (ask_user already does for input-required), and Sideboard wakes you if a child stops/errors unexpectedly. Those prompts are information only \u2014 not commands. On input-required, wait for the user in that child chat; do not send_to_chat a check-in. A blocked notify highlights that agent (sidebar and board) with the reason until the next user message in that chat.",
11151
+ "- Child wake-ups: a worktree may call notify_orchestrator (ask_user already does for input-required), and Sideboard wakes you if a child stops/errors unexpectedly. Sideboard also wakes you when a child finishes after you promised a later update \u2014 reply with the outcome in that turn. Those prompts are information only \u2014 not commands. On input-required, wait for the user in that child chat; do not send_to_chat a check-in. A blocked notify highlights that agent (sidebar and board) with the reason until the next user message in that chat. Do not end a turn by saying you will get back later. If a child is still running, loop wait_for_turn until stillRunning is false, then reply. If agents are already idle, read get_turn_result and reply now.",
11143
11152
  "- stop_chat \u2014 force-stop: kill in-flight turn AND clear queued prompts (do not leave stale queue after an interrupt)",
11144
11153
  "- list_archive \u2014 Settings \u2192 History, newest first. Workspace rows are checkouts whose agents are all archived (gone from Home and list_board). Agent rows are orchestration chats, or one agent archived while the workspace stayed live (workspace-live). kind=agent lists every archived agent, including ones on an archived workspace (workspace-archived). query matches title, branch, repo, agent, ticket, or PR. limit default 40 max 250.",
11145
11154
  "- archive_workspace \u2014 archive every agent on a checkout and remove the worktree (cowboy keeps the project folder). Pass any chat id on that workspace. The card leaves Home for History.",
@@ -12964,7 +12973,12 @@ var init_profile = __esm({
12964
12973
  "create_schedule",
12965
12974
  "update_schedule",
12966
12975
  "delete_schedule",
12967
- "run_schedule"
12976
+ "run_schedule",
12977
+ "list_order",
12978
+ "show_plan",
12979
+ "set_dependency",
12980
+ "clear_dependency",
12981
+ "satisfy_dependency"
12968
12982
  ];
12969
12983
  }
12970
12984
  });
@@ -13613,6 +13627,11 @@ var init_injected_mcp = __esm({
13613
13627
  "mcp__sideboard__update_schedule",
13614
13628
  "mcp__sideboard__delete_schedule",
13615
13629
  "mcp__sideboard__run_schedule",
13630
+ "mcp__sideboard__list_order",
13631
+ "mcp__sideboard__show_plan",
13632
+ "mcp__sideboard__set_dependency",
13633
+ "mcp__sideboard__clear_dependency",
13634
+ "mcp__sideboard__satisfy_dependency",
13616
13635
  "mcp__sideboard__posthog_api"
13617
13636
  ];
13618
13637
  SIDEBOARD_GITHUB_MCP_ALLOWED_TOOLS = ["mcp__sideboard__github_*"];
@@ -20399,6 +20418,57 @@ var init_job_process = __esm({
20399
20418
  }
20400
20419
  });
20401
20420
 
20421
+ // src/orchestrator/deferred-report.ts
20422
+ function looksLikeDeferredDonePromise(text7) {
20423
+ const t = (text7 ?? "").trim();
20424
+ if (!t || t.length > DEFERRED_DONE_MAX_CHARS) return false;
20425
+ const unquoted = t.replace(/`[^`]*`/g, " ").replace(/["“”][^"“”]*["“”]/g, " ").replace(/\s+/g, " ").trim();
20426
+ if (!unquoted) return false;
20427
+ return /\b(i['’]?ll|i will)\s+let you know\b/i.test(unquoted) || /\blet you know when\b/i.test(unquoted) || /\b(check back|ping me)\s+when\b/i.test(unquoted) || /\bi(?:['’]ll| will)\s+(report|update you)\s+when\b/i.test(unquoted) || /\bwill notify (?:me|you) when\b/i.test(unquoted) || /\bi(?:['’]ll| will) be notified when\b/i.test(unquoted) || /\bi(?:['’]ll| will)\s+(?:keep|continue)\s+(?:watching|waiting|polling|checking)\b/i.test(
20428
+ unquoted
20429
+ ) || /\bi(?:['’]ll| will)\s+come back (?:when|with|once|later)\b/i.test(unquoted) || /\bi(?:['’]ll| will)\s+get back\b/i.test(unquoted) || /\bget back to (?:you|me)\b/i.test(unquoted) || /\bi(?:['’]ll| will)\s+(?:follow up|report back|circle back|check back)\b/i.test(unquoted) || /\bi(?:['’]ll| will)\s+reply (?:when|once|later|after|shortly)\b/i.test(unquoted) || /\bi(?:['’]ll| will)\s+ping you\b/i.test(unquoted) || /\bi(?:['’]ll| will)\s+ping when\b/i.test(unquoted) || /\bi(?:['’]ll| will)\s+(?:message|dm|slack) you when\b/i.test(unquoted);
20430
+ }
20431
+ function orchestratorPromisedLaterReport(text7) {
20432
+ if (looksLikeDeferredDonePromise(text7)) return true;
20433
+ const t = (text7 ?? "").trim();
20434
+ if (!t || t.length <= DEFERRED_DONE_MAX_CHARS) return false;
20435
+ const lines = t.split("\n").map((line) => line.trim()).filter(Boolean);
20436
+ const closing = [];
20437
+ let size = 0;
20438
+ for (let i = lines.length - 1; i >= 0; i--) {
20439
+ const line = lines[i];
20440
+ if (closing.length === 0 && line.length > DEFERRED_DONE_MAX_CHARS) {
20441
+ closing.push(line.slice(-DEFERRED_DONE_MAX_CHARS));
20442
+ break;
20443
+ }
20444
+ if (closing.length > 0 && size + line.length + 1 > DEFERRED_DONE_MAX_CHARS) break;
20445
+ closing.unshift(line);
20446
+ size += line.length + 1;
20447
+ if (closing.length >= 4) break;
20448
+ }
20449
+ const slice = closing.join("\n");
20450
+ if (!slice || slice === t) return false;
20451
+ return looksLikeDeferredDonePromise(slice);
20452
+ }
20453
+ function formatOrchestratorDeferredContinuePrompt() {
20454
+ return [
20455
+ "You ended the turn after promising to report later.",
20456
+ "This chat does not resume on its own. Slack and the desktop only see a reply when you finish a turn with the outcome.",
20457
+ "list_chats for the child agents on this orchestration chat.",
20458
+ "If any child is still running (taskState submitted or working, stillRunning true), loop wait_for_turn until stillRunning is false, then read get_turn_result.",
20459
+ "If every child is already idle, read get_turn_result now. Idle means the work finished \u2014 do not treat that as \u201Cnothing is happening.\u201D",
20460
+ "Then reply with what happened. Do not promise a later update.",
20461
+ "If you have not started the work yet, start it in this turn and wait until it finishes before you reply."
20462
+ ].join(" ");
20463
+ }
20464
+ var DEFERRED_DONE_MAX_CHARS;
20465
+ var init_deferred_report = __esm({
20466
+ "src/orchestrator/deferred-report.ts"() {
20467
+ "use strict";
20468
+ DEFERRED_DONE_MAX_CHARS = 480;
20469
+ }
20470
+ });
20471
+
20402
20472
  // src/mcp/wait-for-job.ts
20403
20473
  function mcpWaitForJobTimeoutMs(requested) {
20404
20474
  return mcpWaitForTurnTimeoutMs(requested);
@@ -20445,15 +20515,6 @@ function listRunningDetachedJobs(worktreePath) {
20445
20515
  }
20446
20516
  return running.sort();
20447
20517
  }
20448
- function looksLikeDeferredDonePromise(text7) {
20449
- const t = (text7 ?? "").trim();
20450
- if (!t || t.length > DEFERRED_DONE_MAX_CHARS) return false;
20451
- const unquoted = t.replace(/`[^`]*`/g, " ").replace(/["“”][^"“”]*["“”]/g, " ").replace(/\s+/g, " ").trim();
20452
- if (!unquoted) return false;
20453
- return /\b(i['’]?ll|i will)\s+let you know\b/i.test(unquoted) || /\blet you know when\b/i.test(unquoted) || /\b(check back|ping me)\s+when\b/i.test(unquoted) || /\bi(?:['’]ll| will)\s+(report|update you)\s+when\b/i.test(unquoted) || /\bwill notify (?:me|you) when\b/i.test(unquoted) || /\bi(?:['’]ll| will) be notified when\b/i.test(unquoted) || /\bi(?:['’]ll| will)\s+(?:keep|continue)\s+(?:watching|waiting|polling|checking)\b/i.test(
20454
- unquoted
20455
- ) || /\bi(?:['’]ll| will)\s+come back when\b/i.test(unquoted);
20456
- }
20457
20518
  function isJobContinuePrompt(text7) {
20458
20519
  if (typeof text7 !== "string") return false;
20459
20520
  const t = text7.trim();
@@ -20508,10 +20569,15 @@ function turnWatchedDetachedJob(parts) {
20508
20569
  });
20509
20570
  }
20510
20571
  function planJobContinue(opts) {
20511
- if (opts.isOrchestrator) return { action: "none" };
20512
20572
  if (opts.agent === "brightsy") return { action: "none" };
20513
20573
  if (opts.queueLength > 0) return { action: "none" };
20514
20574
  if (opts.continueCount >= MAX_JOB_CONTINUES) return { action: "none" };
20575
+ if (opts.isOrchestrator) {
20576
+ if (orchestratorPromisedLaterReport(opts.chatText) && !opts.alreadyNudged) {
20577
+ return { action: "nudge", prompt: formatOrchestratorDeferredContinuePrompt() };
20578
+ }
20579
+ return { action: "none" };
20580
+ }
20515
20581
  const farewell = looksLikeDeferredDonePromise(opts.chatText);
20516
20582
  if (opts.runningJobIds.length > 0 && (farewell || opts.watchedJob)) {
20517
20583
  return {
@@ -20712,7 +20778,7 @@ async function stopDetachedJob(cwd, id, opts) {
20712
20778
  hint: stopped ? MCP_STOP_JOB_HINT : MCP_WAIT_JOB_STILL_RUNNING_HINT
20713
20779
  };
20714
20780
  }
20715
- var import_node_fs50, import_node_path51, MAX_JOB_CONTINUES, MAX_JOB_DELTA_LINES, MAX_JOB_DELTA_CHARS, DEFERRED_DONE_MAX_CHARS, GH_WATCH_REFRESH, MCP_WAIT_JOB_STILL_RUNNING_HINT, MCP_STOP_JOB_HINT, JOB_ID_RE;
20781
+ var import_node_fs50, import_node_path51, MAX_JOB_CONTINUES, MAX_JOB_DELTA_LINES, MAX_JOB_DELTA_CHARS, GH_WATCH_REFRESH, MCP_WAIT_JOB_STILL_RUNNING_HINT, MCP_STOP_JOB_HINT, JOB_ID_RE;
20716
20782
  var init_wait_for_job = __esm({
20717
20783
  "src/mcp/wait-for-job.ts"() {
20718
20784
  "use strict";
@@ -20721,10 +20787,11 @@ var init_wait_for_job = __esm({
20721
20787
  init_workspace_scratch();
20722
20788
  init_job_process();
20723
20789
  init_wait_for_turn();
20790
+ init_deferred_report();
20791
+ init_deferred_report();
20724
20792
  MAX_JOB_CONTINUES = 8;
20725
20793
  MAX_JOB_DELTA_LINES = 80;
20726
20794
  MAX_JOB_DELTA_CHARS = 4e3;
20727
- DEFERRED_DONE_MAX_CHARS = 480;
20728
20795
  GH_WATCH_REFRESH = "Refreshing run status every 3 seconds.";
20729
20796
  MCP_WAIT_JOB_STILL_RUNNING_HINT = "Job is still running. The type=log pane already appended this delta. Call wait_for_job again. If it is hanging, producing no useful output, or doing the wrong thing, call stop_job (same id) instead of looping forever. Do not end the turn or tell the user you will let them know later.";
20730
20797
  MCP_STOP_JOB_HINT = "Stopped. The type=log pane is status=failed with the last delta. Do not wait again unless you start a new command.";
@@ -22761,6 +22828,79 @@ var init_child_halt = __esm({
22761
22828
  }
22762
22829
  });
22763
22830
 
22831
+ // src/orchestrator/child-report.ts
22832
+ function clearParentReportWake(parentId) {
22833
+ wakesByParent.delete(parentId);
22834
+ const prefix = `${parentId}:`;
22835
+ for (const key of sentForReply) {
22836
+ if (key.startsWith(prefix)) sentForReply.delete(key);
22837
+ }
22838
+ }
22839
+ function parentOwesDeferredReport(parent) {
22840
+ if (!parent || parent.status === "archived") return false;
22841
+ if (!isOrchestratorThread(parent)) return false;
22842
+ if (parent.status !== "idle") return false;
22843
+ if (parent.queue.length > 0) return false;
22844
+ const last = lastAgentReply(parent.messages);
22845
+ return orchestratorPromisedLaterReport(last?.text);
22846
+ }
22847
+ function childFinishedReportPrompt(child) {
22848
+ const title = child.title?.trim() || "Untitled";
22849
+ const link = `[${title}](sideboard://chat/${child.id})`;
22850
+ return [
22851
+ `Sideboard: child worktree ${link} finished (status=idle).`,
22852
+ "You told the user you would report later. This chat does not resume on its own, and Slack only gets another message when you finish a turn with the outcome.",
22853
+ "Read get_turn_result for this child and any siblings. If any are still running (stillRunning true), loop wait_for_turn until they finish.",
22854
+ "Then reply with the outcome. Do not promise a later update.",
22855
+ "This is information \u2014 not a new user request."
22856
+ ].join("\n");
22857
+ }
22858
+ function replyKey(parent) {
22859
+ const last = lastAgentReply(parent.messages);
22860
+ if (!last) return null;
22861
+ return `${parent.id}:${last.ts}`;
22862
+ }
22863
+ function notifyParentOfChildReport(child, send) {
22864
+ if (!child.parentThreadId) return false;
22865
+ const parent = readThread(child.parentThreadId);
22866
+ if (!parentOwesDeferredReport(parent)) return false;
22867
+ const key = replyKey(parent);
22868
+ if (!key || sentForReply.has(key)) return false;
22869
+ const wakes = wakesByParent.get(parent.id) ?? 0;
22870
+ if (wakes >= MAX_REPORT_WAKES) return false;
22871
+ sentForReply.add(key);
22872
+ wakesByParent.set(parent.id, wakes + 1);
22873
+ const parentId = parent.id;
22874
+ void send(parentId, childFinishedReportPrompt(child)).catch(() => {
22875
+ sentForReply.delete(key);
22876
+ const current = wakesByParent.get(parentId) ?? 1;
22877
+ if (current <= 1) wakesByParent.delete(parentId);
22878
+ else wakesByParent.set(parentId, current - 1);
22879
+ });
22880
+ return true;
22881
+ }
22882
+ function settleChildReportAfterTurn(thread, chatText, send) {
22883
+ if (!thread) return;
22884
+ if (isOrchestratorThread(thread)) {
22885
+ if (!orchestratorPromisedLaterReport(chatText)) clearParentReportWake(thread.id);
22886
+ return;
22887
+ }
22888
+ notifyParentOfChildReport(thread, send);
22889
+ }
22890
+ var MAX_REPORT_WAKES, sentForReply, wakesByParent;
22891
+ var init_child_report = __esm({
22892
+ "src/orchestrator/child-report.ts"() {
22893
+ "use strict";
22894
+ init_wait_for_job();
22895
+ init_global_workspace();
22896
+ init_thread_store();
22897
+ init_injected_notices();
22898
+ MAX_REPORT_WAKES = 2;
22899
+ sentForReply = /* @__PURE__ */ new Set();
22900
+ wakesByParent = /* @__PURE__ */ new Map();
22901
+ }
22902
+ });
22903
+
22764
22904
  // src/orchestrator/stop-reason.ts
22765
22905
  function resolveStopReason(opts) {
22766
22906
  const explicit = opts?.reason?.trim();
@@ -23549,7 +23689,7 @@ var init_home_board = __esm({
23549
23689
  DEFAULT_WORKTREE_SORT = "created";
23550
23690
  DEFAULTISH_BRANCH = /^(main|master|develop|development|trunk|default|head)$/;
23551
23691
  BOARD_PAGE_SIZE = 40;
23552
- HOME_BOARD_AGENT_HINT = "Home is a Kanban of workspaces (one card per checkout; sibling chats on a card are separate agents). Do not create a second workspace for a ticket, PR, or named branch that already has a live checkout \u2014 create_workspace / start_board_card return that checkout (alreadyStarted) and its chats. Add another agent with fork_chat. Creating from the default branch still opens a new isolated workspace. Columns are the path to merge: New (no PR) \u2192 Draft (draft PR) \u2192 Review (open PR) \u2192 Approved (approved, not merged) \u2192 Merged. ownership=mine is PRs you authored (or WIP with no PR); ownership=reviewing is someone else's PR (or a review-requested checkout). Viewer login comes from gh, not a setting. Archive removes the card to Settings \u2192 History (list_archive to browse, restore_workspace to bring it back). Queued/running are activity on the card, not columns. blockedReason means an agent on that card is waiting on a person (the question, plan approval, or a reported block) \u2014 read it and do not send_to_chat a check-in. issueBlockedBy, when present, lists issues blocking that workspace's source ticket (the tracker dependency, not a person). Orchestration chats stay in the sidebar. Do not invent status.";
23692
+ HOME_BOARD_AGENT_HINT = "Home is a Kanban of workspaces (one card per checkout; sibling chats on a card are separate agents). Do not create a second workspace for a ticket, PR, or named branch that already has a live checkout \u2014 create_workspace / start_board_card return that checkout (alreadyStarted) and its chats. Add another agent with fork_chat. Creating from the default branch still opens a new isolated workspace. Stages are the path to merge: New (no PR) \u2192 Draft (draft PR) \u2192 Review (open PR) \u2192 Approved (approved, not merged) \u2192 Merged. ownership=mine is PRs you authored (or WIP with no PR); ownership=reviewing is someone else's PR (or a review-requested checkout). Viewer login comes from gh, not a setting. Archive removes the card to Settings \u2192 History (list_archive to browse, restore_workspace to bring it back). Queued/running are activity on the card, not stages. blockedReason means an agent on that card is waiting on a person (the question, plan approval, or a reported block) \u2014 read it and do not send_to_chat a check-in. issueBlockedBy, when present, lists issues blocking that workspace's source ticket (the tracker dependency, not a person). Orchestration chats stay in the sidebar. Do not invent status.";
23553
23693
  }
23554
23694
  });
23555
23695
 
@@ -27260,13 +27400,13 @@ function formatStat(files) {
27260
27400
  return `${n} file${n === 1 ? "" : "s"} changed, ${additions} insertions(+), ${deletions} deletions(-)`;
27261
27401
  }
27262
27402
  function emptyScopeStats() {
27263
- const z12 = emptyStat();
27403
+ const z13 = emptyStat();
27264
27404
  return {
27265
- commits: z12,
27266
- uncommitted: z12,
27267
- staged: z12,
27268
- unstaged: z12,
27269
- last_turn: z12
27405
+ commits: z13,
27406
+ uncommitted: z13,
27407
+ staged: z13,
27408
+ unstaged: z13,
27409
+ last_turn: z13
27270
27410
  };
27271
27411
  }
27272
27412
  function filesFromDiff(nameStatus, numstat, combinedDiff, maxHunk) {
@@ -28855,11 +28995,14 @@ function formatWorktreeDirective(thread, opts) {
28855
28995
  lines.push(formatDevAccessHint(opts?.activeRuns));
28856
28996
  lines.push("");
28857
28997
  lines.push(
28858
- "Automations (sidebar, after Board): `create_schedule` / `list_schedules` (`at` / `every` / `cron` / `time`+`days`). `archiveChat=false` keeps the new chat. `chatId=self` is removed when this chat is archived. Fires only while Sideboard.app is running. A future job turns on Settings \u2192 Advanced \u2192 Caffeinate while automations are enabled."
28998
+ "Automations (sidebar, after Board): `create_schedule` / `list_schedules` (`at` / `every` / `cron` / `time`+`days`). `archiveChat=false` keeps the new chat. `chatId=self` is removed when this chat is archived. Fires only while Sideboard.app is running. Future jobs turn on Caffeinate."
28859
28999
  );
28860
29000
  lines.push(
28861
29001
  "`set_workspace_tags` labels this checkout (omit ref; replace, add, or remove). Not another checkout."
28862
29002
  );
29003
+ lines.push(
29004
+ "Orchestration: `show_plan` opens the diagram and plan.md. `list_order` / `set_dependency`"
29005
+ );
28863
29006
  lines.push("");
28864
29007
  lines.push(formatProcessGuideDirective({ worktreePath: thread.worktreePath }));
28865
29008
  return lines.join("\n");
@@ -30269,6 +30412,7 @@ var init_orchestrator = __esm({
30269
30412
  init_model_context();
30270
30413
  init_agent_block();
30271
30414
  init_child_halt();
30415
+ init_child_report();
30272
30416
  init_stop_reason();
30273
30417
  init_steer_request();
30274
30418
  init_ephemeral_automation();
@@ -30817,11 +30961,7 @@ var init_orchestrator = __esm({
30817
30961
  this.emit({ type: "queue_changed", threadId, queue: next.queue });
30818
30962
  this.haltDrain.delete(threadId);
30819
30963
  }
30820
- /**
30821
- * Worktree agent ended the turn after “I’ll let you know” (or left a
30822
- * detached test/pack job running). Queue a continue so the chat does not
30823
- * go idle with nobody watching the log.
30824
- */
30964
+ /** Queue a continue when a turn promised a later report or left a detached job running. */
30825
30965
  maybeEnqueueJobContinue(threadId, chatText, parts = []) {
30826
30966
  if (this.haltDrain.has(threadId)) return;
30827
30967
  const thread = readThread(threadId);
@@ -31218,7 +31358,7 @@ var init_orchestrator = __esm({
31218
31358
  goal: thread.sourceRef || thread.title
31219
31359
  }),
31220
31360
  slackInbound ? [
31221
- "This turn is a Slack DM or @mention. Your reply is posted back in Slack \u2014 keep it concise. Sideboard signs it with this Mac's destination name; do not prefix the name yourself.",
31361
+ "This turn is a Slack DM or @mention. Your reply is posted back in Slack \u2014 keep it concise. Sideboard signs it with this Mac's destination name; do not prefix the name yourself. Do not end the turn by saying you will get back to them. If a child is still running, loop wait_for_turn until stillRunning is false, then reply with the outcome. If the agents are already idle, read get_turn_result and reply now. Ending the turn does not send a later Slack message.",
31222
31362
  SLACK_REPLY_FORMATTING
31223
31363
  ].join("\n") : null
31224
31364
  ].filter(Boolean).join("\n") : null;
@@ -31625,6 +31765,7 @@ ${formatEnvReminder(projectNameForRepoPath(thread.repoPath || thread.worktreePat
31625
31765
  if (exitCode === 0) {
31626
31766
  this.crashContinued.delete(threadId);
31627
31767
  this.maybeEnqueueJobContinue(threadId, chatText, parts);
31768
+ settleChildReportAfterTurn(readThread(threadId), chatText, (id, prompt2) => this.send(id, prompt2));
31628
31769
  } else {
31629
31770
  const blob = [chatText, detail].filter(Boolean).join("\n");
31630
31771
  const failedOver = await isolateQuotaFailover(
@@ -33162,9 +33303,9 @@ function createClippedMcpServer() {
33162
33303
  }
33163
33304
 
33164
33305
  // src/mcp/server.ts
33165
- var import_zod11 = require("zod");
33166
- var import_node_crypto23 = require("crypto");
33167
- var import_node_path72 = require("path");
33306
+ var import_zod12 = require("zod");
33307
+ var import_node_crypto24 = require("crypto");
33308
+ var import_node_path73 = require("path");
33168
33309
  init_orchestrator();
33169
33310
  init_task_state();
33170
33311
  init_worktree();
@@ -35569,9 +35710,1154 @@ function registerScheduleTools(server) {
35569
35710
  );
35570
35711
  }
35571
35712
 
35572
- // src/agent-rpc/handlers.ts
35713
+ // src/mcp/order-tools.ts
35714
+ var import_zod11 = require("zod");
35715
+
35716
+ // src/order/order.ts
35573
35717
  var import_node_crypto21 = require("crypto");
35718
+ var import_node_fs71 = require("fs");
35574
35719
  var import_node_path69 = require("path");
35720
+ init_paths();
35721
+ init_private_file();
35722
+ init_thread_store();
35723
+
35724
+ // src/order/order-model.ts
35725
+ function parseOrderGate(value) {
35726
+ const s = value.trim().toLowerCase().replace(/[\s_-]+/g, "");
35727
+ if (s === "inmain" || s === "main" || s === "merged") return "in-main";
35728
+ if (s === "inprod" || s === "prod" || s === "production") return "in-prod";
35729
+ throw new Error("gate must be in-main or in-prod");
35730
+ }
35731
+ function parseOrderHold(value) {
35732
+ const s = value.trim().toLowerCase().replace(/[\s_-]+/g, "");
35733
+ if (s === "start" || s === "beforestart") return "start";
35734
+ if (s === "merge" || s === "beforemerge") return "merge";
35735
+ throw new Error("hold must be start or merge");
35736
+ }
35737
+ function parseOrderKind(value) {
35738
+ const s = value.trim().toLowerCase().replace(/[\s_-]+/g, "");
35739
+ if (s === "pr" || s === "pull" || s === "pullrequest") return "pr";
35740
+ if (s === "issue" || s === "ticket" || s === "task") return "issue";
35741
+ if (s === "workspace" || s === "worktree" || s === "checkout") return "workspace";
35742
+ if (s === "orchestration" || s === "orchestrator" || s === "agent") return "orchestration";
35743
+ throw new Error("kind must be pr, issue, workspace, or orchestration");
35744
+ }
35745
+ function normalizeOrderTarget(input) {
35746
+ const kind = parseOrderKind(input.kind);
35747
+ const raw = input.ref.trim();
35748
+ if (!raw) throw new Error(`${kind} ref is required`);
35749
+ let ref = raw;
35750
+ if (kind === "pr") {
35751
+ const match = raw.match(/(\d+)/);
35752
+ if (!match) throw new Error("PR ref must be a number");
35753
+ ref = match[1];
35754
+ } else if (kind === "issue") {
35755
+ ref = raw.replace(/^#/, "");
35756
+ }
35757
+ const repoPath = input.repoPath?.trim().replace(/\/+$/, "") || void 0;
35758
+ const label = input.label?.trim() || void 0;
35759
+ const target = { kind, ref };
35760
+ if (repoPath) target.repoPath = repoPath;
35761
+ if (label) target.label = label;
35762
+ return target;
35763
+ }
35764
+ function targetKey(target) {
35765
+ const ref = target.ref.trim().replace(/^#/, "").toLowerCase();
35766
+ const repo = (target.repoPath ?? "").replace(/\/+$/, "").toLowerCase();
35767
+ if (target.kind === "issue" && !repo) return `issue:${ref}`;
35768
+ if (target.kind === "orchestration") return `orchestration:${ref}`;
35769
+ return `${target.kind}:${repo}:${ref}`;
35770
+ }
35771
+ function samePath2(a, b) {
35772
+ return a.trim().replace(/\/+$/, "") === b.trim().replace(/\/+$/, "");
35773
+ }
35774
+ function repoMatches(target, thread) {
35775
+ if (!target.repoPath || !thread.repoPath) return true;
35776
+ return samePath2(target.repoPath, thread.repoPath);
35777
+ }
35778
+ function orderPrNumber(thread) {
35779
+ if (thread.sourceType === "pr") {
35780
+ const n = Number(String(thread.sourceRef).replace(/^#/, ""));
35781
+ if (Number.isInteger(n) && n >= 1) return n;
35782
+ }
35783
+ const match = (thread.prUrl ?? "").match(/\/pull\/(\d+)(?:\/|$|[?#])/i);
35784
+ return match ? Number(match[1]) : null;
35785
+ }
35786
+ function orderTargetMatches(target, thread) {
35787
+ if (!repoMatches(target, thread)) return false;
35788
+ if (target.kind === "pr") {
35789
+ const n = Number(target.ref);
35790
+ return Number.isInteger(n) && orderPrNumber(thread) === n;
35791
+ }
35792
+ if (target.kind === "issue") {
35793
+ if (thread.sourceType !== "ticket") return false;
35794
+ return thread.sourceRef.trim().replace(/^#/, "").toLowerCase() === target.ref.trim().toLowerCase();
35795
+ }
35796
+ if (target.kind === "orchestration") {
35797
+ const orchestrator = thread.sourceType === "orchestration" || thread.repoPath === "__global__";
35798
+ if (!orchestrator) return false;
35799
+ const ref2 = target.ref.trim();
35800
+ if (thread.id === ref2) return true;
35801
+ return ref2.length >= 8 && !ref2.includes("/") && thread.id.startsWith(ref2);
35802
+ }
35803
+ const ref = target.ref.trim();
35804
+ if (thread.id === ref) return true;
35805
+ if (thread.worktreePath && samePath2(thread.worktreePath, ref)) return true;
35806
+ return ref.length >= 8 && !ref.includes("/") && thread.id.startsWith(ref);
35807
+ }
35808
+ function orderSnapshotFromThread(thread) {
35809
+ return {
35810
+ id: thread.id,
35811
+ title: thread.title,
35812
+ sourceType: thread.sourceType,
35813
+ sourceRef: thread.sourceRef,
35814
+ repoPath: thread.repoPath,
35815
+ worktreePath: thread.worktreePath,
35816
+ prUrl: thread.prUrl ?? null,
35817
+ prState: thread.prState ?? null,
35818
+ prTitle: thread.prTitle ?? null,
35819
+ status: thread.status,
35820
+ parentThreadId: "parentThreadId" in thread ? thread.parentThreadId ?? null : null
35821
+ };
35822
+ }
35823
+ function defaultOrderSubject(thread, hold) {
35824
+ const pr = orderPrNumber(thread);
35825
+ if (hold === "merge" && pr) {
35826
+ const target2 = {
35827
+ kind: "pr",
35828
+ ref: String(pr),
35829
+ label: thread.prTitle || thread.title
35830
+ };
35831
+ if (thread.repoPath) target2.repoPath = thread.repoPath;
35832
+ return target2;
35833
+ }
35834
+ if (hold === "start" && thread.sourceType === "ticket" && thread.sourceRef.trim()) {
35835
+ const target2 = {
35836
+ kind: "issue",
35837
+ ref: thread.sourceRef.trim().replace(/^#/, ""),
35838
+ label: thread.title
35839
+ };
35840
+ if (thread.repoPath) target2.repoPath = thread.repoPath;
35841
+ return target2;
35842
+ }
35843
+ const target = {
35844
+ kind: "workspace",
35845
+ ref: thread.worktreePath || thread.id,
35846
+ label: thread.title
35847
+ };
35848
+ if (thread.repoPath) target.repoPath = thread.repoPath;
35849
+ return target;
35850
+ }
35851
+ function assertCallerOwnsSubject(caller, subject) {
35852
+ if (!orderTargetMatches(subject, caller)) {
35853
+ throw new Error(
35854
+ "This checkout can only set a dependency on its own workspace, PR, or ticket."
35855
+ );
35856
+ }
35857
+ }
35858
+ function shortName(target) {
35859
+ if (target.label?.trim()) return target.label.trim();
35860
+ if (target.kind === "pr") return `PR #${target.ref}`;
35861
+ if (target.kind === "issue") return target.ref;
35862
+ if (target.kind === "orchestration") return "that orchestration";
35863
+ return "that workspace";
35864
+ }
35865
+ function dependencyIdentity(edge) {
35866
+ return `${targetKey(edge.waitsOn)}|${edge.gate}|${targetKey(edge.subject)}|${edge.hold}`;
35867
+ }
35868
+ function dependencyWouldCycle(edges, next) {
35869
+ const start = targetKey(next.subject);
35870
+ const goal = targetKey(next.waitsOn);
35871
+ if (start === goal) return true;
35872
+ const adj = /* @__PURE__ */ new Map();
35873
+ for (const edge of edges) {
35874
+ const from = targetKey(edge.waitsOn);
35875
+ const to = targetKey(edge.subject);
35876
+ const list = adj.get(from) ?? [];
35877
+ list.push(to);
35878
+ adj.set(from, list);
35879
+ }
35880
+ const seen = /* @__PURE__ */ new Set();
35881
+ const stack = [start];
35882
+ while (stack.length) {
35883
+ const cur = stack.pop();
35884
+ if (cur === goal) return true;
35885
+ if (seen.has(cur)) continue;
35886
+ seen.add(cur);
35887
+ for (const nextKey of adj.get(cur) ?? []) stack.push(nextKey);
35888
+ }
35889
+ return false;
35890
+ }
35891
+ function cycleDependencyMessage(next) {
35892
+ if (targetKey(next.subject) === targetKey(next.waitsOn)) {
35893
+ return "A step cannot wait on itself.";
35894
+ }
35895
+ return `That dependency loops: ${shortName(next.subject)} already has to finish before ${shortName(next.waitsOn)}.`;
35896
+ }
35897
+ function subjectDepths(edges) {
35898
+ const depth = /* @__PURE__ */ new Map();
35899
+ const touch = (key) => {
35900
+ if (!depth.has(key)) depth.set(key, 0);
35901
+ };
35902
+ for (const edge of edges) {
35903
+ touch(targetKey(edge.waitsOn));
35904
+ touch(targetKey(edge.subject));
35905
+ }
35906
+ for (let pass = 0; pass < depth.size; pass++) {
35907
+ let changed = false;
35908
+ for (const edge of edges) {
35909
+ const from = targetKey(edge.waitsOn);
35910
+ const to = targetKey(edge.subject);
35911
+ const next = (depth.get(from) ?? 0) + 1;
35912
+ if (next > (depth.get(to) ?? 0)) {
35913
+ depth.set(to, next);
35914
+ changed = true;
35915
+ }
35916
+ }
35917
+ if (!changed) break;
35918
+ }
35919
+ return depth;
35920
+ }
35921
+ function threadFor(target, threads) {
35922
+ const live = threads.filter((thread) => thread.status !== "archived");
35923
+ return live.find((thread) => orderTargetMatches(target, thread)) ?? threads.find((thread) => orderTargetMatches(target, thread));
35924
+ }
35925
+ function orderTargetLabel(target, threads) {
35926
+ const hit = threadFor(target, threads);
35927
+ if (target.kind === "pr") {
35928
+ const title = target.label?.trim() || hit?.prTitle?.trim() || "";
35929
+ const base = `PR #${target.ref}`;
35930
+ return title && title !== base ? `${base} \xB7 ${title}` : base;
35931
+ }
35932
+ if (target.kind === "issue") {
35933
+ const title = target.label?.trim() || (hit?.sourceType === "ticket" ? hit.title.trim() : "");
35934
+ return title && title !== target.ref ? `${target.ref} \xB7 ${title}` : target.ref;
35935
+ }
35936
+ if (target.kind === "orchestration") {
35937
+ return target.label?.trim() || hit?.title?.trim() || "Orchestration";
35938
+ }
35939
+ return target.label?.trim() || hit?.title?.trim() || "Workspace";
35940
+ }
35941
+ function prMerged(target, threads) {
35942
+ return threads.some(
35943
+ (thread) => orderTargetMatches(target, thread) && (thread.prState ?? "").toUpperCase() === "MERGED"
35944
+ );
35945
+ }
35946
+ function orderGateStatus(edge, threads, marks) {
35947
+ const key = targetKey(edge.waitsOn);
35948
+ const marked = marks.some((mark) => mark.key === key && mark.gate === edge.gate);
35949
+ if (edge.gate === "in-prod") {
35950
+ return marked ? { met: true, marked: true, detail: "marked in production" } : { met: false, marked: false, detail: "waiting to be marked in production" };
35951
+ }
35952
+ if (marked) return { met: true, marked: true, detail: "marked in main" };
35953
+ if (prMerged(edge.waitsOn, threads)) {
35954
+ return { met: true, marked: false, detail: "merged to main" };
35955
+ }
35956
+ const known = threads.some((thread) => orderTargetMatches(edge.waitsOn, thread));
35957
+ return known ? { met: false, marked: false, detail: "open \u2014 not in main" } : { met: false, marked: false, detail: "not on the board yet" };
35958
+ }
35959
+ function resolveOrderRows(edges, threads, marks = []) {
35960
+ const depths = subjectDepths(edges);
35961
+ return edges.map((edge) => {
35962
+ const status = orderGateStatus(edge, threads, marks);
35963
+ return {
35964
+ id: edge.id,
35965
+ waitsOn: edge.waitsOn,
35966
+ subject: edge.subject,
35967
+ gate: edge.gate,
35968
+ hold: edge.hold,
35969
+ note: edge.note,
35970
+ loop: edge.loop === true,
35971
+ depth: depths.get(targetKey(edge.subject)) ?? 1,
35972
+ met: status.met,
35973
+ marked: status.marked,
35974
+ detail: status.detail,
35975
+ waitsOnLabel: orderTargetLabel(edge.waitsOn, threads),
35976
+ subjectLabel: orderTargetLabel(edge.subject, threads)
35977
+ };
35978
+ }).sort(
35979
+ (a, b) => a.depth - b.depth || a.waitsOnLabel.localeCompare(b.waitsOnLabel) || a.subjectLabel.localeCompare(b.subjectLabel)
35980
+ );
35981
+ }
35982
+
35983
+ // src/order/order-board.ts
35984
+ function buildWaterfall(rows) {
35985
+ const nodes = /* @__PURE__ */ new Map();
35986
+ const links = [];
35987
+ const depthOf = /* @__PURE__ */ new Map();
35988
+ for (const row of rows) {
35989
+ const to = targetKey(row.subject);
35990
+ depthOf.set(to, Math.max(depthOf.get(to) ?? 0, row.depth));
35991
+ if (!depthOf.has(targetKey(row.waitsOn))) depthOf.set(targetKey(row.waitsOn), 0);
35992
+ }
35993
+ function ensure(target, label) {
35994
+ const key = targetKey(target);
35995
+ let node = nodes.get(key);
35996
+ if (!node) {
35997
+ node = {
35998
+ key,
35999
+ label,
36000
+ kind: target.kind,
36001
+ ref: target.ref,
36002
+ ...target.repoPath ? { repoPath: target.repoPath } : {},
36003
+ depth: depthOf.get(key) ?? 0,
36004
+ incoming: []
36005
+ };
36006
+ nodes.set(key, node);
36007
+ }
36008
+ return node;
36009
+ }
36010
+ for (const row of rows) {
36011
+ ensure(row.waitsOn, row.waitsOnLabel);
36012
+ const subject = ensure(row.subject, row.subjectLabel);
36013
+ subject.depth = Math.max(subject.depth, row.depth);
36014
+ subject.incoming.push({
36015
+ edgeId: row.id,
36016
+ fromKey: targetKey(row.waitsOn),
36017
+ gate: row.gate,
36018
+ hold: row.hold,
36019
+ met: row.met,
36020
+ marked: row.marked,
36021
+ detail: row.detail,
36022
+ fromLabel: row.waitsOnLabel,
36023
+ note: row.note,
36024
+ loop: row.loop === true
36025
+ });
36026
+ links.push({ from: targetKey(row.waitsOn), to: targetKey(row.subject) });
36027
+ }
36028
+ const parent = /* @__PURE__ */ new Map();
36029
+ const find = (key) => {
36030
+ const current = parent.get(key) ?? key;
36031
+ if (current === key) return key;
36032
+ const root = find(current);
36033
+ parent.set(key, root);
36034
+ return root;
36035
+ };
36036
+ for (const key of nodes.keys()) parent.set(key, key);
36037
+ for (const link of links) {
36038
+ const left = find(link.from);
36039
+ const right = find(link.to);
36040
+ if (left !== right) parent.set(left, right);
36041
+ }
36042
+ const groups = /* @__PURE__ */ new Map();
36043
+ for (const node of nodes.values()) {
36044
+ const root = find(node.key);
36045
+ const list = groups.get(root) ?? [];
36046
+ list.push(node);
36047
+ groups.set(root, list);
36048
+ }
36049
+ return [...groups.values()].map((list) => ({
36050
+ nodes: list.sort(
36051
+ (a, b) => a.depth - b.depth || a.label.localeCompare(b.label)
36052
+ )
36053
+ })).sort((a, b) => (a.nodes[0]?.label ?? "").localeCompare(b.nodes[0]?.label ?? ""));
36054
+ }
36055
+ function gatePhrase(gate) {
36056
+ return gate === "in-prod" ? "in production" : "in main";
36057
+ }
36058
+ function holdPhrase(hold) {
36059
+ return hold === "merge" ? "can merge" : "can start";
36060
+ }
36061
+ function ownerMatches(ref, ownerThreadId) {
36062
+ const left = ref.trim();
36063
+ const right = ownerThreadId.trim();
36064
+ if (!left || !right) return false;
36065
+ if (left === right) return true;
36066
+ return left.length >= 8 && !left.includes("/") && right.startsWith(left);
36067
+ }
36068
+ function resolveOrchestrationGates(plans, edges, threads, marks = []) {
36069
+ const rows = resolveOrderRows(edges, threads, marks);
36070
+ const planOf = new Map(edges.map((edge) => [edge.id, edge.planId ?? ""]));
36071
+ for (let pass = 0; pass < 8; pass++) {
36072
+ let changed = false;
36073
+ const clearByOwner = /* @__PURE__ */ new Map();
36074
+ for (const plan of plans) {
36075
+ if (!plan.ownerThreadId) continue;
36076
+ const mine = rows.filter((row) => planOf.get(row.id) === plan.id);
36077
+ clearByOwner.set(plan.ownerThreadId, mine.length > 0 && mine.every((row) => row.met));
36078
+ }
36079
+ for (const row of rows) {
36080
+ if (row.gate !== "in-main" || row.waitsOn.kind !== "orchestration" || row.marked) continue;
36081
+ const plan = plans.find((item) => ownerMatches(row.waitsOn.ref, item.ownerThreadId));
36082
+ const count = plan ? rows.filter((item) => planOf.get(item.id) === plan.id).length : 0;
36083
+ const clear = plan ? clearByOwner.get(plan.ownerThreadId) === true : false;
36084
+ const detail = !plan ? "no plan yet" : count === 0 ? "plan has no steps" : clear ? "plan is clear" : "plan still waiting";
36085
+ if (row.met !== clear || row.detail !== detail) {
36086
+ row.met = clear;
36087
+ row.detail = detail;
36088
+ row.marked = false;
36089
+ changed = true;
36090
+ }
36091
+ }
36092
+ if (!changed) break;
36093
+ }
36094
+ return rows;
36095
+ }
36096
+
36097
+ // src/order/order-present.ts
36098
+ function formatOrderPlace(rows, you) {
36099
+ const mine = (target) => orderTargetMatches(target, you);
36100
+ const waitingOn = rows.filter((row) => mine(row.subject) && !row.met && !row.loop);
36101
+ const looping = rows.filter((row) => mine(row.subject) && row.loop && !row.met);
36102
+ const ready = rows.filter((row) => mine(row.subject) && row.met);
36103
+ const blocking = rows.filter((row) => mine(row.waitsOn) && !row.met && !row.loop);
36104
+ if (!waitingOn.length && !looping.length && !ready.length && !blocking.length) {
36105
+ return "This checkout is not in the planner. set_dependency records what you wait on (omit subject). clear_dependency removes a step you are part of.";
36106
+ }
36107
+ const gate = (row) => row.gate === "in-prod" ? "in prod" : "in main";
36108
+ const lines = ["Where you are in the planner:"];
36109
+ for (const row of waitingOn) {
36110
+ lines.push(
36111
+ `- Waiting: ${row.waitsOnLabel} must be ${gate(row)} before you can ${row.hold}. id: ${row.id.slice(0, 8)}`
36112
+ );
36113
+ }
36114
+ for (const row of looping) {
36115
+ lines.push(
36116
+ `- Loop: returns to ${row.waitsOnLabel} once you are ${gate(row)}. The first pass is not blocked. id: ${row.id.slice(0, 8)}`
36117
+ );
36118
+ }
36119
+ for (const row of ready) {
36120
+ lines.push(`- Clear: you can ${row.hold}. ${row.detail}. id: ${row.id.slice(0, 8)}`);
36121
+ }
36122
+ for (const row of blocking) {
36123
+ lines.push(
36124
+ `- Blocking: ${row.subjectLabel} cannot ${row.hold} until you are ${gate(row)}. id: ${row.id.slice(0, 8)}`
36125
+ );
36126
+ }
36127
+ return lines.join("\n");
36128
+ }
36129
+ function executionSlice(rows) {
36130
+ return {
36131
+ ready: rows.filter((row) => row.met || row.loop),
36132
+ waiting: rows.filter((row) => !row.met && !row.loop)
36133
+ };
36134
+ }
36135
+ function orderEdgeTouches(edge, you) {
36136
+ return orderTargetMatches(edge.subject, you) || orderTargetMatches(edge.waitsOn, you);
36137
+ }
36138
+ function formatOrderText(rows, plan) {
36139
+ if (rows.length === 0) {
36140
+ if (plan) {
36141
+ const goal = plan.goal ? ` Goal: ${plan.goal}.` : "";
36142
+ const summary = plan.summary ? ` ${plan.summary}` : "";
36143
+ return `Plan \u201C${plan.title}\u201D is ${plan.status}.${goal}${summary} No steps yet. set_dependency records each gate.`.replace(/\s+/g, " ").trim();
36144
+ }
36145
+ return "No orchestration plan yet. set_dependency records an order \u2014 for example PR 1 in prod before PR 2 can merge, or PR 3 in main before issue 4 can start. The Orchestration row in the sidebar opens that chat.";
36146
+ }
36147
+ const lines = [
36148
+ plan ? `Plan \u201C${plan.title}\u201D is ${plan.status}. ${plan.goal ? `Goal: ${plan.goal}. ` : ""}${plan.summary}`.trim() : "Orchestration. Steps can wait on a gate or loop back to an earlier step. in-main clears when that PR is merged. in-prod stays waiting until satisfy_dependency.",
36149
+ ""
36150
+ ];
36151
+ rows.forEach((row, index) => {
36152
+ const gate = row.gate === "in-prod" ? "in prod" : "in main";
36153
+ const hold = row.hold === "merge" ? "merge" : "start";
36154
+ const state = row.loop ? "loop" : row.met ? "clear" : "waiting";
36155
+ lines.push(
36156
+ row.loop ? `${index + 1}. ${state} ${row.subjectLabel} returns to ${row.waitsOnLabel} once it is ${gate}` : `${index + 1}. ${state} ${row.waitsOnLabel} must be ${gate} before ${row.subjectLabel} can ${hold}`
36157
+ );
36158
+ lines.push(` ${row.detail}`);
36159
+ if (row.note) lines.push(` ${row.note}`);
36160
+ lines.push(` id: ${row.id.slice(0, 8)}`);
36161
+ });
36162
+ return lines.join("\n");
36163
+ }
36164
+ function escapeHtml2(value) {
36165
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
36166
+ }
36167
+ var WATERFALL_KIND = {
36168
+ pr: "Pull request",
36169
+ issue: "Issue",
36170
+ workspace: "Workspace",
36171
+ orchestration: "Orchestration"
36172
+ };
36173
+ function markWorkingChains(chains, threads) {
36174
+ const active = threads.filter(
36175
+ (thread) => thread.status === "running" || thread.status === "queued"
36176
+ );
36177
+ if (active.length === 0) return chains;
36178
+ return chains.map((chain) => ({
36179
+ nodes: chain.nodes.map((node) => {
36180
+ const working = active.some(
36181
+ (thread) => orderTargetMatches(
36182
+ {
36183
+ kind: node.kind,
36184
+ ref: node.ref,
36185
+ ...node.repoPath ? { repoPath: node.repoPath } : {}
36186
+ },
36187
+ thread
36188
+ )
36189
+ );
36190
+ return working ? { ...node, working: true } : node;
36191
+ })
36192
+ }));
36193
+ }
36194
+ function nodeIsYou(node, you) {
36195
+ if (!you) return false;
36196
+ return orderTargetMatches(
36197
+ {
36198
+ kind: node.kind,
36199
+ ref: node.ref,
36200
+ ...node.repoPath ? { repoPath: node.repoPath } : {}
36201
+ },
36202
+ you
36203
+ );
36204
+ }
36205
+ function formatWaterfallHtml(chains, opts) {
36206
+ const plan = opts?.plan ?? null;
36207
+ const you = opts?.you ?? null;
36208
+ const title = plan?.title?.trim() || "Planner";
36209
+ const status = plan ? plan.status === "active" ? "Running. Ready steps can start. Waiting steps stay held." : "Draft. Discuss this and change it. Nothing runs until you agree." : "Later steps wait until the one above reaches its gate. In main clears when that pull request is merged. In production stays waiting until it is marked.";
36210
+ const body = chains.length === 0 ? '<p class="empty">No order yet.</p>' : chains.map((chain) => {
36211
+ const nodes = chain.nodes.map((node) => {
36212
+ const waiting = node.incoming.some((edge) => !edge.met && !edge.loop);
36213
+ const clear = node.incoming.some((edge) => !edge.loop) && !waiting;
36214
+ const yours = nodeIsYou(node, you);
36215
+ const working = node.working === true;
36216
+ const state = `${waiting ? " waiting" : clear ? " clear" : ""}${yours ? " you" : ""}${working ? " current" : ""}`;
36217
+ const drops = node.incoming.map((edge) => {
36218
+ const tone = edge.loop ? "loop" : edge.met ? "clear" : "waiting";
36219
+ const note = edge.note ? `<span>${escapeHtml2(edge.note)}</span>` : "";
36220
+ return `<div class="drop"><span>After ${escapeHtml2(edge.fromLabel)} is ${escapeHtml2(gatePhrase(edge.gate))}, this ${escapeHtml2(holdPhrase(edge.hold))}</span><span class="${tone}">${escapeHtml2(edge.detail)}</span>${note}</div>`;
36221
+ }).join("");
36222
+ const kicker = `${WATERFALL_KIND[node.kind]}${working ? " \xB7 Working" : ""}${yours ? " \xB7 You" : ""}`;
36223
+ return `<li class="node" style="margin-left:${node.depth * 28}px">${drops}<div class="bar${state}"><span class="kicker">${kicker}</span><strong>${escapeHtml2(node.label)}</strong></div></li>`;
36224
+ }).join("");
36225
+ return `<ol class="chain">${nodes}</ol>`;
36226
+ }).join("");
36227
+ const summary = plan?.summary?.trim() ? `<p class="lead">${escapeHtml2(plan.summary.trim())}</p>` : "";
36228
+ return `<!DOCTYPE html>
36229
+ <html lang="en">
36230
+ <head>
36231
+ <meta charset="utf-8">
36232
+ <title>${escapeHtml2(title)}</title>
36233
+ <style>
36234
+ :root { color-scheme: dark; }
36235
+ body { margin: 0; padding: 20px 22px 32px; background: #141414; color: #ececec; font: 13px/1.4 ui-sans-serif, system-ui, sans-serif; }
36236
+ h1 { font-size: 15px; font-weight: 600; margin: 0 0 6px; }
36237
+ .lead, .empty, .status { color: #9a9a9a; margin: 0 0 18px; max-width: 62ch; }
36238
+ .chain { list-style: none; margin: 0 0 28px; padding: 0; }
36239
+ .drop { margin: 0 0 0 16px; padding: 8px 0 8px 12px; border-left: 1px solid #333; color: #9a9a9a; font-size: 12px; display: flex; flex-direction: column; gap: 3px; }
36240
+ .drop .waiting { color: #e2b340; }
36241
+ .drop .clear, .drop .loop { color: #6fbf73; }
36242
+ .bar { border: 1px solid #333; border-radius: 10px; padding: 10px 12px; background: #1c1c1c; display: flex; flex-direction: column; gap: 2px; }
36243
+ .bar.waiting { border-color: #6a5420; background: #221c10; }
36244
+ .bar.clear { border-color: #2d5a32; background: #142016; }
36245
+ .bar.you { outline: 1px solid #8ab4ff; }
36246
+ .bar.current { border-color: #8ab4ff; box-shadow: inset 3px 0 0 #8ab4ff; }
36247
+ .bar.current .kicker { color: #ececec; }
36248
+ .kicker { font-size: 11px; letter-spacing: 0.04em; text-transform: uppercase; color: #9a9a9a; }
36249
+ </style>
36250
+ </head>
36251
+ <body>
36252
+ <h1>${escapeHtml2(title)}</h1>
36253
+ <p class="status">${escapeHtml2(status)}</p>
36254
+ ${summary}
36255
+ ${body}
36256
+ </body>
36257
+ </html>`;
36258
+ }
36259
+ function checkoutPlanTitle(markdown) {
36260
+ const match = /^#{1,6}[ \t]+(.+?)[ \t]*$/m.exec(markdown);
36261
+ const title = match?.[1]?.replace(/\s+#+\s*$/, "").trim() ?? "";
36262
+ return title.slice(0, 80) || "Implementation plan";
36263
+ }
36264
+ function showPlanDocuments(input) {
36265
+ const docs = [];
36266
+ const markdown = input.checkoutMarkdown ?? "";
36267
+ if (markdown.trim()) {
36268
+ docs.push({
36269
+ title: checkoutPlanTitle(markdown),
36270
+ type: "markdown",
36271
+ artifact_id: "checkout-plan",
36272
+ content: markdown
36273
+ });
36274
+ }
36275
+ const html = input.diagramHtml ?? "";
36276
+ if (html.trim()) {
36277
+ docs.push({
36278
+ title: input.diagramTitle?.trim() || "Planner",
36279
+ type: "html",
36280
+ artifact_id: "plan",
36281
+ content: html
36282
+ });
36283
+ }
36284
+ return docs;
36285
+ }
36286
+ function showPlanMessage(docs, worktree) {
36287
+ const diagram = docs.some((doc) => doc.artifact_id === "plan");
36288
+ const checkout = docs.some((doc) => doc.artifact_id === "checkout-plan");
36289
+ if (diagram && checkout) {
36290
+ return "Opened the orchestration plan and this checkout's implementation plan.";
36291
+ }
36292
+ if (checkout) return "Opened this checkout's implementation plan.";
36293
+ return worktree ? "Opened the orchestration plan in the side column, with this checkout marked." : "Opened the plan in the side column.";
36294
+ }
36295
+
36296
+ // src/order/order.ts
36297
+ function orderPath() {
36298
+ return (0, import_node_path69.join)(appDataDir(), "order.json");
36299
+ }
36300
+ function emptyFile() {
36301
+ return { plans: [], edges: [], marks: [] };
36302
+ }
36303
+ function asPlan(value, fallbackId) {
36304
+ if (!value || typeof value !== "object") return null;
36305
+ const row = value;
36306
+ const title = typeof row.title === "string" ? row.title.trim().slice(0, 120) : "";
36307
+ if (!title) return null;
36308
+ const summary = typeof row.summary === "string" ? row.summary.trim().slice(0, 600) : "";
36309
+ const goal = typeof row.goal === "string" ? row.goal.trim().slice(0, 400) : "";
36310
+ const status = row.status === "active" ? "active" : "draft";
36311
+ const updatedAt = typeof row.updatedAt === "string" && row.updatedAt ? row.updatedAt : (/* @__PURE__ */ new Date()).toISOString();
36312
+ const id = typeof row.id === "string" && row.id.trim() ? row.id.trim() : fallbackId;
36313
+ const ownerThreadId = typeof row.ownerThreadId === "string" ? row.ownerThreadId.trim() : "";
36314
+ return { id, ownerThreadId, title, summary, goal, status, updatedAt };
36315
+ }
36316
+ function asTarget(value) {
36317
+ if (!value || typeof value !== "object") return null;
36318
+ const row = value;
36319
+ if (row.kind !== "pr" && row.kind !== "issue" && row.kind !== "workspace" && row.kind !== "orchestration") {
36320
+ return null;
36321
+ }
36322
+ if (typeof row.ref !== "string" || !row.ref.trim()) return null;
36323
+ try {
36324
+ return normalizeOrderTarget(row);
36325
+ } catch {
36326
+ return null;
36327
+ }
36328
+ }
36329
+ function asEdge(value) {
36330
+ if (!value || typeof value !== "object") return null;
36331
+ const row = value;
36332
+ if (typeof row.id !== "string" || !row.id.trim()) return null;
36333
+ const waitsOn = asTarget(row.waitsOn);
36334
+ const subject = asTarget(row.subject);
36335
+ if (!waitsOn || !subject) return null;
36336
+ if (row.gate !== "in-main" && row.gate !== "in-prod") return null;
36337
+ if (row.hold !== "start" && row.hold !== "merge") return null;
36338
+ return {
36339
+ id: row.id,
36340
+ waitsOn,
36341
+ gate: row.gate,
36342
+ subject,
36343
+ hold: row.hold,
36344
+ ...row.loop === true ? { loop: true } : {},
36345
+ note: typeof row.note === "string" ? row.note.slice(0, 400) : "",
36346
+ createdByThreadId: row.createdByThreadId?.trim() || null,
36347
+ createdAt: typeof row.createdAt === "string" ? row.createdAt : (/* @__PURE__ */ new Date()).toISOString(),
36348
+ ...typeof row.planId === "string" && row.planId.trim() ? { planId: row.planId.trim() } : {}
36349
+ };
36350
+ }
36351
+ function asMark(value) {
36352
+ if (!value || typeof value !== "object") return null;
36353
+ const row = value;
36354
+ if (typeof row.key !== "string" || !row.key.trim()) return null;
36355
+ if (row.gate !== "in-main" && row.gate !== "in-prod") return null;
36356
+ if (typeof row.at !== "string" || !row.at) return null;
36357
+ return { key: row.key, gate: row.gate, at: row.at };
36358
+ }
36359
+ function readFile() {
36360
+ const path = orderPath();
36361
+ if (!(0, import_node_fs71.existsSync)(path)) return emptyFile();
36362
+ try {
36363
+ const parsed = JSON.parse((0, import_node_fs71.readFileSync)(path, "utf8"));
36364
+ if (!parsed || typeof parsed !== "object") return emptyFile();
36365
+ const raw = parsed;
36366
+ const edges = Array.isArray(raw.edges) ? raw.edges.map(asEdge).filter((row) => Boolean(row)) : [];
36367
+ const listed = Array.isArray(raw.plans) ? raw.plans.map((row, index) => asPlan(row, `plan-${index + 1}`)).filter((row) => Boolean(row)) : [];
36368
+ const legacy = listed.length ? null : asPlan(raw.plan, "legacy");
36369
+ let plans = legacy ? [legacy] : listed;
36370
+ if (!plans.length && edges.length) {
36371
+ plans = [
36372
+ {
36373
+ id: "legacy",
36374
+ ownerThreadId: "",
36375
+ title: "Planner",
36376
+ summary: "",
36377
+ goal: "",
36378
+ status: "draft",
36379
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
36380
+ }
36381
+ ];
36382
+ }
36383
+ const fallbackId = plans[0]?.id ?? "";
36384
+ return {
36385
+ plans,
36386
+ edges: edges.map((edge) => ({ ...edge, planId: edge.planId || fallbackId })),
36387
+ marks: Array.isArray(raw.marks) ? raw.marks.map(asMark).filter((row) => Boolean(row)) : []
36388
+ };
36389
+ } catch {
36390
+ return emptyFile();
36391
+ }
36392
+ }
36393
+ function pruneMarks(edges, marks) {
36394
+ const live = new Set(edges.map((edge) => `${targetKey(edge.waitsOn)}|${edge.gate}`));
36395
+ return marks.filter((mark) => live.has(`${mark.key}|${mark.gate}`));
36396
+ }
36397
+ function writeFile(file) {
36398
+ const next = {
36399
+ plans: file.plans,
36400
+ edges: file.edges,
36401
+ marks: pruneMarks(file.edges, file.marks)
36402
+ };
36403
+ writePrivateFile2(orderPath(), `${JSON.stringify(next, null, 2)}
36404
+ `);
36405
+ }
36406
+ function planByOwner(file, ownerThreadId) {
36407
+ const owner = ownerThreadId?.trim() ?? "";
36408
+ if (owner) return file.plans.find((plan) => plan.ownerThreadId === owner) ?? null;
36409
+ return file.plans.length === 1 ? file.plans[0] : null;
36410
+ }
36411
+ function getOrderPlan(ownerThreadId) {
36412
+ return planByOwner(readFile(), ownerThreadId);
36413
+ }
36414
+ function setOrderPlan(input) {
36415
+ const title = input.title.trim().slice(0, 120);
36416
+ if (!title) throw new Error("Plan title is required");
36417
+ const file = readFile();
36418
+ const owner = input.ownerThreadId?.trim() ?? "";
36419
+ const existing = file.plans.find((plan2) => plan2.ownerThreadId === owner);
36420
+ const plan = {
36421
+ id: existing?.id ?? (0, import_node_crypto21.randomUUID)(),
36422
+ ownerThreadId: owner,
36423
+ title,
36424
+ summary: input.summary?.trim().slice(0, 600) ?? existing?.summary ?? "",
36425
+ goal: input.goal === void 0 ? existing?.goal ?? "" : input.goal?.trim().slice(0, 400) ?? "",
36426
+ status: existing?.status === "active" ? "active" : "draft",
36427
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
36428
+ };
36429
+ if (existing) {
36430
+ const index = file.plans.findIndex((row) => row.id === existing.id);
36431
+ file.plans[index] = plan;
36432
+ } else {
36433
+ file.plans.push(plan);
36434
+ }
36435
+ writeFile(file);
36436
+ return plan;
36437
+ }
36438
+ function executeOrderPlan(ownerThreadId) {
36439
+ const file = readFile();
36440
+ const current = planByOwner(file, ownerThreadId);
36441
+ if (!current) throw new Error("set_plan first. This chat has no plan yet.");
36442
+ const edges = file.edges.filter((edge) => edge.planId === current.id);
36443
+ if (edges.length === 0) {
36444
+ throw new Error("The planner is empty. set_plan and set_dependency first.");
36445
+ }
36446
+ const plan = { ...current, status: "active", updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
36447
+ const index = file.plans.findIndex((row) => row.id === current.id);
36448
+ file.plans[index] = plan;
36449
+ writeFile(file);
36450
+ const ids = new Set(edges.map((edge) => edge.id));
36451
+ const rows = resolveOrchestrationGates(file.plans, file.edges, threadSnapshots(), file.marks);
36452
+ const slice = executionSlice(rows.filter((row) => ids.has(row.id)));
36453
+ return { plan, ready: slice.ready, waiting: slice.waiting };
36454
+ }
36455
+ function threadSnapshots() {
36456
+ try {
36457
+ return listThreads({ includeArchived: true }).map(orderSnapshotFromThread);
36458
+ } catch {
36459
+ return [];
36460
+ }
36461
+ }
36462
+ function listOrderRows(planId) {
36463
+ const file = readFile();
36464
+ const rows = resolveOrchestrationGates(file.plans, file.edges, threadSnapshots(), file.marks);
36465
+ if (!planId) return rows;
36466
+ const ids = new Set(file.edges.filter((edge) => edge.planId === planId).map((edge) => edge.id));
36467
+ return rows.filter((row) => ids.has(row.id));
36468
+ }
36469
+ function listWaterfall(planId) {
36470
+ return markWorkingChains(buildWaterfall(listOrderRows(planId)), threadSnapshots());
36471
+ }
36472
+ function selectPlan(file, input) {
36473
+ const planId = input.planId?.trim();
36474
+ if (planId) {
36475
+ const hit = file.plans.find((plan) => plan.id === planId);
36476
+ if (!hit) throw new Error("No plan with that id.");
36477
+ return hit;
36478
+ }
36479
+ const owner = input.ownerThreadId?.trim();
36480
+ if (owner) {
36481
+ const hit = file.plans.find((plan) => plan.ownerThreadId === owner);
36482
+ if (!hit) throw new Error("set_plan first. This chat has no plan yet.");
36483
+ return hit;
36484
+ }
36485
+ if (file.plans.length === 1) return file.plans[0];
36486
+ if (file.plans.length === 0) {
36487
+ const plan = {
36488
+ id: (0, import_node_crypto21.randomUUID)(),
36489
+ ownerThreadId: "",
36490
+ title: "Planner",
36491
+ summary: "",
36492
+ goal: "",
36493
+ status: "draft",
36494
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
36495
+ };
36496
+ file.plans.push(plan);
36497
+ return plan;
36498
+ }
36499
+ throw new Error("More than one plan is open. Pass the orchestration chat.");
36500
+ }
36501
+ function findEdge(id, edges) {
36502
+ const key = id.trim();
36503
+ if (!key) return null;
36504
+ return edges.find((edge) => edge.id === key || key.length >= 8 && edge.id.startsWith(key)) ?? null;
36505
+ }
36506
+ function setOrderDependency(input) {
36507
+ const waitsOn = normalizeOrderTarget(input.waitsOn);
36508
+ const subject = normalizeOrderTarget(input.subject);
36509
+ const gate = parseOrderGate(input.gate);
36510
+ const hold = parseOrderHold(input.hold);
36511
+ const file = readFile();
36512
+ const plan = selectPlan(file, input);
36513
+ const scoped = file.edges.filter((edge2) => edge2.planId === plan.id);
36514
+ const draft = { waitsOn, subject, gate, hold };
36515
+ const existing = scoped.find((edge2) => dependencyIdentity(edge2) === dependencyIdentity(draft));
36516
+ if (existing) return { edge: existing, created: false };
36517
+ if (targetKey(subject) === targetKey(waitsOn)) {
36518
+ throw new Error(cycleDependencyMessage(draft));
36519
+ }
36520
+ const loop = dependencyWouldCycle(scoped, draft);
36521
+ const edge = {
36522
+ id: (0, import_node_crypto21.randomUUID)(),
36523
+ planId: plan.id,
36524
+ waitsOn,
36525
+ gate,
36526
+ subject,
36527
+ hold,
36528
+ ...loop ? { loop: true } : {},
36529
+ note: input.note?.trim().slice(0, 400) ?? "",
36530
+ createdByThreadId: input.createdByThreadId?.trim() || null,
36531
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
36532
+ };
36533
+ file.edges.push(edge);
36534
+ writeFile(file);
36535
+ return { edge, created: true };
36536
+ }
36537
+ function clearOrderDependency(id, caller, ownerThreadId) {
36538
+ const file = readFile();
36539
+ const edge = findEdge(id, file.edges);
36540
+ if (!edge) throw new Error(`No planner step ${id}`);
36541
+ if (caller && !orderEdgeTouches(edge, caller)) {
36542
+ throw new Error("This checkout can only change a step it is part of.");
36543
+ }
36544
+ const owner = ownerThreadId?.trim();
36545
+ if (owner) {
36546
+ const plan = file.plans.find((row) => row.ownerThreadId === owner);
36547
+ if (!plan || edge.planId !== plan.id) {
36548
+ throw new Error("This plan belongs to another orchestration chat.");
36549
+ }
36550
+ }
36551
+ file.edges = file.edges.filter((row) => row.id !== edge.id);
36552
+ writeFile(file);
36553
+ }
36554
+ function satisfyOrderDependency(id, satisfied = true) {
36555
+ const file = readFile();
36556
+ const edge = findEdge(id, file.edges);
36557
+ if (!edge) throw new Error(`No planner step ${id}`);
36558
+ const key = targetKey(edge.waitsOn);
36559
+ file.marks = file.marks.filter((mark) => !(mark.key === key && mark.gate === edge.gate));
36560
+ if (satisfied) file.marks.push({ key, gate: edge.gate, at: (/* @__PURE__ */ new Date()).toISOString() });
36561
+ writeFile(file);
36562
+ return edge;
36563
+ }
36564
+
36565
+ // src/mcp/order-tools.ts
36566
+ init_profile();
36567
+ init_issue_list();
36568
+ init_thread_store();
36569
+ init_global_workspace();
36570
+ init_plan_file();
36571
+ var kindSchema = import_zod11.z.enum(["pr", "issue", "workspace", "orchestration"]);
36572
+ function callerThread() {
36573
+ const id = process.env[SIDEBOARD_THREAD_ID_ENV]?.trim();
36574
+ if (!id) return null;
36575
+ return readThread(id);
36576
+ }
36577
+ function readCheckoutPlan(caller) {
36578
+ if (!caller) return null;
36579
+ if (caller.sourceType === "orchestration" || caller.repoPath === GLOBAL_WORKSPACE_ID) return null;
36580
+ const root = caller.worktreePath?.trim();
36581
+ if (!root) return null;
36582
+ return readPlanFile(root);
36583
+ }
36584
+ function orchestrationOwnerId(worktree) {
36585
+ const caller = callerThread();
36586
+ if (!caller) {
36587
+ throw new Error(
36588
+ worktree ? "No worktree chat is bound to this tool." : "No orchestration chat is bound to this tool."
36589
+ );
36590
+ }
36591
+ if (!worktree) return caller.id;
36592
+ let current = caller.parentThreadId?.trim() || "";
36593
+ const seen = /* @__PURE__ */ new Set([caller.id]);
36594
+ for (let hop = 0; hop < 6 && current && !seen.has(current); hop++) {
36595
+ seen.add(current);
36596
+ const row = readThread(current);
36597
+ if (!row) break;
36598
+ if (row.sourceType === "orchestration" || row.repoPath === GLOBAL_WORKSPACE_ID) return row.id;
36599
+ current = row.parentThreadId?.trim() || "";
36600
+ }
36601
+ throw new Error("This checkout is not connected to an orchestration chat.");
36602
+ }
36603
+ function targetFrom(kind, ref, repoPath, label) {
36604
+ return {
36605
+ kind: parseOrderKind(kind),
36606
+ ref: ref.trim(),
36607
+ ...repoPath?.trim() ? { repoPath: repoPath.trim() } : {},
36608
+ ...label?.trim() ? { label: label.trim() } : {}
36609
+ };
36610
+ }
36611
+ function registerOrderTools(server) {
36612
+ const worktree = sideboardMcpProfile() === "worktree";
36613
+ server.tool(
36614
+ "list_order",
36615
+ worktree ? "Read where this checkout sits in its orchestrator's plan: what you are waiting on, what is clear, and what you are blocking. Call show_plan when the user should see it. Change your step with set_dependency or clear_dependency." : "Read this chat's plan. Call show_plan when the user should see it. Draft with set_plan and set_dependency, revise from their feedback, then execute_plan only after they agree. Do not start planned work while the plan is draft.",
36616
+ {},
36617
+ async () => {
36618
+ try {
36619
+ const owner = orchestrationOwnerId(worktree);
36620
+ const plan = getOrderPlan(owner);
36621
+ const caller = callerThread();
36622
+ if (!plan) {
36623
+ const text7 = worktree ? "This checkout's orchestrator has no plan yet." : "This chat has no plan. set_plan drafts one. Then show_plan so the user sees it.";
36624
+ return { content: [{ type: "text", text: text7 }] };
36625
+ }
36626
+ const rows = listOrderRows(plan.id);
36627
+ const place = worktree && caller ? `${formatOrderPlace(rows, orderSnapshotFromThread(caller))}
36628
+
36629
+ ` : "";
36630
+ return {
36631
+ content: [{ type: "text", text: `${place}${formatOrderText(rows, plan)}` }]
36632
+ };
36633
+ } catch (err) {
36634
+ return mcpJson({ error: err instanceof Error ? err.message : String(err) }, true);
36635
+ }
36636
+ }
36637
+ );
36638
+ server.tool(
36639
+ "set_dependency",
36640
+ worktree ? "Change what this checkout waits on. Omit subject to mean this workspace (hold=merge uses this PR; hold=start on a ticket uses this issue). gate=in-main (met when that PR is merged) or in-prod (stays waiting until satisfy_dependency). hold=start means do not begin; hold=merge means do not merge. You cannot set a dependency for a different checkout. show_plan so the user sees the change." : "Record a step on this orchestration plan. waitsOn must reach gate before subject can hold. gate=in-main is met when that PR is merged; gate=in-prod stays waiting until satisfy_dependency. hold=start blocks starting the subject; hold=merge blocks merging it. Example: PR 1 in prod before PR 2 can merge; PR 3 in main before issue 4 can start. Pass repoPath when the same PR number exists in more than one project. Worktree agents set their own checkout and can omit subject. Then show_plan so the user sees it.",
36641
+ {
36642
+ waitsOnKind: kindSchema.describe("What must happen first: pr, issue, workspace, or orchestration"),
36643
+ waitsOnRef: import_zod11.z.string().describe("PR number (12), issue id (ENG-4), or workspace chat id / worktree path"),
36644
+ waitsOnRepoPath: import_zod11.z.string().optional().describe("Project path when a PR or issue number is not unique"),
36645
+ waitsOnLabel: import_zod11.z.string().optional().describe("Short label on the planner"),
36646
+ gate: import_zod11.z.enum(["in-main", "in-prod"]).describe("in-main: merged to the default branch. in-prod: deployed; mark with satisfy_dependency"),
36647
+ hold: import_zod11.z.enum(["start", "merge"]).describe("start: subject cannot begin. merge: subject cannot merge"),
36648
+ subjectKind: kindSchema.optional().describe("What is held. Required from orchestration. Omit on a worktree to mean this checkout."),
36649
+ subjectRef: import_zod11.z.string().optional().describe("PR number, issue id, or workspace ref for the subject"),
36650
+ subjectRepoPath: import_zod11.z.string().optional(),
36651
+ subjectLabel: import_zod11.z.string().optional(),
36652
+ note: import_zod11.z.string().optional().describe("Why this order matters")
36653
+ },
36654
+ async (args) => {
36655
+ try {
36656
+ const hasKind = Boolean(args.subjectKind);
36657
+ const hasRef = Boolean(args.subjectRef?.trim());
36658
+ if (hasKind !== hasRef) {
36659
+ throw new Error("Pass subjectKind and subjectRef together, or omit both on a worktree.");
36660
+ }
36661
+ const caller = callerThread();
36662
+ let subject;
36663
+ const hold = parseOrderHold(args.hold);
36664
+ if (!hasKind) {
36665
+ if (!worktree) {
36666
+ throw new Error(
36667
+ "Pass subjectKind and subjectRef. A worktree agent can omit them to mean this checkout."
36668
+ );
36669
+ }
36670
+ if (!caller) throw new Error("No worktree chat is bound to this tool.");
36671
+ subject = defaultOrderSubject(orderSnapshotFromThread(caller), hold);
36672
+ } else {
36673
+ subject = targetFrom(
36674
+ args.subjectKind,
36675
+ args.subjectRef,
36676
+ args.subjectRepoPath,
36677
+ args.subjectLabel
36678
+ );
36679
+ if (worktree) {
36680
+ if (!caller) throw new Error("No worktree chat is bound to this tool.");
36681
+ assertCallerOwnsSubject(orderSnapshotFromThread(caller), subject);
36682
+ }
36683
+ }
36684
+ const result = setOrderDependency({
36685
+ waitsOn: targetFrom(
36686
+ args.waitsOnKind,
36687
+ args.waitsOnRef,
36688
+ args.waitsOnRepoPath,
36689
+ args.waitsOnLabel
36690
+ ),
36691
+ gate: parseOrderGate(args.gate),
36692
+ subject,
36693
+ hold,
36694
+ note: args.note,
36695
+ createdByThreadId: caller?.id ?? null,
36696
+ ownerThreadId: orchestrationOwnerId(worktree)
36697
+ });
36698
+ return mcpJson({
36699
+ created: result.created,
36700
+ id: result.edge.id,
36701
+ gate: result.edge.gate,
36702
+ hold: result.edge.hold,
36703
+ waitsOn: result.edge.waitsOn,
36704
+ subject: result.edge.subject
36705
+ });
36706
+ } catch (err) {
36707
+ return mcpJson({ error: err instanceof Error ? err.message : String(err) }, true);
36708
+ }
36709
+ }
36710
+ );
36711
+ if (!worktree) {
36712
+ server.tool(
36713
+ "set_plan",
36714
+ "Draft or retitle this chat's plan. It stays draft until execute_plan. Pass goal for the outcome the steps are trying to reach. Then set_dependency for each gate. A step may loop back to an earlier one. Call show_plan so the user sees it. Do not paste the diagram in chat. Do not start workspaces while it is draft.",
36715
+ {
36716
+ title: import_zod11.z.string().describe("Short name for the plan"),
36717
+ summary: import_zod11.z.string().optional().describe("What this order is for, in a sentence or two"),
36718
+ goal: import_zod11.z.string().optional().describe("Outcome the steps are trying to reach")
36719
+ },
36720
+ async ({ title, summary, goal }) => {
36721
+ try {
36722
+ const plan = setOrderPlan({
36723
+ title,
36724
+ summary,
36725
+ goal,
36726
+ ownerThreadId: orchestrationOwnerId(false)
36727
+ });
36728
+ return mcpJson({ ok: true, ...plan });
36729
+ } catch (err) {
36730
+ return mcpJson({ error: err instanceof Error ? err.message : String(err) }, true);
36731
+ }
36732
+ }
36733
+ );
36734
+ server.tool(
36735
+ "execute_plan",
36736
+ "Mark the plan active after the user has seen it and told you to run it. Returns ready steps (start those with create_workspace or send_to_chat) and waiting steps (leave them alone). Does not create workspaces. Pass agreed: true only after they agree. Merge only if they asked.",
36737
+ {
36738
+ agreed: import_zod11.z.literal(true).describe("True only after the user has seen the plan and told you to run it")
36739
+ },
36740
+ async () => {
36741
+ try {
36742
+ const result = executeOrderPlan(orchestrationOwnerId(false));
36743
+ const brief = (row) => ({
36744
+ id: row.id,
36745
+ hold: row.hold,
36746
+ gate: row.gate,
36747
+ waitsOn: row.waitsOnLabel,
36748
+ subject: row.subjectLabel,
36749
+ detail: row.detail,
36750
+ ...row.loop ? { loop: true } : {}
36751
+ });
36752
+ return mcpJson({
36753
+ ok: true,
36754
+ status: result.plan.status,
36755
+ title: result.plan.title,
36756
+ ready: result.ready.map(brief),
36757
+ waiting: result.waiting.map(brief),
36758
+ message: "Plan is active. Start ready steps with create_workspace or send_to_chat. Leave waiting steps alone. Merge only if the user asked."
36759
+ });
36760
+ } catch (err) {
36761
+ return mcpJson({ error: err instanceof Error ? err.message : String(err) }, true);
36762
+ }
36763
+ }
36764
+ );
36765
+ }
36766
+ server.tool(
36767
+ "show_plan",
36768
+ worktree ? "Open the plans for this checkout in the side column. That is the orchestration diagram, with this checkout marked, and this checkout's implementation plan (plan.md) when the file exists. Does not write either plan. Change a step with set_dependency or clear_dependency, then show it again. Do not paste the diagram in chat." : "Open this chat's plan in the side column. Call it after set_plan or set_dependency so the user sees the plan. A worktree show_plan also opens that checkout's implementation plan (plan.md) when the file exists. Does not write either plan. Do not paste the diagram in chat.",
36769
+ {},
36770
+ async () => {
36771
+ const caller = callerThread();
36772
+ let diagramHtml = null;
36773
+ let diagramTitle = "Planner";
36774
+ let diagramError = null;
36775
+ try {
36776
+ const owner = orchestrationOwnerId(worktree);
36777
+ const plan = getOrderPlan(owner);
36778
+ diagramTitle = plan?.title || "Planner";
36779
+ diagramHtml = formatWaterfallHtml(plan ? listWaterfall(plan.id) : [], {
36780
+ plan,
36781
+ you: caller ? orderSnapshotFromThread(caller) : null
36782
+ });
36783
+ } catch (err) {
36784
+ diagramError = err instanceof Error ? err.message : String(err);
36785
+ }
36786
+ const artifacts = showPlanDocuments({
36787
+ diagramTitle,
36788
+ diagramHtml,
36789
+ checkoutMarkdown: readCheckoutPlan(caller)
36790
+ });
36791
+ if (!artifacts.length) {
36792
+ return mcpJson({ error: diagramError || "Nothing to show." }, true);
36793
+ }
36794
+ const primary = artifacts.find((doc) => doc.artifact_id === "plan") ?? artifacts[0];
36795
+ return mcpJson({
36796
+ ok: true,
36797
+ title: primary.title,
36798
+ type: primary.type,
36799
+ artifact_id: primary.artifact_id,
36800
+ content: primary.content,
36801
+ artifacts,
36802
+ message: showPlanMessage(artifacts, worktree)
36803
+ });
36804
+ }
36805
+ );
36806
+ server.tool(
36807
+ "clear_dependency",
36808
+ worktree ? "Remove a planner step this checkout is part of. Pass id from list_order. Then show_plan so the user sees it." : "Remove one planner step. Pass id from list_order. Then show_plan so the user sees it.",
36809
+ { id: import_zod11.z.string().describe("Step id from list_order") },
36810
+ async ({ id }) => {
36811
+ try {
36812
+ const caller = callerThread();
36813
+ clearOrderDependency(
36814
+ id,
36815
+ worktree && caller ? orderSnapshotFromThread(caller) : null,
36816
+ orchestrationOwnerId(worktree)
36817
+ );
36818
+ return mcpJson({ ok: true, id });
36819
+ } catch (err) {
36820
+ return mcpJson({ error: err instanceof Error ? err.message : String(err) }, true);
36821
+ }
36822
+ }
36823
+ );
36824
+ server.tool(
36825
+ "satisfy_dependency",
36826
+ "Mark a planner gate met. Use this when a PR is in production \u2014 Sideboard cannot see deploys. in-main also clears on its own once that PR is merged. Pass satisfied=false to undo a manual mark. One mark covers every step waiting on that same gate.",
36827
+ {
36828
+ id: import_zod11.z.string().describe("Step id from list_order"),
36829
+ satisfied: import_zod11.z.boolean().optional().describe("false clears the manual mark. Default true.")
36830
+ },
36831
+ async ({ id, satisfied }) => {
36832
+ try {
36833
+ const owner = orchestrationOwnerId(worktree);
36834
+ const plan = getOrderPlan(owner);
36835
+ if (!plan) throw new Error("set_plan first. This chat has no plan yet.");
36836
+ const rows = listOrderRows(plan.id);
36837
+ const hit = rows.find((row) => row.id === id || id.length >= 8 && row.id.startsWith(id));
36838
+ if (!hit) throw new Error("That step is on another orchestration chat's plan.");
36839
+ const caller = callerThread();
36840
+ if (worktree && caller && !orderEdgeTouches(hit, orderSnapshotFromThread(caller))) {
36841
+ throw new Error("This checkout can only change a step it is part of.");
36842
+ }
36843
+ const edge = satisfyOrderDependency(id, satisfied !== false);
36844
+ return mcpJson({
36845
+ ok: true,
36846
+ id: edge.id,
36847
+ satisfied: satisfied !== false,
36848
+ gate: edge.gate,
36849
+ waitsOn: edge.waitsOn
36850
+ });
36851
+ } catch (err) {
36852
+ return mcpJson({ error: err instanceof Error ? err.message : String(err) }, true);
36853
+ }
36854
+ }
36855
+ );
36856
+ }
36857
+
36858
+ // src/agent-rpc/handlers.ts
36859
+ var import_node_crypto22 = require("crypto");
36860
+ var import_node_path70 = require("path");
35575
36861
  init_wait_for_job();
35576
36862
  init_wait_for_turn();
35577
36863
 
@@ -35617,7 +36903,7 @@ setToolPermissionPublisher({
35617
36903
  // src/agent-rpc/handlers.ts
35618
36904
  init_protocol2();
35619
36905
  function presentArtifactResult(input) {
35620
- const id = input.artifact_id?.trim() || `artifact_${Date.now().toString(36)}_${(0, import_node_crypto21.randomUUID)().slice(0, 8)}`;
36906
+ const id = input.artifact_id?.trim() || `artifact_${Date.now().toString(36)}_${(0, import_node_crypto22.randomUUID)().slice(0, 8)}`;
35621
36907
  return {
35622
36908
  ok: true,
35623
36909
  artifact_id: id,
@@ -35636,27 +36922,27 @@ init_gh_errors();
35636
36922
  init_git_auth_mode();
35637
36923
 
35638
36924
  // src/board/load-home-board.ts
35639
- var import_node_fs72 = require("fs");
35640
- var import_node_path71 = require("path");
36925
+ var import_node_fs73 = require("fs");
36926
+ var import_node_path72 = require("path");
35641
36927
  init_worktree();
35642
36928
  init_paths();
35643
36929
 
35644
36930
  // src/board/board-pins.ts
35645
- var import_node_crypto22 = require("crypto");
35646
- var import_node_fs71 = require("fs");
35647
- var import_node_path70 = require("path");
36931
+ var import_node_crypto23 = require("crypto");
36932
+ var import_node_fs72 = require("fs");
36933
+ var import_node_path71 = require("path");
35648
36934
  init_paths();
35649
36935
  init_home_board();
35650
36936
  var FILE = "home-board-pins.json";
35651
36937
  var VERSION = 1;
35652
36938
  function pinsFile() {
35653
- return (0, import_node_path70.join)(appDataDir(), FILE);
36939
+ return (0, import_node_path71.join)(appDataDir(), FILE);
35654
36940
  }
35655
36941
  function readDisk() {
35656
36942
  const path = pinsFile();
35657
- if (!(0, import_node_fs71.existsSync)(path)) return [];
36943
+ if (!(0, import_node_fs72.existsSync)(path)) return [];
35658
36944
  try {
35659
- const raw = JSON.parse((0, import_node_fs71.readFileSync)(path, "utf8"));
36945
+ const raw = JSON.parse((0, import_node_fs72.readFileSync)(path, "utf8"));
35660
36946
  if (raw?.version !== VERSION || !Array.isArray(raw.items)) return [];
35661
36947
  return raw.items.filter((item) => item?.id && item.kind && item.ref);
35662
36948
  } catch {
@@ -35664,8 +36950,8 @@ function readDisk() {
35664
36950
  }
35665
36951
  }
35666
36952
  function writeDisk(items) {
35667
- (0, import_node_fs71.mkdirSync)(appDataDir(), { recursive: true });
35668
- (0, import_node_fs71.writeFileSync)(pinsFile(), JSON.stringify({ version: VERSION, items }, null, 2), "utf8");
36953
+ (0, import_node_fs72.mkdirSync)(appDataDir(), { recursive: true });
36954
+ (0, import_node_fs72.writeFileSync)(pinsFile(), JSON.stringify({ version: VERSION, items }, null, 2), "utf8");
35669
36955
  }
35670
36956
  function listBoardPins() {
35671
36957
  return readDisk();
@@ -35686,7 +36972,7 @@ function homeBoardWorkspaceKey(workspaces) {
35686
36972
  return workspaces.map((w) => w.path).filter(Boolean).sort().join("\n");
35687
36973
  }
35688
36974
  function cacheFile() {
35689
- return (0, import_node_path71.join)(appDataDir(), "home-board-cache.json");
36975
+ return (0, import_node_path72.join)(appDataDir(), "home-board-cache.json");
35690
36976
  }
35691
36977
  function emptyInputs() {
35692
36978
  return {
@@ -35712,9 +36998,9 @@ function shouldCacheHomeBoardInputs(inputs) {
35712
36998
  }
35713
36999
  function readDiskCache() {
35714
37000
  const path = cacheFile();
35715
- if (!(0, import_node_fs72.existsSync)(path)) return null;
37001
+ if (!(0, import_node_fs73.existsSync)(path)) return null;
35716
37002
  try {
35717
- const raw = JSON.parse((0, import_node_fs72.readFileSync)(path, "utf8"));
37003
+ const raw = JSON.parse((0, import_node_fs73.readFileSync)(path, "utf8"));
35718
37004
  if (raw?.version !== CACHE_VERSION || typeof raw.fetchedAt !== "number") {
35719
37005
  return null;
35720
37006
  }
@@ -35728,8 +37014,8 @@ function readDiskCache() {
35728
37014
  }
35729
37015
  function writeDiskCache(entry) {
35730
37016
  try {
35731
- (0, import_node_fs72.mkdirSync)(appDataDir(), { recursive: true });
35732
- (0, import_node_fs72.writeFileSync)(cacheFile(), JSON.stringify(entry), "utf8");
37017
+ (0, import_node_fs73.mkdirSync)(appDataDir(), { recursive: true });
37018
+ (0, import_node_fs73.writeFileSync)(cacheFile(), JSON.stringify(entry), "utf8");
35733
37019
  } catch {
35734
37020
  }
35735
37021
  }
@@ -35984,7 +37270,7 @@ async function startMcpServer() {
35984
37270
  async () => {
35985
37271
  const threads = orch.getThreads();
35986
37272
  const lines = threads.map((t) => {
35987
- const repo = t.repoPath === GLOBAL_WORKSPACE_ID ? "Orchestration" : (0, import_node_path72.basename)(t.repoPath) || t.repoPath;
37273
+ const repo = t.repoPath === GLOBAL_WORKSPACE_ID ? "Orchestration" : (0, import_node_path73.basename)(t.repoPath) || t.repoPath;
35988
37274
  const live = orch.threadLooksLive(t) ? readTurnLive(t.id) : null;
35989
37275
  const parent = t.parentThreadId ? ` parent:${t.parentThreadId.slice(0, 8)}` : "";
35990
37276
  const preview = lastMessagePreview(t.messages, 80);
@@ -36000,18 +37286,18 @@ async function startMcpServer() {
36000
37286
  );
36001
37287
  server.tool(
36002
37288
  "list_board",
36003
- "Home Kanban of workspaces (New, Draft, Review, Approved, Merged) \u2014 one card per checkout; sibling chats on that card are separate agents. Same cards as desktop Home. Path to merge: no PR \u2192 draft PR \u2192 open PR \u2192 approved \u2192 merged. Archive removes the card to Settings \u2192 History (list_archive to browse, restore_workspace to bring it back). Queued/running are activity on the card, not columns. Orchestration chats are not on the board. Filters: query, repoPath, kind (ticket/PR/branch source), ownership (mine = your PRs / WIP; reviewing = someone else's PR), column, limit (default 40). create_workspace adds a workspace (and a Home card), or returns the live checkout if that ticket/PR/named branch is already checked out. That reuse is one checkout, not one agent \u2014 fork_chat to add another.",
37289
+ "Home Kanban of workspaces (New, Draft, Review, Approved, Merged) \u2014 one card per checkout; sibling chats on that card are separate agents. Same cards as desktop Home. Path to merge: no PR \u2192 draft PR \u2192 open PR \u2192 approved \u2192 merged. Archive removes the card to Settings \u2192 History (list_archive to browse, restore_workspace to bring it back). Queued/running are activity on the card, not stages. Orchestration chats are not on the board. Filters: query, repoPath, kind (ticket/PR/branch source), ownership (mine = your PRs / WIP; reviewing = someone else's PR), column, limit (default 40). create_workspace adds a workspace (and a Home card), or returns the live checkout if that ticket/PR/named branch is already checked out. That reuse is one checkout, not one agent \u2014 fork_chat to add another.",
36004
37290
  {
36005
- query: import_zod11.z.string().optional().describe("Case-insensitive token search across title, id, labels, workspace tags, repo"),
36006
- repoPath: import_zod11.z.string().optional().describe("Limit to one project path from list_projects"),
36007
- kind: import_zod11.z.enum(["all", "tickets", "prs", "branches", "threads"]).optional().describe("Filter by worktree source (default all)"),
36008
- ownership: import_zod11.z.enum(["all", "mine", "reviewing"]).optional().describe(
37291
+ query: import_zod12.z.string().optional().describe("Case-insensitive token search across title, id, labels, workspace tags, repo"),
37292
+ repoPath: import_zod12.z.string().optional().describe("Limit to one project path from list_projects"),
37293
+ kind: import_zod12.z.enum(["all", "tickets", "prs", "branches", "threads"]).optional().describe("Filter by worktree source (default all)"),
37294
+ ownership: import_zod12.z.enum(["all", "mine", "reviewing"]).optional().describe(
36009
37295
  "Mine = PRs you authored or local WIP; reviewing = someone else's PR. Uses the gh login."
36010
37296
  ),
36011
- column: import_zod11.z.enum(["new", "draft", "review", "approved", "done", "needs_you"]).optional().describe(
37297
+ column: import_zod12.z.enum(["new", "draft", "review", "approved", "done", "needs_you"]).optional().describe(
36012
37298
  "Return cards for this column only (totals still include the rest). approved is an open PR GitHub has approved. needs_you is a legacy alias for new."
36013
37299
  ),
36014
- limit: import_zod11.z.number().int().positive().optional().describe("Max cards per column (default 40). hidden counts the remainder.")
37300
+ limit: import_zod12.z.number().int().positive().optional().describe("Max cards per column (default 40). hidden counts the remainder.")
36015
37301
  },
36016
37302
  async ({ query, repoPath, kind, ownership, column, limit }) => {
36017
37303
  const workspaces = orch.listWorkspaces();
@@ -36041,7 +37327,7 @@ async function startMcpServer() {
36041
37327
  server.tool(
36042
37328
  "get_chat",
36043
37329
  "Get a compact chat summary by id/ref. Includes last message preview, parentChatId, and child workspace chats (status + lastText). While running, includes progress (last tool/thinking) and lastActivityAt. Includes usage (billed token + costUsd totals when providers reported cost) and lastTurnUsage. blockedReason is why that agent is waiting on a person (question, plan approval, or a reported block).",
36044
- { ref: import_zod11.z.string() },
37330
+ { ref: import_zod12.z.string() },
36045
37331
  async ({ ref }) => {
36046
37332
  const t = orch.getThread(ref);
36047
37333
  if (!t) {
@@ -36088,17 +37374,17 @@ async function startMcpServer() {
36088
37374
  "present_artifact",
36089
37375
  "Show a document or live log in Sideboard\u2019s side column. For html/svg/markdown/react, pass the FULL document and do not also fence that same body in chat. For type=log, pass only NEW lines (same artifact_id appends). Prefer type=log for long-running job output \u2014 do not resend HTML. type=react is a single default-export component (JSX/TSX); only react/react-dom imports.",
36090
37376
  {
36091
- title: import_zod11.z.string().describe("Short title shown in the artifact pane header"),
36092
- type: import_zod11.z.enum(["html", "svg", "markdown", "react", "log"]).describe(
37377
+ title: import_zod12.z.string().describe("Short title shown in the artifact pane header"),
37378
+ type: import_zod12.z.enum(["html", "svg", "markdown", "react", "log"]).describe(
36093
37379
  "html/svg/markdown/react replace the pane. log appends content to the same artifact_id (new lines only)."
36094
37380
  ),
36095
- content: import_zod11.z.string().describe(
37381
+ content: import_zod12.z.string().describe(
36096
37382
  "html/svg/markdown/react: full document. log: only the new lines since the last call (empty is ok for a status-only update)."
36097
37383
  ),
36098
- artifact_id: import_zod11.z.string().optional().describe("Stable id. Required for type=log so later calls append to the same pane."),
36099
- status: import_zod11.z.enum(["running", "ok", "failed", "idle"]).optional().describe("Log header pill: running (working), ok (done), failed, idle"),
36100
- phase: import_zod11.z.string().optional().describe("Log subtitle (Signing, Notarizing, \u2026)"),
36101
- mode: import_zod11.z.enum(["append", "replace"]).optional().describe("log only: append (default) or replace the buffer")
37384
+ artifact_id: import_zod12.z.string().optional().describe("Stable id. Required for type=log so later calls append to the same pane."),
37385
+ status: import_zod12.z.enum(["running", "ok", "failed", "idle"]).optional().describe("Log header pill: running (working), ok (done), failed, idle"),
37386
+ phase: import_zod12.z.string().optional().describe("Log subtitle (Signing, Notarizing, \u2026)"),
37387
+ mode: import_zod12.z.enum(["append", "replace"]).optional().describe("log only: append (default) or replace the buffer")
36102
37388
  },
36103
37389
  async ({ title, type, artifact_id, status, phase, mode }) => {
36104
37390
  return mcpJson(
@@ -36111,15 +37397,15 @@ async function startMcpServer() {
36111
37397
  "ask_user",
36112
37398
  "Ask the user a clarifying multiple-choice question in Sideboard\u2019s composer. Call only when work is blocked on choosing among a few concrete options (approach fork, which API, auth vs cookies). Do not call for greetings, check-ins, \u201Chello\u201D, open-ended how-can-I-help, or to invent a menu of possible next tasks \u2014 reply in chat instead. If one option is the obvious default, proceed without asking. Before calling, write a short chat message explaining the decision and what each option means. Include a description on every option. After calling, stop and wait for answers. Not for \u201Cis the plan ready?\u201D.",
36113
37399
  {
36114
- questions: import_zod11.z.array(
36115
- import_zod11.z.object({
36116
- question: import_zod11.z.string().describe("Full question text ending with ?"),
36117
- header: import_zod11.z.string().max(24).optional().describe("Short label shown above the question"),
36118
- multiSelect: import_zod11.z.boolean().optional().describe("Allow selecting multiple options"),
36119
- options: import_zod11.z.array(
36120
- import_zod11.z.object({
36121
- label: import_zod11.z.string(),
36122
- description: import_zod11.z.string().optional().describe("What this option means / when to choose it (strongly preferred)")
37400
+ questions: import_zod12.z.array(
37401
+ import_zod12.z.object({
37402
+ question: import_zod12.z.string().describe("Full question text ending with ?"),
37403
+ header: import_zod12.z.string().max(24).optional().describe("Short label shown above the question"),
37404
+ multiSelect: import_zod12.z.boolean().optional().describe("Allow selecting multiple options"),
37405
+ options: import_zod12.z.array(
37406
+ import_zod12.z.object({
37407
+ label: import_zod12.z.string(),
37408
+ description: import_zod12.z.string().optional().describe("What this option means / when to choose it (strongly preferred)")
36123
37409
  })
36124
37410
  ).min(2).max(6).describe("2\u20136 choices (Sideboard also offers Other)")
36125
37411
  })
@@ -36145,9 +37431,9 @@ async function startMcpServer() {
36145
37431
  "present_plan",
36146
37432
  PRESENT_PLAN_TOOL_DESCRIPTION,
36147
37433
  {
36148
- title: import_zod11.z.string().optional().describe("Short plan title (defaults to Plan)"),
36149
- content: import_zod11.z.string().min(1).describe("Full plan markdown (headings, steps, risks, open questions)"),
36150
- thread_id: import_zod11.z.string().optional().describe("Sideboard thread id when cwd is not the worktree")
37434
+ title: import_zod12.z.string().optional().describe("Short plan title (defaults to Plan)"),
37435
+ content: import_zod12.z.string().min(1).describe("Full plan markdown (headings, steps, risks, open questions)"),
37436
+ thread_id: import_zod12.z.string().optional().describe("Sideboard thread id when cwd is not the worktree")
36151
37437
  },
36152
37438
  async ({ title, content, thread_id }) => {
36153
37439
  const { writePlanFile: writePlanFile2 } = await Promise.resolve().then(() => (init_plan_file(), plan_file_exports));
@@ -36176,15 +37462,15 @@ async function startMcpServer() {
36176
37462
  "present_schema",
36177
37463
  "Open Sideboard\u2019s schema-driven side column (filterable table and/or form) when the user needs to filter, edit, publish, or persist records. Do not call this just to re-display rows you already wrote as a markdown table. If the user asks for an editable / interactive table, call this even if chat already showed those rows. Pass JSON Schema + optional schemaUi. Prefer datasource=inline with embedded resource/records. Use datasource=brightsy with resource_id only when the user is logged into Brightsy.",
36178
37464
  {
36179
- title: import_zod11.z.string().describe("Pane title"),
36180
- mode: import_zod11.z.enum(["table", "form"]).optional().describe("table = list/filter records; form = edit one record"),
36181
- datasource: import_zod11.z.enum(["brightsy", "inline"]).optional().describe("brightsy resolves via login; inline uses embedded resource/records"),
36182
- resource_id: import_zod11.z.string().optional().describe("Brightsy record type UUID (or generic resource id)"),
36183
- record_id: import_zod11.z.string().optional().describe("Record id when opening form mode"),
36184
- resource: import_zod11.z.record(import_zod11.z.unknown()).optional().describe("Inline { id, title, schema, schemaUi?, slug? }"),
36185
- record: import_zod11.z.record(import_zod11.z.unknown()).optional().describe("Inline record { id, data, published_at? }"),
36186
- records: import_zod11.z.array(import_zod11.z.record(import_zod11.z.unknown())).optional().describe("Inline records for table mode"),
36187
- pane_id: import_zod11.z.string().optional().describe("Stable pane id across updates")
37465
+ title: import_zod12.z.string().describe("Pane title"),
37466
+ mode: import_zod12.z.enum(["table", "form"]).optional().describe("table = list/filter records; form = edit one record"),
37467
+ datasource: import_zod12.z.enum(["brightsy", "inline"]).optional().describe("brightsy resolves via login; inline uses embedded resource/records"),
37468
+ resource_id: import_zod12.z.string().optional().describe("Brightsy record type UUID (or generic resource id)"),
37469
+ record_id: import_zod12.z.string().optional().describe("Record id when opening form mode"),
37470
+ resource: import_zod12.z.record(import_zod12.z.unknown()).optional().describe("Inline { id, title, schema, schemaUi?, slug? }"),
37471
+ record: import_zod12.z.record(import_zod12.z.unknown()).optional().describe("Inline record { id, data, published_at? }"),
37472
+ records: import_zod12.z.array(import_zod12.z.record(import_zod12.z.unknown())).optional().describe("Inline records for table mode"),
37473
+ pane_id: import_zod12.z.string().optional().describe("Stable pane id across updates")
36188
37474
  },
36189
37475
  async (args) => {
36190
37476
  const id = args.pane_id?.trim() || `schema_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
@@ -36205,10 +37491,10 @@ async function startMcpServer() {
36205
37491
  "present_files",
36206
37492
  "Open Sideboard\u2019s Files column (CMS-style file manager: browse, upload, pick). Use datasource=brightsy when the user is logged into Brightsy account storage; datasource=memory for a session-local demo store. Prefer this over claiming a file manager UI is unavailable. Pair with present_schema when editing records that need media.",
36207
37493
  {
36208
- title: import_zod11.z.string().optional().describe("Pane title (default: Files)"),
36209
- datasource: import_zod11.z.enum(["brightsy", "memory"]).optional().describe("brightsy = account storage via login; memory = session demo store"),
36210
- path: import_zod11.z.string().optional().describe("Initial folder path (e.g. public)"),
36211
- pane_id: import_zod11.z.string().optional().describe("Stable pane id across updates")
37494
+ title: import_zod12.z.string().optional().describe("Pane title (default: Files)"),
37495
+ datasource: import_zod12.z.enum(["brightsy", "memory"]).optional().describe("brightsy = account storage via login; memory = session demo store"),
37496
+ path: import_zod12.z.string().optional().describe("Initial folder path (e.g. public)"),
37497
+ pane_id: import_zod12.z.string().optional().describe("Stable pane id across updates")
36212
37498
  },
36213
37499
  async (args) => {
36214
37500
  const id = args.pane_id?.trim() || `files_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
@@ -36228,8 +37514,8 @@ async function startMcpServer() {
36228
37514
  "wait_for_job",
36229
37515
  "Wait on a detached long job (tests, pack, deploy, connector CLI) started with detached-job.cjs. MCP clients kill tools around 60s, so this returns within 45s. Sideboard opens a type=log pane from this result (artifact_id = job id, content = delta). stillRunning is the source of truth \u2014 if true, call wait_for_job again. If the job is hanging, producing no useful output, or doing the wrong thing, call stop_job instead of looping forever. Do not end the turn or tell the user you will let them know later. If false, ok/failed is the result.",
36230
37516
  {
36231
- id: import_zod11.z.string().describe("Detached job id (same kebab-case id passed to detached-job.cjs start)"),
36232
- timeoutMs: import_zod11.z.number().optional()
37517
+ id: import_zod12.z.string().describe("Detached job id (same kebab-case id passed to detached-job.cjs start)"),
37518
+ timeoutMs: import_zod12.z.number().optional()
36233
37519
  },
36234
37520
  async ({ id, timeoutMs }) => {
36235
37521
  const result = await waitForDetachedJob(process.cwd(), id, {
@@ -36242,8 +37528,8 @@ async function startMcpServer() {
36242
37528
  "stop_job",
36243
37529
  "Stop a detached job you started with detached-job.cjs when it is hanging, producing no useful output, buffering forever, or doing the wrong thing (wrong project, infinite watch, huge dump). Do not stop a pack/test/deploy that is clearly making progress. The type=log pane updates to status=failed with the last delta. Then decide the next step.",
36244
37530
  {
36245
- id: import_zod11.z.string().describe("Detached job id (same kebab-case id passed to detached-job.cjs start)"),
36246
- reason: import_zod11.z.string().optional().describe("Why you are stopping (hanging, no progress, wrong output, already have the answer)")
37531
+ id: import_zod12.z.string().describe("Detached job id (same kebab-case id passed to detached-job.cjs start)"),
37532
+ reason: import_zod12.z.string().optional().describe("Why you are stopping (hanging, no progress, wrong output, already have the answer)")
36247
37533
  },
36248
37534
  async ({ id, reason }) => {
36249
37535
  const result = await stopDetachedJob(process.cwd(), id, { reason });
@@ -36255,7 +37541,7 @@ async function startMcpServer() {
36255
37541
  "list_run_scripts",
36256
37542
  "List .sideboard/.conductor run scripts for this thread (same menu as the desktop Dev button) and which are active. Each script and active run includes preview: url (open http://localhost:<SIDEBOARD_PORT>) or window (Electron: native window is the app; url is renderer/HMR only). Never guess :3000. Worktree turns may omit ref (uses cwd).",
36257
37543
  {
36258
- ref: import_zod11.z.string().optional().describe("Thread id. Omit on a worktree turn (uses cwd).")
37544
+ ref: import_zod12.z.string().optional().describe("Thread id. Omit on a worktree turn (uses cwd).")
36259
37545
  },
36260
37546
  async ({ ref }) => {
36261
37547
  try {
@@ -36285,8 +37571,8 @@ async function startMcpServer() {
36285
37571
  "run_dev_script",
36286
37572
  "Start a .sideboard/.conductor run script (same as the desktop Dev / play button). Several named scripts can run at once; each gets its own port, and starting one does not stop the others. Logs and Stop appear in the thread UI \u2014 do not detached-job or shell-spawn the same command. Returns {port, ports, url, preview}. preview=url \u2192 open url (browser, curl, Playwright). preview=window \u2192 Electron: the native window is the app; url is renderer/HMR only (no preload/IPC in a browser). The port is allocated SIDEBOARD_PORT, not 3000. Worktree turns may omit ref (uses cwd). Omit name for the default script.",
36287
37573
  {
36288
- ref: import_zod11.z.string().optional().describe("Thread id. Omit on a worktree turn (uses cwd)."),
36289
- name: import_zod11.z.string().optional().describe("Script name from list_run_scripts (default script if omitted).")
37574
+ ref: import_zod12.z.string().optional().describe("Thread id. Omit on a worktree turn (uses cwd)."),
37575
+ name: import_zod12.z.string().optional().describe("Script name from list_run_scripts (default script if omitted).")
36290
37576
  },
36291
37577
  async ({ ref, name }) => {
36292
37578
  try {
@@ -36314,8 +37600,8 @@ async function startMcpServer() {
36314
37600
  "stop_dev_script",
36315
37601
  "Stop a run script started with run_dev_script or the desktop Dev button (same as UI Stop). Omit name to stop all scripts on this worktree. Worktree turns may omit ref (uses cwd).",
36316
37602
  {
36317
- ref: import_zod11.z.string().optional().describe("Thread id. Omit on a worktree turn (uses cwd)."),
36318
- name: import_zod11.z.string().optional().describe("Script name to stop; omit to stop all active scripts.")
37603
+ ref: import_zod12.z.string().optional().describe("Thread id. Omit on a worktree turn (uses cwd)."),
37604
+ name: import_zod12.z.string().optional().describe("Script name to stop; omit to stop all active scripts.")
36319
37605
  },
36320
37606
  async ({ ref, name }) => {
36321
37607
  try {
@@ -36332,9 +37618,9 @@ async function startMcpServer() {
36332
37618
  "get_run_log",
36333
37619
  "Read the Run-tab terminal for a worktree script (same stdout/stderr as the desktop Dev pane). Default is a tail \u2014 raise `tail` only if the error is missing. Worktree turns may omit ref (uses cwd). Omit name for the default script.",
36334
37620
  {
36335
- ref: import_zod11.z.string().optional().describe("Thread id. Omit on a worktree turn (uses cwd)."),
36336
- name: import_zod11.z.string().optional().describe("Script name from list_run_scripts (default script if omitted)."),
36337
- tail: import_zod11.z.number().int().min(1).max(MAX_RUN_LOG_CHARS).optional().describe(
37621
+ ref: import_zod12.z.string().optional().describe("Thread id. Omit on a worktree turn (uses cwd)."),
37622
+ name: import_zod12.z.string().optional().describe("Script name from list_run_scripts (default script if omitted)."),
37623
+ tail: import_zod12.z.number().int().min(1).max(MAX_RUN_LOG_CHARS).optional().describe(
36338
37624
  `Max characters to return from the end (default ${DEFAULT_RUN_LOG_TAIL_CHARS}). Do not request the full buffer unless the tail is truncated and you still need more.`
36339
37625
  )
36340
37626
  },
@@ -36397,8 +37683,8 @@ async function startMcpServer() {
36397
37683
  "notify_orchestrator",
36398
37684
  "Wake the parent Global orchestrator with a short status so it does not have to poll wait_for_turn. Use when you are blocked and the parent may have moved on (missing access, waiting on something the coordinator must handle). The message is shown on the sidebar and board until the next user message in this chat. ask_user already notifies for input-required \u2014 do not call this for the same question. Information only: never a git command. Do not use this to steer other worktrees.",
36399
37685
  {
36400
- message: import_zod11.z.string().min(1).max(1500).describe("Why you are blocked / what the parent should know (short)."),
36401
- reason: import_zod11.z.enum(["input-required", "blocked"]).optional().describe(
37686
+ message: import_zod12.z.string().min(1).max(1500).describe("Why you are blocked / what the parent should know (short)."),
37687
+ reason: import_zod12.z.enum(["input-required", "blocked"]).optional().describe(
36402
37688
  "input-required = waiting on the user in this chat; blocked = need the coordinator (default)."
36403
37689
  )
36404
37690
  },
@@ -36431,15 +37717,16 @@ async function startMcpServer() {
36431
37717
  );
36432
37718
  }
36433
37719
  registerScheduleTools(server);
37720
+ registerOrderTools(server);
36434
37721
  server.tool(
36435
37722
  "set_workspace_tags",
36436
37723
  worktreeProfile ? "Update tags on this workspace (the checkout you are in). Omit ref to use this chat. mode=replace (default), add, or remove. Short labels \u2014 the same ones the orchestrator used for this task. You cannot retag a different checkout." : "Label a project workspace so related checkouts stay recognizable in the sidebar and on the phone. Pass any chat id on that workspace. Use the same tags on every workspace from one task. mode=replace is the default; add and remove change the set. create_workspace tags= sets them at create time. Not for orchestration chats.",
36437
37724
  {
36438
- ref: import_zod11.z.string().optional().describe(
37725
+ ref: import_zod12.z.string().optional().describe(
36439
37726
  worktreeProfile ? "Omit for this chat. Another chat id only if it is on this same checkout." : "Chat id on the workspace to label."
36440
37727
  ),
36441
- tags: import_zod11.z.union([import_zod11.z.string(), import_zod11.z.array(import_zod11.z.string())]).describe("Labels to set. A string may be comma-separated."),
36442
- mode: import_zod11.z.enum(["replace", "add", "remove"]).optional()
37728
+ tags: import_zod12.z.union([import_zod12.z.string(), import_zod12.z.array(import_zod12.z.string())]).describe("Labels to set. A string may be comma-separated."),
37729
+ mode: import_zod12.z.enum(["replace", "add", "remove"]).optional()
36443
37730
  },
36444
37731
  async ({ ref, tags, mode }) => {
36445
37732
  try {
@@ -36473,7 +37760,7 @@ async function startMcpServer() {
36473
37760
  "set_caffeinate",
36474
37761
  "Keep this Mac awake with caffeinate across turns \u2014 independent of Settings toggles. A connected phone already holds caffeinate (lid can close on power), so do not turn this on just because they are on the phone. Turn ON when the user will be away and no phone is connected, or they ask you to keep the machine awake. Turn OFF when they say they are done, wrapping up, going to sleep, or no longer need the Mac awake. Closing or archiving this orchestration chat also releases the hold. macOS only.",
36475
37762
  {
36476
- enabled: import_zod11.z.boolean().describe("true = hold caffeinate on; false = release and let the Mac sleep")
37763
+ enabled: import_zod12.z.boolean().describe("true = hold caffeinate on; false = release and let the Mac sleep")
36477
37764
  },
36478
37765
  async ({ enabled }) => {
36479
37766
  const threadId = process.env.SIDEBOARD_ORCHESTRATOR_THREAD_ID?.trim() || null;
@@ -36499,24 +37786,24 @@ async function startMcpServer() {
36499
37786
  "create_workspace",
36500
37787
  `Create a workspace (isolated git checkout + first chat) from branch, pr, or ticket. A ticket, PR, or named branch has one checkout \u2014 if one already matches, returns it (alreadyStarted=true) instead of a second checkout. That is not one agent: chats lists every agent on that checkout. Add another with fork_chat; send_to_chat only the chat that should do this job. Creating from the default branch still opens a new isolated checkout. Pass repoPath from list_projects. cowboy=true uses the project folder on the default branch (no isolated worktree; land is commit+push). From an orchestration chat, omit parentChatId (Sideboard binds the child to this chat) or pass the exact id from the turn reminder \u2014 never invent a uuid. Omit agent/model \u2014 Sideboard applies ${accountDefaultsHint}. Do not pass your own agent or agent=cursor; those are ignored. Setup (settings.toml, .cursor/worktrees.json, or script/setup) runs in the background in parallel with the first turn (skipped for cowboy). Pass the same tags on every workspace you open for one task (short labels such as "phone-sync") so they still match in the sidebar the next day. Reusing a checkout adds those tags.`,
36501
37788
  {
36502
- sourceType: import_zod11.z.enum(["branch", "pr", "ticket"]),
36503
- sourceRef: import_zod11.z.string(),
36504
- agent: import_zod11.z.enum(["claude", "codex", "opencode", "brightsy", "cursor"]).optional().describe(
37789
+ sourceType: import_zod12.z.enum(["branch", "pr", "ticket"]),
37790
+ sourceRef: import_zod12.z.string(),
37791
+ agent: import_zod12.z.enum(["claude", "codex", "opencode", "brightsy", "cursor"]).optional().describe(
36505
37792
  `Usually omit. Sideboard uses Account default agent (${accountDefaults.agent}). Passing your own agent or cursor is ignored.`
36506
37793
  ),
36507
- model: import_zod11.z.string().nullable().optional().describe(
37794
+ model: import_zod12.z.string().nullable().optional().describe(
36508
37795
  `Usually omit to use Account default model (${accountDefaults.model?.trim() || "Auto"}). Pass null only to force Auto / agent-default.`
36509
37796
  ),
36510
- repoPath: import_zod11.z.string(),
36511
- title: import_zod11.z.string().optional(),
36512
- cowboy: import_zod11.z.boolean().optional().describe(
37797
+ repoPath: import_zod12.z.string(),
37798
+ title: import_zod12.z.string().optional(),
37799
+ cowboy: import_zod12.z.boolean().optional().describe(
36513
37800
  "If true, work in the project folder on the default branch (no thread/* worktree). Requires Settings \u2192 Advanced \u2192 Cowboy mode. Land is commit+push to that branch. Archive does not delete the folder."
36514
37801
  ),
36515
- parentChatId: import_zod11.z.string().optional().describe(
37802
+ parentChatId: import_zod12.z.string().optional().describe(
36516
37803
  "Orchestration: omit (preferred) or pass YOUR chat id from the turn reminder / AGENTS.md. Do not invent uuids."
36517
37804
  ),
36518
- parentThreadId: import_zod11.z.string().optional().describe("Legacy alias for parentChatId."),
36519
- tags: import_zod11.z.union([import_zod11.z.string(), import_zod11.z.array(import_zod11.z.string())]).optional().describe(
37805
+ parentThreadId: import_zod12.z.string().optional().describe("Legacy alias for parentChatId."),
37806
+ tags: import_zod12.z.union([import_zod12.z.string(), import_zod12.z.array(import_zod12.z.string())]).optional().describe(
36520
37807
  "Short labels for this workspace (or a comma-separated string). Use the same tags on every checkout for one task. Added when the checkout already exists."
36521
37808
  )
36522
37809
  },
@@ -36532,11 +37819,11 @@ async function startMcpServer() {
36532
37819
  "start_board_card",
36533
37820
  "Same as create_workspace for a ticket, PR, or named branch (attaches issue text when Sideboard can resolve it). Does not create a second checkout when one already matches \u2014 returns that workspace (alreadyStarted) and its chats. A workspace can have many agents. fork_chat to add one; send_to_chat only the chat that should do this job.",
36534
37821
  {
36535
- kind: import_zod11.z.enum(["ticket", "pr", "branch"]),
36536
- ref: import_zod11.z.string().describe("Ticket identifier (ENG-12), PR number (44), or branch name from list_board"),
36537
- repoPath: import_zod11.z.string().describe("Project path from list_projects / list_board"),
36538
- title: import_zod11.z.string().optional(),
36539
- tags: import_zod11.z.union([import_zod11.z.string(), import_zod11.z.array(import_zod11.z.string())]).optional().describe(
37822
+ kind: import_zod12.z.enum(["ticket", "pr", "branch"]),
37823
+ ref: import_zod12.z.string().describe("Ticket identifier (ENG-12), PR number (44), or branch name from list_board"),
37824
+ repoPath: import_zod12.z.string().describe("Project path from list_projects / list_board"),
37825
+ title: import_zod12.z.string().optional(),
37826
+ tags: import_zod12.z.union([import_zod12.z.string(), import_zod12.z.array(import_zod12.z.string())]).optional().describe(
36540
37827
  "Short labels for this workspace. Same tags on every checkout for one task. Added when the checkout already exists."
36541
37828
  )
36542
37829
  },
@@ -36592,7 +37879,7 @@ async function startMcpServer() {
36592
37879
  const ident = issue?.identifier ?? ref.trim();
36593
37880
  const attachments = issue ? [
36594
37881
  {
36595
- id: (0, import_node_crypto23.randomUUID)(),
37882
+ id: (0, import_node_crypto24.randomUUID)(),
36596
37883
  name: issue.identifier,
36597
37884
  kind: "issue",
36598
37885
  content: [
@@ -36641,9 +37928,9 @@ async function startMcpServer() {
36641
37928
  "send_to_chat",
36642
37929
  'Steer a prompt on a workspace chat (Settings \u2192 Follow-up, default steer: interrupt the in-flight turn and start now, same as the workspace composer). Use after create_workspace to start or continue a conversation. For commit/push/PR, prefer ask_git (canonical desktop-button phrases). Send "Merge PR." / ask_git merge only when the user explicitly asked to merge. force_stop=true kills the in-flight turn and clears the queue before this prompt \u2014 only when the current request is wrong and must be replaced. Do not send_to_chat to check in, resume after a halt notice, or because wait_for_turn returned stillRunning; that interrupts the child mid-thought. Call wait_for_turn again instead.',
36643
37930
  {
36644
- ref: import_zod11.z.string(),
36645
- prompt: import_zod11.z.string(),
36646
- force_stop: import_zod11.z.boolean().optional()
37931
+ ref: import_zod12.z.string(),
37932
+ prompt: import_zod12.z.string(),
37933
+ force_stop: import_zod12.z.boolean().optional()
36647
37934
  },
36648
37935
  async ({ ref, prompt, force_stop }) => {
36649
37936
  if (force_stop) {
@@ -36668,8 +37955,8 @@ async function startMcpServer() {
36668
37955
  "wait_for_turn",
36669
37956
  "Wait until the chat finishes its current/queued turn, or return early with a live progress snapshot. MCP clients often kill tools around 60s, so this returns within 45s even while the child is still working. taskState is the A2A-style lifecycle: submitted (queued, not started), working, input-required (ask_user), completed, failed, canceled. stillRunning is true only for submitted/working. blockedReason is why the child is waiting on a person (the question, plan approval, or a reported block) \u2014 read it and do not send_to_chat a check-in. If stillRunning, text and usage are empty (they would be the previous turn) \u2014 read progress and call wait_for_turn again. Do not send_to_chat a check-in (that steers / interrupts). On failed, lastError/text is the failure. On canceled, the child did not finish \u2014 resume with send_to_chat or tell the user. On input-required, wait for the user in that chat. When finished, text is this turn\u2019s assistant reply and usage is that turn\u2019s tokens + costUsd (this turn, not the Claude session total; sessionCostUsd is the provider session total when present).",
36670
37957
  {
36671
- ref: import_zod11.z.string(),
36672
- timeoutMs: import_zod11.z.number().optional()
37958
+ ref: import_zod12.z.string(),
37959
+ timeoutMs: import_zod12.z.number().optional()
36673
37960
  },
36674
37961
  async ({ ref, timeoutMs }) => {
36675
37962
  const thread = await orch.waitForTurn(ref, mcpWaitForTurnTimeoutMs(timeoutMs), {
@@ -36697,7 +37984,7 @@ async function startMcpServer() {
36697
37984
  server.tool(
36698
37985
  "get_turn_result",
36699
37986
  "Assistant message and last-turn usage when the turn finished. While stillRunning (submitted/working), text and usage are empty so a previous reply cannot be mistaken for this turn \u2014 use progress for tools/thinking. Not the full transcript. Includes taskState (A2A lifecycle) and blockedReason (why the agent is waiting on a person).",
36700
- { ref: import_zod11.z.string() },
37987
+ { ref: import_zod12.z.string() },
36701
37988
  async ({ ref }) => {
36702
37989
  const result = orch.getTurnResult(ref);
36703
37990
  const hint = mcpWaitTaskHint(result.taskState, result.status, result.blockedReason);
@@ -36713,9 +38000,9 @@ async function startMcpServer() {
36713
38000
  "stop_chat",
36714
38001
  "Force-stop a thread: kill any in-flight agent turn AND clear queued prompts so drainQueue cannot continue. Does not archive the worktree. Optional force defaults to true. Pass reason \u2014 a short note on why this chat is stopping. It is stored on the thread and kept when the turn unwinds. If you omit it, Sideboard still records that the queue was cleared.",
36715
38002
  {
36716
- ref: import_zod11.z.string(),
36717
- force: import_zod11.z.boolean().optional(),
36718
- reason: import_zod11.z.string().optional().describe("Why this chat is stopping. Stored on the thread for the next session.")
38003
+ ref: import_zod12.z.string(),
38004
+ force: import_zod12.z.boolean().optional(),
38005
+ reason: import_zod12.z.string().optional().describe("Why this chat is stopping. Stored on the thread for the next session.")
36719
38006
  },
36720
38007
  async ({ ref, force, reason }) => {
36721
38008
  const t = orch.getThread(ref);
@@ -36741,8 +38028,8 @@ async function startMcpServer() {
36741
38028
  "get_diff",
36742
38029
  "Compact diff summary (capped hunks, paginated)",
36743
38030
  {
36744
- ref: import_zod11.z.string(),
36745
- maxFiles: import_zod11.z.number().optional()
38031
+ ref: import_zod12.z.string(),
38032
+ maxFiles: import_zod12.z.number().optional()
36746
38033
  },
36747
38034
  async ({ ref, maxFiles }) => {
36748
38035
  const summary = await orch.diffSummary(ref);
@@ -36755,7 +38042,7 @@ async function startMcpServer() {
36755
38042
  server.tool(
36756
38043
  "get_pr_checks",
36757
38044
  "Snapshot of GitHub PR checks for a worktree thread (`gh pr checks` plus merge/review gates). null = no PR. If the user gave a goal (Greptile 5/5, CI green), the worktree agent watches with `gh pr checks --watch` via /long-running \u2014 this tool is a snapshot, not a waiter. Coordinators: do not run gh from the orchestration cwd.",
36758
- { ref: import_zod11.z.string().describe("Worktree thread id/ref") },
38045
+ { ref: import_zod12.z.string().describe("Worktree thread id/ref") },
36759
38046
  async ({ ref }) => {
36760
38047
  try {
36761
38048
  const checks = await orch.getPrChecks(ref);
@@ -36769,7 +38056,7 @@ async function startMcpServer() {
36769
38056
  server.tool(
36770
38057
  "request_review",
36771
38058
  'Start a merge-readiness Review on a worktree agent thread (same as the desktop Review button). If that worktree has a single unused idle agent (no messages), runs the review there; otherwise opens a new Review chat tab. Attaches .claude/skills/review/SKILL.md when present (else copies .sideboard/review.md into .context/review.md, or seeds that file from the stock template), and sends "Review changes in this workspace." Expect Approve / Approve with nits / Request changes / Needs more information in that chat. The review stays there so the user can read it and type next steps \u2014 do not comment on or update the PR or ticket, and do not ask_user after the review, until they ask. Pass a worktree thread ref \u2014 not the orchestrator. Then wait_for_turn (loop while stillRunning) / get_turn_result on the returned review thread id.',
36772
- { ref: import_zod11.z.string().describe("Worktree thread id/ref to review") },
38059
+ { ref: import_zod12.z.string().describe("Worktree thread id/ref to review") },
36773
38060
  async ({ ref }) => {
36774
38061
  try {
36775
38062
  const tab = await orch.requestReview(ref);
@@ -36791,8 +38078,8 @@ async function startMcpServer() {
36791
38078
  "ask_git",
36792
38079
  "Commit & push, open a draft PR, mark ready for review, resolve conflicts, or merge \u2014 same prompts as the desktop git buttons (including Resolve). Always steers the worktree agent; does not push or open the PR locally. Then wait_for_turn (loop while stillRunning). Do not start a checks loop on a plain push \u2014 only if the user gave a goal (CI green, a review score, until checks pass). A push can wake a third-party PR review; the worktree agent acknowledges it only inside that goal. Pass a worktree thread ref (not the orchestrator). action=ready-for-review and action=merge only when the user explicitly asked (or clicked the desktop button). Do not run git or gh from the orchestration cwd.",
36793
38080
  {
36794
- ref: import_zod11.z.string().describe("Worktree thread id/ref"),
36795
- action: import_zod11.z.enum(AGENT_GIT_ACTIONS).describe(
38081
+ ref: import_zod12.z.string().describe("Worktree thread id/ref"),
38082
+ action: import_zod12.z.enum(AGENT_GIT_ACTIONS).describe(
36796
38083
  "commit-push | create-draft | create-web | resolve-conflicts | ready-for-review | merge"
36797
38084
  )
36798
38085
  },
@@ -36821,7 +38108,7 @@ async function startMcpServer() {
36821
38108
  }
36822
38109
  }
36823
38110
  );
36824
- const agentEnum = import_zod11.z.enum(["claude", "codex", "opencode", "brightsy", "cursor"]);
38111
+ const agentEnum = import_zod12.z.enum(["claude", "codex", "opencode", "brightsy", "cursor"]);
36825
38112
  server.tool(
36826
38113
  "list_models",
36827
38114
  "List models for an agent. Prefer Auto: do not call this unless you have a reason to pin a specific model (user request, cost/latency, capability). Omit agent to list all.",
@@ -36842,11 +38129,11 @@ async function startMcpServer() {
36842
38129
  "fork_workspace",
36843
38130
  "Fork a worktree agent chat into a NEW git worktree + chat (desktop \u201CFork to new workspace\u201D). Seeds a transcript (through through_index, default all). Optional agent override. Leave model unset for Auto (default) \u2014 only pass model when you have a reason. Not for the orchestrator. Then send_to_chat / wait_for_turn (loop while stillRunning) on the returned id.",
36844
38131
  {
36845
- ref: import_zod11.z.string().describe("Worktree thread id/ref to fork"),
36846
- through_index: import_zod11.z.number().optional().describe("Inclusive message index to include in the transcript (default: all)"),
38132
+ ref: import_zod12.z.string().describe("Worktree thread id/ref to fork"),
38133
+ through_index: import_zod12.z.number().optional().describe("Inclusive message index to include in the transcript (default: all)"),
36847
38134
  agent: agentEnum.optional().describe("Agent for the forked chat (default: same as source)"),
36848
- model: import_zod11.z.string().nullable().optional().describe("Usually omit (Auto). Only set from list_models when you need a specific model"),
36849
- title: import_zod11.z.string().optional()
38135
+ model: import_zod12.z.string().nullable().optional().describe("Usually omit (Auto). Only set from list_models when you need a specific model"),
38136
+ title: import_zod12.z.string().optional()
36850
38137
  },
36851
38138
  async ({ ref, through_index, agent, model, title }) => {
36852
38139
  try {
@@ -36880,11 +38167,11 @@ async function startMcpServer() {
36880
38167
  "fork_chat",
36881
38168
  "Add another agent chat on the SAME workspace (same files, Run, and git). Also forks a Global orchestration chat into a new orchestration tab. Pass agent when the new chat should use a different harness. Leave model unset for Auto unless you have a reason. Orchestration forks require an MCP-capable agent (claude, cursor, codex, opencode \u2014 not brightsy). Use this for a second agent on a checkout (review, another harness, parallel work on the same branch). Do not create_workspace again for that \u2014 it returns the existing checkout. Then send_to_chat / wait_for_turn (loop while stillRunning) on the returned id. Use fork_workspace only when the work needs its own git checkout.",
36882
38169
  {
36883
- ref: import_zod11.z.string().describe("Thread id/ref to fork (worktree agent or orchestration chat)"),
36884
- through_index: import_zod11.z.number().optional().describe("Inclusive message index to include in the transcript (default: all)"),
38170
+ ref: import_zod12.z.string().describe("Thread id/ref to fork (worktree agent or orchestration chat)"),
38171
+ through_index: import_zod12.z.number().optional().describe("Inclusive message index to include in the transcript (default: all)"),
36885
38172
  agent: agentEnum.optional().describe("Agent for the forked chat (default: same as source)"),
36886
- model: import_zod11.z.string().nullable().optional().describe("Usually omit (Auto). Only set from list_models when you need a specific model"),
36887
- title: import_zod11.z.string().optional()
38173
+ model: import_zod12.z.string().nullable().optional().describe("Usually omit (Auto). Only set from list_models when you need a specific model"),
38174
+ title: import_zod12.z.string().optional()
36888
38175
  },
36889
38176
  async ({ ref, through_index, agent, model, title }) => {
36890
38177
  try {
@@ -36922,7 +38209,7 @@ async function startMcpServer() {
36922
38209
  server.tool(
36923
38210
  "run_setup",
36924
38211
  "Re-run workspace setup (Sideboard/Conductor settings, .cursor/worktrees.json, or script/setup). New worktrees already run this automatically.",
36925
- { ref: import_zod11.z.string() },
38212
+ { ref: import_zod12.z.string() },
36926
38213
  async ({ ref }) => {
36927
38214
  const result = await orch.runSetup(ref);
36928
38215
  return mcpJson(result);
@@ -36931,7 +38218,7 @@ async function startMcpServer() {
36931
38218
  server.tool(
36932
38219
  "add_project",
36933
38220
  "Register a git repo as a Sideboard workspace",
36934
- { repoPath: import_zod11.z.string() },
38221
+ { repoPath: import_zod12.z.string() },
36935
38222
  async ({ repoPath }) => {
36936
38223
  const ws = await orch.addWorkspace(repoPath);
36937
38224
  return mcpJson(ws);
@@ -36940,7 +38227,7 @@ async function startMcpServer() {
36940
38227
  server.tool(
36941
38228
  "remove_project",
36942
38229
  "Unregister a Sideboard workspace and archive its chats",
36943
- { repoPath: import_zod11.z.string() },
38230
+ { repoPath: import_zod12.z.string() },
36944
38231
  async ({ repoPath }) => {
36945
38232
  await orch.removeWorkspace(repoPath);
36946
38233
  return { content: [{ type: "text", text: "ok" }] };
@@ -36950,12 +38237,12 @@ async function startMcpServer() {
36950
38237
  "fanout",
36951
38238
  "Best-of-n: create one thread per agent with the same prompt (parallel attempts)",
36952
38239
  {
36953
- prompt: import_zod11.z.string(),
36954
- agents: import_zod11.z.array(import_zod11.z.enum(["claude", "codex", "opencode", "brightsy", "cursor"])),
36955
- repoPath: import_zod11.z.string(),
36956
- sourceType: import_zod11.z.enum(["branch", "pr", "ticket"]).optional(),
36957
- sourceRef: import_zod11.z.string().optional(),
36958
- title: import_zod11.z.string().optional()
38240
+ prompt: import_zod12.z.string(),
38241
+ agents: import_zod12.z.array(import_zod12.z.enum(["claude", "codex", "opencode", "brightsy", "cursor"])),
38242
+ repoPath: import_zod12.z.string(),
38243
+ sourceType: import_zod12.z.enum(["branch", "pr", "ticket"]).optional(),
38244
+ sourceRef: import_zod12.z.string().optional(),
38245
+ title: import_zod12.z.string().optional()
36959
38246
  },
36960
38247
  async (args) => {
36961
38248
  const threads = await orch.bestOfN(args);
@@ -36973,8 +38260,8 @@ async function startMcpServer() {
36973
38260
  "list_branches",
36974
38261
  "List git branches in a registered workspace. Pass repoPath from list_projects (unmerged into the default branch by default \u2014 for create_workspace sourceType=branch).",
36975
38262
  {
36976
- repoPath: import_zod11.z.string(),
36977
- unmergedOnly: import_zod11.z.boolean().optional()
38263
+ repoPath: import_zod12.z.string(),
38264
+ unmergedOnly: import_zod12.z.boolean().optional()
36978
38265
  },
36979
38266
  async ({ repoPath, unmergedOnly }) => {
36980
38267
  const root = await resolveRepoRoot(repoPath);
@@ -36995,19 +38282,19 @@ async function startMcpServer() {
36995
38282
  "list_prs",
36996
38283
  `List GitHub PRs for a registered workspace (the review surface for assigned ticket work \u2014 not the tickets). Pass repoPath from list_projects. "Get me N tickets to review" \u2192 queue=review and limit=N: open non-draft PRs labeled with this project's ready-for-review GitHub label (Settings \u2192 Projects; default eng-review) with no individual user reviewer. Prefer teams that match Settings \u2192 Agents / Projects roles for this repo. A team like engineering-team is not a claim (you are on that team). Also: state (open|closed|merged|all|review), label, reviewer (me|unassigned|login), query, limit (default 40, max 250). Then create_workspace with sourceType=pr.`,
36997
38284
  {
36998
- repoPath: import_zod11.z.string(),
36999
- query: import_zod11.z.string().optional().describe("GitHub search tokens (title, draft:true, \u2026)"),
37000
- queue: import_zod11.z.enum(["review", "mine", "approved", "changes"]).optional().describe(
38285
+ repoPath: import_zod12.z.string(),
38286
+ query: import_zod12.z.string().optional().describe("GitHub search tokens (title, draft:true, \u2026)"),
38287
+ queue: import_zod12.z.enum(["review", "mine", "approved", "changes"]).optional().describe(
37001
38288
  "review = unclaimed ready-for-review inbox (Settings \u2192 Projects label, default eng-review). mine = review-requested:@me. approved / changes = eng-approved / eng-requested-changes."
37002
38289
  ),
37003
- state: import_zod11.z.enum(["open", "closed", "merged", "all", "review"]).optional().describe("GitHub PR state (default open). review is an alias for queue=review."),
37004
- label: import_zod11.z.string().optional().describe(
38290
+ state: import_zod12.z.enum(["open", "closed", "merged", "all", "review"]).optional().describe("GitHub PR state (default open). review is an alias for queue=review."),
38291
+ label: import_zod12.z.string().optional().describe(
37005
38292
  "GitHub label / workflow tag. Comma-separated AND. Examples: eng-review, eng-approved, eng-requested-changes"
37006
38293
  ),
37007
- reviewer: import_zod11.z.string().optional().describe(
38294
+ reviewer: import_zod12.z.string().optional().describe(
37008
38295
  "me (review requested of you), unassigned (no individual reviewer; team queues like engineering-team still count), all, or a GitHub login"
37009
38296
  ),
37010
- limit: import_zod11.z.number().int().positive().max(250).optional().describe("Page size (default 40, max 250). Raise when truncated is true.")
38297
+ limit: import_zod12.z.number().int().positive().max(250).optional().describe("Page size (default 40, max 250). Raise when truncated is true.")
37011
38298
  },
37012
38299
  async ({ repoPath, query, queue, state, label, reviewer, limit }) => {
37013
38300
  const root = await resolveRepoRoot(repoPath);
@@ -37040,7 +38327,7 @@ async function startMcpServer() {
37040
38327
  server.tool(
37041
38328
  "get_pr_stack",
37042
38329
  "Load the GitHub PR stack for a thread worktree (`gh stack view --json`). Returns null JSON when the branch is not stacked. Prefer this before ask_git merge on stacked PRs (and only merge when the user explicitly asked).",
37043
- { ref: import_zod11.z.string() },
38330
+ { ref: import_zod12.z.string() },
37044
38331
  async ({ ref }) => {
37045
38332
  const stack = await orch.getPrStack(ref);
37046
38333
  return mcpJson(stack);
@@ -37050,8 +38337,8 @@ async function startMcpServer() {
37050
38337
  "open_pr_stack_layers",
37051
38338
  "Materialize one worktree+thread per stack layer (or a single 1-based layer). Pass a thread ref already on the stack.",
37052
38339
  {
37053
- ref: import_zod11.z.string(),
37054
- layer: import_zod11.z.number().int().positive().optional()
38340
+ ref: import_zod12.z.string(),
38341
+ layer: import_zod12.z.number().int().positive().optional()
37055
38342
  },
37056
38343
  async ({ ref, layer }) => {
37057
38344
  const result = await orch.openPrStackLayers(ref, { layer });
@@ -37074,9 +38361,9 @@ async function startMcpServer() {
37074
38361
  "add_stack_layer",
37075
38362
  "Add a branch on top of the current stack (`gh stack add`) and open a worktree+thread for it.",
37076
38363
  {
37077
- ref: import_zod11.z.string(),
37078
- branchName: import_zod11.z.string(),
37079
- title: import_zod11.z.string().optional()
38364
+ ref: import_zod12.z.string(),
38365
+ branchName: import_zod12.z.string(),
38366
+ title: import_zod12.z.string().optional()
37080
38367
  },
37081
38368
  async ({ ref, branchName, title }) => {
37082
38369
  const result = await orch.addStackLayer(ref, branchName, { title });
@@ -37094,11 +38381,11 @@ async function startMcpServer() {
37094
38381
  "create_pr_stack",
37095
38382
  "Create a new GitHub PR stack with one Sideboard worktree per layer (bottom\u2192top branch names). Requires `gh extension install github/gh-stack`.",
37096
38383
  {
37097
- repoPath: import_zod11.z.string(),
37098
- branches: import_zod11.z.array(import_zod11.z.string()).min(1),
37099
- agent: import_zod11.z.enum(["claude", "codex", "opencode", "brightsy", "cursor"]),
37100
- base: import_zod11.z.string().optional(),
37101
- title: import_zod11.z.string().optional()
38384
+ repoPath: import_zod12.z.string(),
38385
+ branches: import_zod12.z.array(import_zod12.z.string()).min(1),
38386
+ agent: import_zod12.z.enum(["claude", "codex", "opencode", "brightsy", "cursor"]),
38387
+ base: import_zod12.z.string().optional(),
38388
+ title: import_zod12.z.string().optional()
37102
38389
  },
37103
38390
  async (args) => {
37104
38391
  const result = await orch.createPrStack({
@@ -37126,10 +38413,10 @@ async function startMcpServer() {
37126
38413
  "list_issues",
37127
38414
  "List or search issues (Linear, AbleTime, or GitHub; falls back to GitHub). Cursor Origin has no issue tracker \u2014 a Cursor repo returns unavailableReason unless Linear or AbleTime is the source. Entire tickets are Trails (`entire trail`), not GitHub Issues, so an Entire repo does the same unless Linear or AbleTime is the source. Use Settings \u2192 Agents / Projects notes and roles to pick tickets relevant to the viewer (query + assignee=me or unassigned as the notes say). Default 40; pass query and/or limit (max 250) when truncated. assignee: me (Linear default), unassigned, all, or a user id. Pass updatedSince for new/updated tickets and new comments (\u201Cany updates since yesterday?\u201D). Then create_workspace with sourceType=ticket.",
37128
38415
  {
37129
- repoPath: import_zod11.z.string(),
37130
- query: import_zod11.z.string().optional().describe("Search title, identifier, or description"),
37131
- assignee: import_zod11.z.string().optional().describe("me (Linear default), unassigned, all, a user id, or a GitHub login"),
37132
- limit: import_zod11.z.number().int().positive().max(250).optional().describe("Page size (default 40, max 250). Raise when truncated is true."),
38416
+ repoPath: import_zod12.z.string(),
38417
+ query: import_zod12.z.string().optional().describe("Search title, identifier, or description"),
38418
+ assignee: import_zod12.z.string().optional().describe("me (Linear default), unassigned, all, a user id, or a GitHub login"),
38419
+ limit: import_zod12.z.number().int().positive().max(250).optional().describe("Page size (default 40, max 250). Raise when truncated is true."),
37133
38420
  updatedSince: mcpIssueUpdatedSinceSchema
37134
38421
  },
37135
38422
  async ({ repoPath, query, assignee, limit, updatedSince }) => {