@dunnewold-labs/mr-manager 0.4.8 → 0.4.12

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 (2) hide show
  1. package/dist/index.mjs +1395 -556
  2. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // cli/index.ts
4
- import { Command as Command26 } from "commander";
5
- import { existsSync as existsSync16 } from "fs";
4
+ import { Command as Command27 } from "commander";
5
+ import { existsSync as existsSync17 } from "fs";
6
6
  import { homedir as homedir3 } from "os";
7
7
  import { join as join12 } from "path";
8
8
 
@@ -132,7 +132,7 @@ Remote login \u2014 visit this URL in any browser:
132
132
  }
133
133
  async function loginWithLocalServer(apiUrl) {
134
134
  const port = getRandomPort();
135
- return new Promise((resolve7, reject) => {
135
+ return new Promise((resolve8, reject) => {
136
136
  const server = createServer((req, res) => {
137
137
  const url = new URL(req.url ?? "/", `http://localhost:${port}`);
138
138
  const key = url.searchParams.get("key");
@@ -144,7 +144,7 @@ async function loginWithLocalServer(apiUrl) {
144
144
  </body></html>
145
145
  `);
146
146
  server.close();
147
- if (key) resolve7(key);
147
+ if (key) resolve8(key);
148
148
  else reject(new Error("No key received from server"));
149
149
  });
150
150
  server.listen(port, () => {
@@ -185,7 +185,7 @@ import { fileURLToPath } from "url";
185
185
  // cli/package.json
186
186
  var package_default = {
187
187
  name: "@dunnewold-labs/mr-manager",
188
- version: "0.4.8",
188
+ version: "0.4.12",
189
189
  description: "Mr. Manager - Task and project management CLI",
190
190
  bin: {
191
191
  mr: "./dist/index.mjs"
@@ -356,10 +356,10 @@ function detectVcs(cwd) {
356
356
  // cli/commands/link.ts
357
357
  function prompt(question) {
358
358
  const rl = createInterface({ input: process.stdin, output: process.stdout });
359
- return new Promise((resolve7) => {
359
+ return new Promise((resolve8) => {
360
360
  rl.question(question, (answer) => {
361
361
  rl.close();
362
- resolve7(answer.trim());
362
+ resolve8(answer.trim());
363
363
  });
364
364
  });
365
365
  }
@@ -492,7 +492,7 @@ import { Command as Command8 } from "commander";
492
492
  import { spawn as spawn4, exec } from "child_process";
493
493
  import { randomUUID } from "crypto";
494
494
  import { resolve as resolve2 } from "path";
495
- import { readFileSync as readFileSync5, readdirSync, unlinkSync, existsSync as existsSync7, statSync } from "fs";
495
+ import { readFileSync as readFileSync5, readdirSync, unlinkSync, existsSync as existsSync7, statSync, writeFileSync as writeFileSync4 } from "fs";
496
496
  import * as readline from "readline";
497
497
 
498
498
  // lib/test-runner.ts
@@ -512,25 +512,89 @@ function tryExec(command, cwd) {
512
512
  return false;
513
513
  }
514
514
  }
515
+ function resolveWorktreeStartPoint(hasRemoteBranch, hasLocalBranch, hasOriginMain) {
516
+ if (hasRemoteBranch && !hasLocalBranch) {
517
+ return "origin-branch";
518
+ }
519
+ if (hasLocalBranch) {
520
+ return "local-branch";
521
+ }
522
+ if (hasOriginMain) {
523
+ return "origin-main";
524
+ }
525
+ return null;
526
+ }
527
+ function parseGitWorktreePorcelain(output) {
528
+ const entries = [];
529
+ const blocks = output.trim().split(/\n(?=worktree )/);
530
+ for (const block of blocks) {
531
+ if (!block.trim()) continue;
532
+ let path = null;
533
+ let branch = null;
534
+ for (const line of block.split("\n")) {
535
+ if (line.startsWith("worktree ")) {
536
+ path = line.slice("worktree ".length).trim();
537
+ } else if (line.startsWith("branch ")) {
538
+ const ref = line.slice("branch ".length).trim();
539
+ branch = ref.replace(/^refs\/heads\//, "");
540
+ }
541
+ }
542
+ if (path) {
543
+ entries.push({ path, branch });
544
+ }
545
+ }
546
+ return entries;
547
+ }
548
+ function findExistingWorktreeForBranch(repoDir, branch) {
549
+ try {
550
+ const output = execSync2("git worktree list --porcelain", {
551
+ cwd: repoDir,
552
+ stdio: "pipe"
553
+ }).toString();
554
+ const match = parseGitWorktreePorcelain(output).find((entry) => entry.branch === branch);
555
+ return match?.path ?? null;
556
+ } catch {
557
+ return null;
558
+ }
559
+ }
515
560
  function createWorktree(repoDir, branch, worktreeName) {
516
561
  const wtPath = join4(repoDir, ".mr-worktrees", worktreeName);
517
562
  if (existsSync4(wtPath)) {
518
563
  execSync2(`git checkout ${branch}`, { cwd: wtPath, stdio: "pipe" });
519
- return wtPath;
564
+ return {
565
+ path: wtPath,
566
+ created: false,
567
+ reusedBranchWorktree: false
568
+ };
569
+ }
570
+ const existingBranchWorktree = findExistingWorktreeForBranch(repoDir, branch);
571
+ if (existingBranchWorktree) {
572
+ return {
573
+ path: existingBranchWorktree,
574
+ created: false,
575
+ reusedBranchWorktree: true
576
+ };
520
577
  }
521
578
  tryExec(`git fetch origin ${branch}`, repoDir);
579
+ const hasOriginMain = tryExec(`git fetch origin main`, repoDir) && tryExec(`git rev-parse --verify "origin/main"`, repoDir);
522
580
  const hasRemoteBranch = tryExec(`git rev-parse --verify "origin/${branch}"`, repoDir);
523
581
  const hasLocalBranch = tryExec(`git rev-parse --verify "${branch}"`, repoDir);
524
- if (hasRemoteBranch && !hasLocalBranch) {
582
+ const startPoint = resolveWorktreeStartPoint(hasRemoteBranch, hasLocalBranch, hasOriginMain);
583
+ if (startPoint === "origin-branch") {
525
584
  execSync2(`git worktree add -b "${branch}" "${wtPath}" "origin/${branch}"`, {
526
585
  cwd: repoDir,
527
586
  stdio: "pipe"
528
587
  });
529
- } else if (hasLocalBranch) {
588
+ } else if (startPoint === "local-branch") {
530
589
  execSync2(`git worktree add "${wtPath}" "${branch}"`, {
531
590
  cwd: repoDir,
532
591
  stdio: "pipe"
533
592
  });
593
+ } else if (startPoint === "origin-main") {
594
+ execSync2(`git worktree add -b "${branch}" "${wtPath}" "origin/main"`, {
595
+ cwd: repoDir,
596
+ stdio: "pipe"
597
+ });
534
598
  } else {
535
599
  execSync2(`git worktree add -b "${branch}" "${wtPath}"`, {
536
600
  cwd: repoDir,
@@ -543,7 +607,11 @@ function createWorktree(repoDir, branch, worktreeName) {
543
607
  copyFileSync(src, join4(wtPath, envFile));
544
608
  }
545
609
  }
546
- return wtPath;
610
+ return {
611
+ path: wtPath,
612
+ created: true,
613
+ reusedBranchWorktree: false
614
+ };
547
615
  }
548
616
  function removeWorktree(repoDir, wtPath) {
549
617
  try {
@@ -777,7 +845,7 @@ async function runTest(options) {
777
845
  }
778
846
  log2(`Branch: ${branch}`);
779
847
  log2("Creating git worktree...");
780
- wtPath = createWorktree(localPath, branch, worktreeName);
848
+ wtPath = createWorktree(localPath, branch, worktreeName).path;
781
849
  log2(`Worktree created at ${wtPath}`);
782
850
  log2("Installing dependencies...");
783
851
  try {
@@ -890,6 +958,55 @@ async function runTest(options) {
890
958
  return result;
891
959
  }
892
960
 
961
+ // lib/agent-fallback.ts
962
+ var AGENT_FALLBACK_ORDER = ["claude", "codex", "gemini"];
963
+ function getAgentFallbackChain(agent) {
964
+ const startIndex = AGENT_FALLBACK_ORDER.indexOf(agent);
965
+ if (startIndex === -1) {
966
+ return [];
967
+ }
968
+ return AGENT_FALLBACK_ORDER.slice(startIndex);
969
+ }
970
+ function getAvailableAgentFallbackChain(agent, availability) {
971
+ return getAgentFallbackChain(agent).filter((candidate) => availability[candidate] !== false);
972
+ }
973
+
974
+ // lib/task-workflow.ts
975
+ function normalizeWhitespace(value) {
976
+ return value.replace(/\s+/g, " ").trim();
977
+ }
978
+ var NON_CODE_TASK_KEYWORDS = [
979
+ "no code",
980
+ "no-code",
981
+ "without code",
982
+ "research",
983
+ "document",
984
+ "documentation",
985
+ "docs",
986
+ "prd",
987
+ "test plan",
988
+ "resource",
989
+ "write up",
990
+ "writeup",
991
+ "config via the ui",
992
+ "configuration via the ui",
993
+ "ui configuration",
994
+ "upload"
995
+ ];
996
+ var NON_CODE_TASK_PATTERNS = [
997
+ /\b(?:doesn'?t|does not|don't|do not)\s+(?:involve|require|need)\s+(?:writing\s+)?(?:any\s+)?code\b/,
998
+ /\b(?:without|avoids?)\s+(?:writing\s+)?(?:any\s+)?code\b/,
999
+ /\b(?:no need|skip)\s+to\s+(?:spin up|create|prepare)\s+(?:an?\s+)?worktree\b/
1000
+ ];
1001
+ function taskLikelyDoesNotNeedCodeChanges(task) {
1002
+ if (task.mode && task.mode !== "development") return true;
1003
+ const haystack = normalizeWhitespace(
1004
+ [task.title, task.notes, task.prdContent].filter(Boolean).join(" ").toLowerCase()
1005
+ );
1006
+ if (!haystack) return false;
1007
+ return NON_CODE_TASK_KEYWORDS.some((keyword) => haystack.includes(keyword)) || NON_CODE_TASK_PATTERNS.some((pattern) => pattern.test(haystack));
1008
+ }
1009
+
893
1010
  // cli/browse-runner.ts
894
1011
  import { execSync as execSync4, spawn as spawn3 } from "child_process";
895
1012
  import { existsSync as existsSync6 } from "fs";
@@ -916,7 +1033,7 @@ Run the setup script: cd browse && ./setup`
916
1033
  async function runBrowseCommand2(browseArgs) {
917
1034
  const runner = getBrowseRunner();
918
1035
  const fullArgs = [...runner.args, ...browseArgs];
919
- return new Promise((resolve7) => {
1036
+ return new Promise((resolve8) => {
920
1037
  const proc = spawn3(runner.cmd, fullArgs, {
921
1038
  stdio: ["pipe", "pipe", "pipe"],
922
1039
  env: { ...process.env }
@@ -933,21 +1050,156 @@ async function runBrowseCommand2(browseArgs) {
933
1050
  if (stderr && code !== 0) {
934
1051
  process.stderr.write(stderr);
935
1052
  }
936
- resolve7({ stdout: stdout.trim(), exitCode: code || 0 });
1053
+ resolve8({ stdout: stdout.trim(), exitCode: code || 0 });
937
1054
  });
938
1055
  proc.on("error", () => {
939
- resolve7({ stdout: "", exitCode: 1 });
1056
+ resolve8({ stdout: "", exitCode: 1 });
940
1057
  });
941
1058
  });
942
1059
  }
943
1060
 
1061
+ // cli/utils/token-estimate.ts
1062
+ function estimateTokens(text) {
1063
+ return Math.ceil(text.length / 4);
1064
+ }
1065
+ function formatTokenCount(tokens) {
1066
+ if (tokens < 1e3) return String(tokens);
1067
+ if (tokens < 1e4) return `~${(tokens / 1e3).toFixed(1)}k`;
1068
+ return `~${Math.round(tokens / 1e3)}k`;
1069
+ }
1070
+ function tokenLogLine(jobType, identifier, prompt2, systemPrompt) {
1071
+ const promptTokens = estimateTokens(prompt2);
1072
+ const systemTokens = systemPrompt ? estimateTokens(systemPrompt) : 0;
1073
+ const total = promptTokens + systemTokens;
1074
+ const parts = [`[tokens] ${jobType}:${identifier} prompt=${formatTokenCount(promptTokens)}`];
1075
+ if (systemTokens > 0) {
1076
+ parts[0] += ` system=${formatTokenCount(systemTokens)}`;
1077
+ }
1078
+ parts[0] += ` total=${formatTokenCount(total)}`;
1079
+ return parts[0];
1080
+ }
1081
+
944
1082
  // cli/commands/watch.ts
945
1083
  var FEATURES_FILE2 = ".mr-features.md";
946
- function readFeaturesDoc(repoDir) {
947
- const path = resolve2(repoDir, FEATURES_FILE2);
948
- if (!existsSync7(path)) return null;
949
- return readFileSync5(path, "utf-8");
1084
+ var SYSTEM_SECTION_STATUS_UPDATES = `## Status Updates
1085
+
1086
+ As you work, post brief status updates so progress is visible in the UI.
1087
+ Use: mr update <task-id> "your status message here"
1088
+
1089
+ The system automatically posts updates for: agent dispatch and task completion. Do NOT duplicate these \u2014 focus your updates on what you're actually doing:
1090
+ - What you found while exploring (e.g. "Found the auth logic in src/auth.ts, needs refactoring")
1091
+ - What specific changes you're making (e.g. "Adding validation to the signup form component")
1092
+ - Problems you hit and how you solved them (e.g. "Fixed circular dependency between User and Order models")
1093
+ - What files/components you modified (e.g. "Updated api/routes.ts and middleware/auth.ts")
1094
+
1095
+ Be specific about your changes \u2014 don't post vague messages like "working on the task" or "exploring the codebase". Each update should tell the user something concrete about what changed or what you learned.
1096
+
1097
+ Keep messages short (1 sentence). Post 3-5 updates total.`;
1098
+ var SYSTEM_SECTION_SCREENSHOTS = `## Screenshots
1099
+
1100
+ Before you finish, take a screenshot of your work to attach to the task. This helps the reviewer see what changed visually.
1101
+ Use: mr screenshot <task-id> <path-to-image> -m "Description of what the screenshot shows"
1102
+
1103
+ You can take a screenshot on macOS (no file arg needed) or provide a path to an existing image file.
1104
+ When no file is provided, the command uses the browse daemon (headless Chromium) to screenshot the app's project page automatically.
1105
+ You can also specify a custom URL: mr screenshot <task-id> --url "http://localhost:3000/some-page" -m "description"
1106
+ If your changes are visual (UI changes), try to capture the result. If they are purely backend/logic changes, you can skip this step.`;
1107
+ var SYSTEM_SECTION_TEST_PLAN = `## Test Plan
1108
+
1109
+ After pushing your MR/PR, create a structured test plan so the reviewer can run automated browser tests against your changes.
1110
+ Save the test plan as a TaskResource by calling:
1111
+ mr update <task-id> --resource test-plan "Test plan for <task-title>" '<json>'
1112
+
1113
+ Or write it to a file and upload it. The test plan is a JSON array of browse commands:
1114
+
1115
+ \`\`\`json
1116
+ [
1117
+ { "command": "goto", "args": ["/login"], "description": "Navigate to login page" },
1118
+ { "command": "fill", "args": ["input[type=email]", "test@example.com"], "description": "Enter email" },
1119
+ { "command": "fill", "args": ["input[type=password]", "test-password"], "description": "Enter password" },
1120
+ { "command": "click", "args": ["button[type=submit]"], "description": "Submit login" },
1121
+ { "command": "wait", "args": ["2000"], "description": "Wait for redirect" },
1122
+ { "command": "goto", "args": ["/dashboard"], "description": "Navigate to changed page" },
1123
+ { "command": "screenshot", "description": "Capture dashboard" },
1124
+ { "command": "assertVisible", "args": [".dashboard-widget"], "description": "Verify widget renders" },
1125
+ { "command": "assertText", "args": ["h1", "Dashboard"], "description": "Verify page title" }
1126
+ ]
1127
+ \`\`\`
1128
+
1129
+ Supported commands: goto, click, fill, wait, screenshot, assertVisible, assertText, assertUrl.
1130
+ Include auth steps (login/signup URLs) if the feature requires authentication.
1131
+ If your changes don't have a testable UI flow, you can skip this step.`;
1132
+ var SYSTEM_SECTION_NO_MR = `## Tasks That Don't Need an MR/PR
1133
+
1134
+ If the task does not require code changes (e.g. research, documentation uploaded as a resource, configuration via the UI, etc.), you can signal this instead of creating a pull request:
1135
+ mr no-mr <task-id> "Brief description of what was done instead"
1136
+
1137
+ This tells the watch system to skip looking for a PR and records what action was taken. You should still clean up any worktrees and exit normally.`;
1138
+ var SYSTEM_SECTION_FEATURES_WORKFLOW = `## Features & Goals Document Workflow
1139
+
1140
+ After completing your work, check if the project has a .mr-features.md file. If changes are relevant, update it.
1141
+ Write the updated content to a temp file and run: mr features --file /tmp/mr-features-update.md
1142
+ Only update the sections relevant to your changes. Preserve existing content that is still accurate.
1143
+ If the project does not yet have .mr-features.md, create one capturing the current state of features grouped by area.`;
1144
+ var SYSTEM_SECTION_PRD_FORMAT = `### PRD Format Conventions
1145
+
1146
+ Follow these conventions so PRDs are scannable by humans and parseable by agents.
1147
+ All sections are optional \u2014 include only what's relevant for this task type (greenfield, feature, bug fix, refactor). Omit sections that would be boilerplate.
1148
+
1149
+ **TL;DR Block** \u2014 Start the PRD with a \`> \` blockquote summary (2-3 sentences) immediately after the \`# PRD: Title\` heading.
1150
+
1151
+ **Requirement IDs** \u2014 Every requirement gets a unique ID prefix and a single-sentence summary on the first line:
1152
+ \`**F1: Name** \u2014 One-sentence summary.\` followed by optional \`- Detail bullet\` lines.
1153
+ Use \`F\` prefix for functional requirements, \`NF\` for non-functional. Number sequentially within each category.
1154
+
1155
+ **Success Metrics as JSON** \u2014 Use a fenced \`json\` code block containing an array of objects with \`Metric\`, \`Target\`, and \`Type\` fields.
1156
+
1157
+ **Affected Components as JSON** \u2014 Use the same JSON table format for the technical approach section.
1158
+
1159
+ **Implementation Steps as Phased Checklists** \u2014 Use \`### Phase N: Name\` headers with markdown checklists (\`- [ ]\`).
1160
+
1161
+ **Edge Cases as Tagged List** \u2014 Each edge case leads with a bold tag: \`- **Tag** \u2014 Description.\`
1162
+
1163
+ **No Frontmatter** \u2014 Do not include YAML frontmatter. Metadata lives in the database.`;
1164
+ var SYSTEM_SECTION_PRD_OPEN_QUESTIONS = `### Open Questions Format
1165
+
1166
+ The "Open Questions" section of the PRD MUST end with a fenced JSON code block tagged \`open-questions\`.
1167
+
1168
+ Format:
1169
+ \`\`\`open-questions
1170
+ [
1171
+ {
1172
+ "id": "q1",
1173
+ "question": "Which approach should we use for X?",
1174
+ "context": "One sentence explaining why this decision matters.",
1175
+ "options": [
1176
+ "Option A \u2014 brief description",
1177
+ "Option B \u2014 brief description"
1178
+ ]
1179
+ }
1180
+ ]
1181
+ \`\`\`
1182
+
1183
+ Rules:
1184
+ - Each question MUST have 2-4 concrete options.
1185
+ - Options should be actionable choices.
1186
+ - The "context" field should be a single sentence.
1187
+ - Use sequential IDs: q1, q2, q3, etc.
1188
+ - Place the JSON block at the very end of the "Open Questions" section.`;
1189
+ var SYSTEM_SECTIONS = {
1190
+ "status-updates": SYSTEM_SECTION_STATUS_UPDATES,
1191
+ "screenshots": SYSTEM_SECTION_SCREENSHOTS,
1192
+ "test-plan": SYSTEM_SECTION_TEST_PLAN,
1193
+ "no-mr": SYSTEM_SECTION_NO_MR,
1194
+ "features-workflow": SYSTEM_SECTION_FEATURES_WORKFLOW,
1195
+ "prd-format": SYSTEM_SECTION_PRD_FORMAT,
1196
+ "prd-open-questions": SYSTEM_SECTION_PRD_OPEN_QUESTIONS
1197
+ };
1198
+ function composeSystemPrompt(sections) {
1199
+ return sections.map((s) => SYSTEM_SECTIONS[s]).join("\n\n");
950
1200
  }
1201
+ var EXECUTION_SYSTEM_SECTIONS = ["status-updates", "screenshots", "test-plan", "no-mr", "features-workflow"];
1202
+ var PRD_SYSTEM_SECTIONS = ["prd-format", "prd-open-questions"];
951
1203
  var c = {
952
1204
  reset: "\x1B[0m",
953
1205
  bold: "\x1B[1m",
@@ -1047,7 +1299,7 @@ function worktreePath(name) {
1047
1299
  function worktreeNameFromPath(wtPath) {
1048
1300
  return wtPath.replace(/^\.mr-worktrees\//, "");
1049
1301
  }
1050
- function normalizeWhitespace(value) {
1302
+ function normalizeWhitespace2(value) {
1051
1303
  return value.replace(/\s+/g, " ").trim();
1052
1304
  }
1053
1305
  function extractFirstMeaningfulParagraph(markdown) {
@@ -1072,7 +1324,7 @@ function extractFirstMeaningfulParagraph(markdown) {
1072
1324
  if (quoteLines.length > 0) break;
1073
1325
  }
1074
1326
  if (quoteLines.length > 0) {
1075
- const text2 = normalizeWhitespace(quoteLines.join(" "));
1327
+ const text2 = normalizeWhitespace2(quoteLines.join(" "));
1076
1328
  return text2 || null;
1077
1329
  }
1078
1330
  const paragraphLines = [];
@@ -1095,7 +1347,7 @@ function extractFirstMeaningfulParagraph(markdown) {
1095
1347
  paragraphLines.push(line);
1096
1348
  }
1097
1349
  if (paragraphLines.length === 0) return null;
1098
- const text = normalizeWhitespace(paragraphLines.join(" "));
1350
+ const text = normalizeWhitespace2(paragraphLines.join(" "));
1099
1351
  return text || null;
1100
1352
  }
1101
1353
  function truncateText(value, maxLength) {
@@ -1133,25 +1385,6 @@ function buildPrBodyTemplate(task, subtasks, protoRefs = [], feedbackUpdates = [
1133
1385
  "_Replace every placeholder above before creating the PR. Remove bullets or sections that do not apply._"
1134
1386
  ].join("\n");
1135
1387
  }
1136
- function pullLatestMain(repoDir, prefix) {
1137
- return new Promise((resolve7) => {
1138
- exec(
1139
- "git pull origin main --ff-only",
1140
- { cwd: repoDir },
1141
- (err, stdout, stderr) => {
1142
- if (err) {
1143
- logWarn(prefix, `git pull failed (proceeding anyway): ${stderr.trim() || err.message}`);
1144
- } else {
1145
- const msg = stdout.trim();
1146
- if (msg && msg !== "Already up to date.") {
1147
- logInfo(prefix, `pulled latest main: ${paint("gray", msg.split("\n")[0])}`);
1148
- }
1149
- }
1150
- resolve7();
1151
- }
1152
- );
1153
- });
1154
- }
1155
1388
  function buildPlanningPrompt(task, repoDir) {
1156
1389
  const notes = task.notes ? `
1157
1390
 
@@ -1177,17 +1410,109 @@ ${task.notes}` : "";
1177
1410
  }
1178
1411
  function findPrUrl(branchName, repoDir, vcs = "github") {
1179
1412
  const cmd = vcs === "gitlab" ? `glab mr view "${branchName}" --output json 2>/dev/null | jq -r '.web_url // empty'` : `gh pr view "${branchName}" --json url -q .url`;
1180
- return new Promise((resolve7) => {
1413
+ return new Promise((resolve8) => {
1181
1414
  exec(
1182
1415
  cmd,
1183
1416
  { cwd: repoDir },
1184
1417
  (err, stdout) => {
1185
- if (err) resolve7(null);
1186
- else resolve7(stdout.trim() || null);
1418
+ if (err) resolve8(null);
1419
+ else resolve8(stdout.trim() || null);
1187
1420
  }
1188
1421
  );
1189
1422
  });
1190
1423
  }
1424
+ function buildAutomaticPrBody(task, branchName, vcs, subtasks, protoRefs = [], feedbackUpdates = [], existingResources = [], skillRefs = []) {
1425
+ const contextSource = task.prdContent ?? task.notes ?? "";
1426
+ const taskContext = extractFirstMeaningfulParagraph(contextSource);
1427
+ const contextBullets = [
1428
+ `- Resolves MR Manager task ${task.id}.`,
1429
+ `- Task: ${task.title}.`,
1430
+ ...taskContext ? [`- Goal/context: ${truncateText(taskContext, 220)}.`] : [],
1431
+ ...subtasks.map((subtask) => `- Completed subtask: ${subtask.title}.`),
1432
+ ...protoRefs.map((ref) => `- Related prototype: ${ref.prototype.title}${ref.selectedVariants?.length ? ` (variants ${ref.selectedVariants.join(", ")})` : ""}.`),
1433
+ ...feedbackUpdates.slice(0, 3).map((update) => `- Addresses feedback from ${new Date(update.createdAt).toLocaleDateString("en-US")}.`),
1434
+ ...existingResources.slice(0, 3).map((resource) => `- Referenced resource: ${resource.name}.${resource.kind === "link" && resource.url ? ` (${resource.url})` : ""}`),
1435
+ ...skillRefs.slice(0, 3).map((ref) => `- Applied skill guidance: ${ref.skill.name}.`)
1436
+ ];
1437
+ return [
1438
+ "## Summary",
1439
+ `- Auto-created by \`mr watch\` because no existing ${detectPrLabelFromVcs(vcs)} was found for branch \`${branchName}\` after the agent finished.`,
1440
+ `- Captures the implementation for MR Manager task \`${task.id}\` while preserving the task title as the review title.`,
1441
+ "",
1442
+ "## Context",
1443
+ ...contextBullets,
1444
+ "",
1445
+ "## Testing",
1446
+ "- [ ] Automated tests: Not run by `mr watch`; see task updates or follow-up commits for validation details.",
1447
+ "- [ ] Manual verification completed by reviewer."
1448
+ ].join("\n");
1449
+ }
1450
+ function detectPrLabelFromVcs(vcs) {
1451
+ return vcs === "gitlab" ? "MR" : "PR";
1452
+ }
1453
+ function extractPrUrlFromText(value) {
1454
+ const match = value.match(/https?:\/\/(?:github\.com\/[^\s]+\/pull\/\d+|gitlab\.[^\s]+\/merge_requests\/\d+)/);
1455
+ return match ? match[0] : null;
1456
+ }
1457
+ function commandSucceeds(command, cwd) {
1458
+ return new Promise((resolve8) => {
1459
+ exec(command, { cwd }, (err) => resolve8(!err));
1460
+ });
1461
+ }
1462
+ async function createPrInRepo(task, branchName, repoDir, vcs, subtasks, protoRefs = [], feedbackUpdates = [], existingResources = [], skillRefs = []) {
1463
+ const hasLocalBranch = await commandSucceeds(`git show-ref --verify --quiet refs/heads/${JSON.stringify(branchName)}`, repoDir);
1464
+ const hasRemoteBranch = await commandSucceeds(`git ls-remote --exit-code --heads origin ${JSON.stringify(branchName)}`, repoDir);
1465
+ if (!hasLocalBranch && !hasRemoteBranch) {
1466
+ return null;
1467
+ }
1468
+ const bodyPath = resolve2("/tmp", `mr-auto-pr-${randomUUID()}.md`);
1469
+ const body = buildAutomaticPrBody(task, branchName, vcs, subtasks, protoRefs, feedbackUpdates, existingResources, skillRefs);
1470
+ writeFileSync4(bodyPath, `${body}
1471
+ `, "utf-8");
1472
+ const createCommand2 = vcs === "gitlab" ? `glab mr create --source-branch ${JSON.stringify(branchName)} --title ${JSON.stringify(task.title)} --description-file ${JSON.stringify(bodyPath)} --yes` : `gh pr create --head ${JSON.stringify(branchName)} --title ${JSON.stringify(task.title)} --body-file ${JSON.stringify(bodyPath)}`;
1473
+ try {
1474
+ const output = await new Promise((resolve8, reject) => {
1475
+ exec(createCommand2, { cwd: repoDir }, (err, stdout, stderr) => {
1476
+ if (err) {
1477
+ reject(new Error(stderr.trim() || stdout.trim() || err.message));
1478
+ return;
1479
+ }
1480
+ resolve8(`${stdout}
1481
+ ${stderr}`.trim());
1482
+ });
1483
+ });
1484
+ const createdUrl = extractPrUrlFromText(output);
1485
+ return createdUrl ?? await findPrUrl(branchName, repoDir, vcs);
1486
+ } catch {
1487
+ return null;
1488
+ } finally {
1489
+ if (existsSync7(bodyPath)) {
1490
+ unlinkSync(bodyPath);
1491
+ }
1492
+ }
1493
+ }
1494
+ async function createPrAcrossRepos(task, branchName, repoDir, vcs, subtasks, protoRefs = [], feedbackUpdates = [], existingResources = [], skillRefs = []) {
1495
+ if (isGitRepo(repoDir)) {
1496
+ return createPrInRepo(task, branchName, repoDir, vcs, subtasks, protoRefs, feedbackUpdates, existingResources, skillRefs);
1497
+ }
1498
+ const childRepos = findChildGitRepos(repoDir);
1499
+ for (const repo of childRepos) {
1500
+ const childVcs = detectVcs(repo)?.provider ?? vcs;
1501
+ const url = await createPrInRepo(
1502
+ task,
1503
+ branchName,
1504
+ repo,
1505
+ childVcs,
1506
+ subtasks,
1507
+ protoRefs,
1508
+ feedbackUpdates,
1509
+ existingResources,
1510
+ skillRefs
1511
+ );
1512
+ if (url) return url;
1513
+ }
1514
+ return null;
1515
+ }
1191
1516
  function isGitRepo(dir) {
1192
1517
  try {
1193
1518
  return existsSync7(resolve2(dir, ".git"));
@@ -1235,38 +1560,39 @@ async function extractPrUrlFromUpdates(taskId) {
1235
1560
  }
1236
1561
  function checkPrStatus(prUrl, repoDir, vcs = "github") {
1237
1562
  const cmd = vcs === "gitlab" ? `glab mr view "${prUrl}" --output json 2>/dev/null` : `gh pr view "${prUrl}" --json merged,mergeable 2>/dev/null`;
1238
- return new Promise((resolve7) => {
1563
+ return new Promise((resolve8) => {
1239
1564
  exec(cmd, { cwd: repoDir }, (err, stdout) => {
1240
1565
  if (err || !stdout.trim()) {
1241
- resolve7(null);
1566
+ resolve8(null);
1242
1567
  return;
1243
1568
  }
1244
1569
  try {
1245
1570
  const data = JSON.parse(stdout.trim());
1246
1571
  if (vcs === "gitlab") {
1247
- resolve7({
1572
+ resolve8({
1248
1573
  merged: data.state === "merged",
1249
1574
  hasConflicts: data.has_conflicts === true
1250
1575
  });
1251
1576
  } else {
1252
- resolve7({
1577
+ resolve8({
1253
1578
  merged: data.merged === true,
1254
1579
  hasConflicts: data.mergeable === "CONFLICTING"
1255
1580
  });
1256
1581
  }
1257
1582
  } catch {
1258
- resolve7(null);
1583
+ resolve8(null);
1259
1584
  }
1260
1585
  });
1261
1586
  });
1262
1587
  }
1263
- function buildPrototypeSection(protoRefs) {
1588
+ function buildPrototypeSection(protoRefs, workingDir) {
1264
1589
  if (protoRefs.length === 0) return "";
1265
1590
  const sections = [
1266
1591
  ``,
1267
1592
  `## Referenced Prototypes`,
1268
1593
  ``,
1269
1594
  `The following prototype designs have been linked to this task as reference. Use them to guide the implementation.`,
1595
+ `Read the referenced files when you need to see the HTML content.`,
1270
1596
  ``
1271
1597
  ];
1272
1598
  for (const ref of protoRefs) {
@@ -1284,10 +1610,19 @@ function buildPrototypeSection(protoRefs) {
1284
1610
  for (let i = 0; i < selectedFiles.length; i++) {
1285
1611
  const file = selectedFiles[i];
1286
1612
  const variantLabel = selected.length < files.length ? `Variant ${selected[i] + 1} (selected)` : `Variant ${i + 1}`;
1287
- sections.push(`#### ${variantLabel}: ${file.name}`);
1288
- sections.push(`\`\`\`html`);
1289
- sections.push(file.content);
1290
- sections.push(`\`\`\``);
1613
+ const tmpDir = workingDir ?? "/tmp";
1614
+ const safeProtoId = proto.id.slice(0, 8);
1615
+ const tmpPath = resolve2(tmpDir, `.mr-proto-${safeProtoId}-v${selected[i] ?? i}.html`);
1616
+ try {
1617
+ writeFileSync4(tmpPath, file.content, "utf-8");
1618
+ sections.push(`#### ${variantLabel}: ${file.name}`);
1619
+ sections.push(`File: \`${tmpPath}\` \u2014 read this file to see the full HTML content.`);
1620
+ } catch {
1621
+ sections.push(`#### ${variantLabel}: ${file.name}`);
1622
+ sections.push(`\`\`\`html`);
1623
+ sections.push(file.content);
1624
+ sections.push(`\`\`\``);
1625
+ }
1291
1626
  sections.push(``);
1292
1627
  }
1293
1628
  }
@@ -1353,8 +1688,9 @@ function buildFeedbackSection(updates) {
1353
1688
  return lines.join("\n");
1354
1689
  }
1355
1690
  function buildFeaturesSection(repoDir) {
1356
- const content = readFeaturesDoc(repoDir);
1357
- if (!content) {
1691
+ const featuresPath = resolve2(repoDir, FEATURES_FILE2);
1692
+ const exists = existsSync7(featuresPath);
1693
+ if (!exists) {
1358
1694
  return [
1359
1695
  ``,
1360
1696
  `## Features & Goals Document`,
@@ -1374,11 +1710,8 @@ function buildFeaturesSection(repoDir) {
1374
1710
  ``,
1375
1711
  `## Features & Goals Document`,
1376
1712
  ``,
1377
- `The project maintains a features & goals document at \`.mr-features.md\`. Here is its current content:`,
1378
- ``,
1379
- "```markdown",
1380
- content,
1381
- "```",
1713
+ `The project maintains a features & goals document at \`${featuresPath}\`.`,
1714
+ `Read this file if you need to understand existing features or update it after your work.`,
1382
1715
  ``,
1383
1716
  `After completing your work, update this document to reflect any changes. Write the updated content to a temp file and run:`,
1384
1717
  `\`mr features --file /tmp/mr-features-update.md\``,
@@ -1387,8 +1720,7 @@ function buildFeaturesSection(repoDir) {
1387
1720
  ``
1388
1721
  ].join("\n");
1389
1722
  }
1390
- function buildExecutionPrompt(task, repoDir, subtasks, vcs = "github", protoRefs = [], feedbackUpdates = [], existingResources = [], skillRefs = [], executionDir) {
1391
- const sid = shortId(task.id);
1723
+ function buildExecutionPrompt(task, repoDir, subtasks, vcs = "github", protoRefs = [], feedbackUpdates = [], existingResources = [], skillRefs = [], executionDir, startWithoutWorktree = false) {
1392
1724
  const slug = slugify(task.title);
1393
1725
  const owner = ownerPrefix(task);
1394
1726
  const branchName = `${owner}/${slug}`;
@@ -1415,7 +1747,6 @@ ${task.notes}` : "";
1415
1747
  ``
1416
1748
  ].join("\n") : "";
1417
1749
  const hasFeedback = feedbackUpdates.length > 0;
1418
- const feedbackWtPath = hasFeedback ? worktreePath(`${owner}-${slug}-fb`) : wtPath;
1419
1750
  const prBodyTemplate = buildPrBodyTemplate(task, pendingSubtasks, protoRefs, feedbackUpdates, existingResources, skillRefs);
1420
1751
  const prCreateCmd = vcs === "gitlab" ? `glab mr create --title "${task.title}" --description-file ${prBodyPath} --yes` : `gh pr create --title "${task.title}" --body-file ${prBodyPath}`;
1421
1752
  return [
@@ -1427,7 +1758,7 @@ ${task.notes}` : "";
1427
1758
  `ID: ${task.id}${notes}`,
1428
1759
  subtaskSection,
1429
1760
  buildResourcesSection(existingResources),
1430
- buildPrototypeSection(protoRefs),
1761
+ buildPrototypeSection(protoRefs, workingDir),
1431
1762
  buildSkillsSection(skillRefs),
1432
1763
  buildFeedbackSection(feedbackUpdates),
1433
1764
  `## Instructions`,
@@ -1442,9 +1773,16 @@ ${task.notes}` : "";
1442
1773
  ] : hasFeedback ? [
1443
1774
  `2. Set up your working environment:`,
1444
1775
  ` - Fetch the latest from origin: \`git fetch origin\``,
1445
- ` - Check out the existing branch in a worktree: \`git worktree add ${feedbackWtPath} origin/${branchName}\``,
1446
- ` - If the origin branch doesn't exist yet, fall back to: \`git worktree add -b ${branchName} ${feedbackWtPath}\``,
1447
- ` - Work in the worktree directory: ${feedbackWtPath}`
1776
+ ` - Reuse the existing task branch/worktree if it is still present.`,
1777
+ ` - Otherwise check out the existing branch in a worktree: \`git worktree add ${wtPath} origin/${branchName}\``,
1778
+ ` - If the origin branch doesn't exist yet, fall back to: \`git worktree add -b ${branchName} ${wtPath}\``,
1779
+ ` - Work in the worktree directory: ${wtPath}`
1780
+ ] : startWithoutWorktree ? [
1781
+ `2. Start in the linked project directory first:`,
1782
+ ` - Current working directory: ${repoDir}`,
1783
+ ` - This task appears likely to be a no-code workflow (research, documentation, UI configuration, or resource updates), so no worktree has been pre-created.`,
1784
+ ` - If you discover you need to edit tracked files or write code after all, create a worktree before making changes: \`git worktree add -b ${branchName} ${wtPath}\``,
1785
+ ` - If the task spans multiple repos, create matching worktrees only in the repo(s) where edits are actually needed.`
1448
1786
  ] : [
1449
1787
  `2. Set up an isolated working environment:`,
1450
1788
  ` - If ${repoDir} is a git repo, create a worktree: \`git worktree add -b ${branchName} ${wtPath}\``,
@@ -1480,21 +1818,6 @@ ${task.notes}` : "";
1480
1818
  ``,
1481
1819
  `This tells the watch system to skip looking for a ${vcs === "gitlab" ? "MR" : "PR"} and records what action was taken. You should still clean up any worktrees and exit normally.`,
1482
1820
  ``,
1483
- `## Status Updates`,
1484
- ``,
1485
- `As you work, post brief status updates so progress is visible in the UI:`,
1486
- `\`mr update ${task.id} "your status message here"\``,
1487
- ``,
1488
- `The system automatically posts updates for: agent dispatch and task completion. Do NOT duplicate these \u2014 focus your updates on what you're actually doing:`,
1489
- `- What you found while exploring (e.g. "Found the auth logic in src/auth.ts, needs refactoring")`,
1490
- `- What specific changes you're making (e.g. "Adding validation to the signup form component")`,
1491
- `- Problems you hit and how you solved them (e.g. "Fixed circular dependency between User and Order models")`,
1492
- `- What files/components you modified (e.g. "Updated api/routes.ts and middleware/auth.ts")`,
1493
- ``,
1494
- `Be specific about your changes \u2014 don't post vague messages like "working on the task" or "exploring the codebase". Each update should tell the user something concrete about what changed or what you learned.`,
1495
- ``,
1496
- `Keep messages short (1 sentence). Post 3-5 updates total.`,
1497
- ``,
1498
1821
  ...hasFeedback ? [] : [
1499
1822
  `## PR Description Template`,
1500
1823
  ``,
@@ -1506,41 +1829,6 @@ ${task.notes}` : "";
1506
1829
  "```",
1507
1830
  ``
1508
1831
  ],
1509
- `## Screenshots`,
1510
- ``,
1511
- `Before you finish, take a screenshot of your work to attach to the task. This helps the reviewer see what changed visually.`,
1512
- `\`mr screenshot ${task.id} <path-to-image> -m "Description of what the screenshot shows"\``,
1513
- ``,
1514
- `You can take a screenshot on macOS (no file arg needed) or provide a path to an existing image file.`,
1515
- `When no file is provided, the command uses the browse daemon (headless Chromium) to screenshot the app's project page automatically.`,
1516
- `You can also specify a custom URL: \`mr screenshot ${task.id} --url "http://localhost:3000/some-page" -m "description"\``,
1517
- `If your changes are visual (UI changes), try to capture the result. If they are purely backend/logic changes, you can skip this step.`,
1518
- ``,
1519
- `## Test Plan`,
1520
- ``,
1521
- `After pushing your MR/PR, create a structured test plan so the reviewer can run automated browser tests against your changes.`,
1522
- `Save the test plan as a TaskResource by calling:`,
1523
- `\`mr update ${task.id} --resource test-plan "Test plan for ${task.title}" '<json>'\``,
1524
- ``,
1525
- `Or write it to a file and upload it. The test plan is a JSON array of browse commands:`,
1526
- ``,
1527
- "```json",
1528
- `[`,
1529
- ` { "command": "goto", "args": ["/login"], "description": "Navigate to login page" },`,
1530
- ` { "command": "fill", "args": ["input[type=email]", "test@example.com"], "description": "Enter email" },`,
1531
- ` { "command": "fill", "args": ["input[type=password]", "test-password"], "description": "Enter password" },`,
1532
- ` { "command": "click", "args": ["button[type=submit]"], "description": "Submit login" },`,
1533
- ` { "command": "wait", "args": ["2000"], "description": "Wait for redirect" },`,
1534
- ` { "command": "goto", "args": ["/dashboard"], "description": "Navigate to changed page" },`,
1535
- ` { "command": "screenshot", "description": "Capture dashboard" },`,
1536
- ` { "command": "assertVisible", "args": [".dashboard-widget"], "description": "Verify widget renders" },`,
1537
- ` { "command": "assertText", "args": ["h1", "Dashboard"], "description": "Verify page title" }`,
1538
- `]`,
1539
- "```",
1540
- ``,
1541
- `Supported commands: goto, click, fill, wait, screenshot, assertVisible, assertText, assertUrl.`,
1542
- `Include auth steps (login/signup URLs) if the feature requires authentication.`,
1543
- `If your changes don't have a testable UI flow, you can skip this step.`,
1544
1832
  buildFeaturesSection(repoDir),
1545
1833
  `Complete all steps autonomously without asking for confirmation. Exit with code 0 when done.`
1546
1834
  ].join("\n");
@@ -1551,16 +1839,31 @@ function buildPrdPrompt(task, repoDir, existingPrd, feedbackUpdates = []) {
1551
1839
  Task notes:
1552
1840
  ${task.notes}` : "";
1553
1841
  const isRevision = !!(existingPrd && feedbackUpdates.length > 0);
1554
- const feedbackSection = isRevision ? [
1555
- ``,
1556
- `## Existing PRD`,
1557
- ``,
1558
- `The following PRD was previously generated. You must revise it based on the user's feedback below \u2014 do NOT start from scratch.`,
1559
- ``,
1560
- existingPrd,
1561
- ``,
1562
- buildFeedbackSection(feedbackUpdates)
1563
- ].join("\n") : "";
1842
+ let feedbackSection = "";
1843
+ if (isRevision) {
1844
+ const prdTmpPath = resolve2(repoDir, ".mr-existing-prd.md");
1845
+ try {
1846
+ writeFileSync4(prdTmpPath, existingPrd, "utf-8");
1847
+ } catch {
1848
+ }
1849
+ const prdSummaryLines = [];
1850
+ for (const line of (existingPrd ?? "").split("\n")) {
1851
+ const trimmed = line.trim();
1852
+ if (/^#{1,3}\s/.test(trimmed)) prdSummaryLines.push(trimmed);
1853
+ else if (/^\*\*[FN]+\d+:/.test(trimmed)) prdSummaryLines.push(` ${trimmed.split("\u2014")[0].trim()}`);
1854
+ }
1855
+ feedbackSection = [
1856
+ ``,
1857
+ `## Existing PRD`,
1858
+ ``,
1859
+ `A PRD was previously generated. You must revise it based on the user's feedback below \u2014 do NOT start from scratch.`,
1860
+ ``,
1861
+ `**Full PRD file:** \`${prdTmpPath}\` \u2014 read this file for the complete existing PRD.`,
1862
+ ``,
1863
+ ...prdSummaryLines.length > 0 ? [`**PRD structure summary:**`, ...prdSummaryLines, ``] : [],
1864
+ buildFeedbackSection(feedbackUpdates)
1865
+ ].join("\n");
1866
+ }
1564
1867
  const revisionInstructions = isRevision ? [
1565
1868
  `1. Read the existing PRD and user feedback above carefully.`,
1566
1869
  `2. Revise the PRD to address every piece of feedback. Keep sections that are still valid \u2014 only modify what the feedback requires.`,
@@ -1591,77 +1894,16 @@ ${task.notes}` : "";
1591
1894
  ` - Technical approach and affected components`,
1592
1895
  ` - Edge cases`,
1593
1896
  ` - Implementation steps / breakdown`,
1594
- ` - **Open Questions** \u2014 this section MUST use the structured format below`,
1595
- ``,
1596
- `### PRD Format Conventions`,
1897
+ ` - **Open Questions** \u2014 this section MUST use the structured format described in the system prompt`,
1597
1898
  ``,
1598
- `Follow these conventions so PRDs are scannable by humans and parseable by agents.`,
1599
- `All sections are optional \u2014 include only what's relevant for this task type (greenfield, feature, bug fix, refactor). Omit sections that would be boilerplate.`,
1600
- ``,
1601
- `**TL;DR Block** \u2014 Start the PRD with a \`> \` blockquote summary (2-3 sentences) immediately after the \`# PRD: Title\` heading. This gives humans instant orientation and agents a compact context summary.`,
1602
- ``,
1603
- `**Requirement IDs** \u2014 Every requirement gets a unique ID prefix and a single-sentence summary on the first line:`,
1604
- `\`**F1: Name** \u2014 One-sentence summary.\` followed by optional \`- Detail bullet\` lines.`,
1605
- `Use \`F\` prefix for functional requirements, \`NF\` for non-functional. Number sequentially within each category.`,
1606
- `The summary line must be a complete description \u2014 an agent should be able to extract just summary lines to build a work plan.`,
1607
- ...isRevision ? [`When revising, preserve existing requirement IDs. Add new requirements by continuing the numbering sequence \u2014 never restart at F1.`] : [],
1608
- ``,
1609
- `**Success Metrics as JSON** \u2014 Use a fenced \`json\` code block containing an array of objects. The UI auto-renders these as tables.`,
1610
- `Each object should have \`Metric\`, \`Target\`, and \`Type\` fields. Example:`,
1611
- "````json",
1612
- `[`,
1613
- ` { "Metric": "API response time under load", "Target": "< 200ms p95", "Type": "Performance" }`,
1614
- `]`,
1615
- "````",
1616
- ``,
1617
- `**Affected Components as JSON** \u2014 Use the same JSON table format for the technical approach section:`,
1618
- "````json",
1619
- `[`,
1620
- ` { "Component": "path/to/file.ts", "Change": "What changes", "Scope": "~N lines" }`,
1621
- `]`,
1622
- "````",
1623
- ``,
1624
- `**Implementation Steps as Phased Checklists** \u2014 Use \`### Phase N: Name\` headers with markdown checklists (\`- [ ]\`).`,
1625
- `Gives humans a timeline overview at heading level; gives agents discrete work items.`,
1626
- ``,
1627
- `**Edge Cases as Tagged List** \u2014 Each edge case leads with a bold tag: \`- **Tag** \u2014 Description.\``,
1628
- ``,
1629
- `**No Frontmatter** \u2014 Do not include YAML frontmatter. Metadata lives in the database.`,
1630
- ``,
1631
- `### Open Questions Format`,
1632
- ``,
1633
- `The "Open Questions" section of the PRD MUST end with a fenced JSON code block`,
1634
- `tagged \`open-questions\`. This allows the UI to present them as answerable cards.`,
1635
- ``,
1636
- `Format:`,
1637
- "```",
1638
- "```open-questions",
1639
- `[`,
1640
- ` {`,
1641
- ` "id": "q1",`,
1642
- ` "question": "Which approach should we use for X?",`,
1643
- ` "context": "One sentence explaining why this decision matters.",`,
1644
- ` "options": [`,
1645
- ` "Option A \u2014 brief description",`,
1646
- ` "Option B \u2014 brief description",`,
1647
- ` "Option C \u2014 brief description"`,
1648
- ` ]`,
1649
- ` }`,
1650
- `]`,
1651
- "```",
1652
- "```",
1653
- ``,
1654
- `Rules for open questions:`,
1655
- `- Each question MUST have 2-4 concrete options.`,
1656
- `- Options should be actionable choices, not vague ("Yes"/"No" is fine when appropriate).`,
1657
- `- The "context" field should be a single sentence explaining why the decision matters.`,
1658
- `- Use sequential IDs: q1, q2, q3, etc.`,
1659
- `- Place the JSON block at the very end of the "Open Questions" section.`,
1660
- `- You may include a brief prose introduction before the JSON block, but the block itself must be last.`,
1661
1899
  ...isRevision ? [
1662
- `- If the user's feedback answered an open question, incorporate their answer and remove that question.`,
1663
- `- Only include questions that are still genuinely open after considering the feedback.`
1664
- ] : [],
1900
+ `Follow the PRD Format Conventions and Open Questions Format from the system prompt.`,
1901
+ `When revising, preserve existing requirement IDs. Add new requirements by continuing the numbering sequence \u2014 never restart at F1.`,
1902
+ `If the user's feedback answered an open question, incorporate their answer and remove that question.`,
1903
+ `Only include questions that are still genuinely open after considering the feedback.`
1904
+ ] : [
1905
+ `Follow the PRD Format Conventions and Open Questions Format from the system prompt.`
1906
+ ],
1665
1907
  `${nextStep(4)}. Save the PRD as a Markdown file in the working directory:`,
1666
1908
  ` - File name: \`prd.md\``,
1667
1909
  ` - Write the full PRD content to this file.`,
@@ -1818,13 +2060,23 @@ function buildRefinementPrompt(proto, parentFiles, repoDir) {
1818
2060
  );
1819
2061
  }
1820
2062
  const variantList = Array.from({ length: proto.variantCount }, (_, i) => `prototype-${i + 1}.html`);
1821
- const existingVariants = parentFiles.map((f, i) => [
1822
- `### Previous Variant ${i + 1} (${f.name})`,
1823
- `\`\`\`html`,
1824
- f.content,
1825
- `\`\`\``,
1826
- ``
1827
- ].join("\n")).join("\n");
2063
+ const existingVariantLines = [];
2064
+ for (let i = 0; i < parentFiles.length; i++) {
2065
+ const f = parentFiles[i];
2066
+ const tmpPath = resolve2(repoDir, `.mr-parent-variant-${i + 1}.html`);
2067
+ try {
2068
+ writeFileSync4(tmpPath, f.content, "utf-8");
2069
+ existingVariantLines.push(`### Previous Variant ${i + 1} (${f.name})`);
2070
+ existingVariantLines.push(`File: \`${tmpPath}\` \u2014 read this file to see the full HTML content.`);
2071
+ } catch {
2072
+ existingVariantLines.push(`### Previous Variant ${i + 1} (${f.name})`);
2073
+ existingVariantLines.push(`\`\`\`html`);
2074
+ existingVariantLines.push(f.content);
2075
+ existingVariantLines.push(`\`\`\``);
2076
+ }
2077
+ existingVariantLines.push(``);
2078
+ }
2079
+ const existingVariants = existingVariantLines.join("\n");
1828
2080
  return [
1829
2081
  `You are a UI designer and frontend engineer. Your job is to REFINE an existing prototype based on user feedback.`,
1830
2082
  ``,
@@ -1941,7 +2193,7 @@ function buildIdeaPrompt(idea, repoDir) {
1941
2193
  `- Do NOT exit until both files have been written and verified`
1942
2194
  ].join("\n");
1943
2195
  }
1944
- function buildAgentArgs(agent, prompt2, mode, sessionId, name) {
2196
+ function buildAgentArgs(agent, prompt2, mode, sessionId, name, resumeSession = false, systemPrompt, maxTurns) {
1945
2197
  if (agent === "codex") {
1946
2198
  const args = [];
1947
2199
  if (mode === "execute") {
@@ -1951,26 +2203,41 @@ function buildAgentArgs(agent, prompt2, mode, sessionId, name) {
1951
2203
  if (mode === "execute") {
1952
2204
  args.push("-s", "danger-full-access");
1953
2205
  }
1954
- args.push(prompt2);
2206
+ const fullPrompt = systemPrompt ? `${prompt2}
2207
+
2208
+ ${systemPrompt}` : prompt2;
2209
+ args.push(fullPrompt);
1955
2210
  return { bin: "codex", args };
1956
2211
  }
1957
2212
  if (agent === "gemini") {
1958
- const args = ["-p", prompt2];
2213
+ const fullPrompt = systemPrompt ? `${prompt2}
2214
+
2215
+ ${systemPrompt}` : prompt2;
2216
+ const args = ["-p", fullPrompt];
1959
2217
  if (mode === "execute") {
1960
2218
  args.push("--yolo");
1961
2219
  }
1962
2220
  return { bin: "gemini", args };
1963
2221
  }
1964
- const sessionArgs = sessionId ? ["--session-id", sessionId] : [];
2222
+ const sessionArgs = sessionId ? resumeSession ? ["--resume", sessionId] : ["--session-id", sessionId] : [];
1965
2223
  const nameArgs = name ? ["--name", name] : [];
2224
+ const systemArgs = systemPrompt ? ["--append-system-prompt", systemPrompt] : [];
2225
+ const turnsArgs = maxTurns ? ["--max-turns", String(maxTurns)] : [];
1966
2226
  if (mode === "plan") {
1967
- return { bin: "claude", args: [...sessionArgs, ...nameArgs, "--permission-mode", "plan", "-p", prompt2] };
2227
+ return { bin: "claude", args: [...sessionArgs, ...nameArgs, ...systemArgs, ...turnsArgs, "--permission-mode", "plan", "-p", prompt2] };
1968
2228
  }
1969
- return { bin: "claude", args: [...sessionArgs, ...nameArgs, "-p", "--dangerously-skip-permissions", prompt2] };
2229
+ return { bin: "claude", args: [...sessionArgs, ...nameArgs, ...systemArgs, ...turnsArgs, "-p", "--dangerously-skip-permissions", prompt2] };
2230
+ }
2231
+ function commandExists(cmd) {
2232
+ return new Promise((resolve8) => {
2233
+ exec(`command -v ${cmd}`, (err) => resolve8(!err));
2234
+ });
1970
2235
  }
1971
2236
  function runPlanningPhase(task, repoDir, agent) {
1972
2237
  return new Promise((res, reject) => {
1973
- const { bin, args } = buildAgentArgs(agent, buildPlanningPrompt(task, repoDir), "plan", void 0, task.title);
2238
+ const planPrompt = buildPlanningPrompt(task, repoDir);
2239
+ console.log(`${timestamp()} ${taskTag(shortId(task.id))} ${paint("dim", tokenLogLine("plan", shortId(task.id), planPrompt))}`);
2240
+ const { bin, args } = buildAgentArgs(agent, planPrompt, "plan", void 0, task.title);
1974
2241
  const child = spawn4(bin, args, { cwd: repoDir, stdio: ["ignore", "pipe", "pipe"] });
1975
2242
  child.on("error", (err) => {
1976
2243
  reject(new Error(`Failed to spawn ${agent}: ${err.message}`));
@@ -2003,25 +2270,28 @@ ${output.trim()}`));
2003
2270
  });
2004
2271
  }
2005
2272
  function askYesNo(question) {
2006
- return new Promise((resolve7) => {
2273
+ return new Promise((resolve8) => {
2007
2274
  const rl = readline.createInterface({
2008
2275
  input: process.stdin,
2009
2276
  output: process.stdout
2010
2277
  });
2011
2278
  rl.question(question, (answer) => {
2012
2279
  rl.close();
2013
- resolve7(answer.trim().toLowerCase() === "y" || answer.trim().toLowerCase() === "yes");
2280
+ resolve8(answer.trim().toLowerCase() === "y" || answer.trim().toLowerCase() === "yes");
2014
2281
  });
2015
2282
  });
2016
2283
  }
2017
- function spawnAgent(agent, repoDir, prompt2, prefix, onActivity, sessionId, name) {
2018
- const { bin, args } = buildAgentArgs(agent, prompt2, "execute", sessionId, name);
2284
+ function spawnAgent(agent, repoDir, prompt2, prefix, onActivity, sessionId, name, resumeSession = false, onSpawnError, systemPrompt, maxTurns) {
2285
+ const jobLabel = name ?? "unknown";
2286
+ console.log(`${timestamp()} ${prefix} ${paint("dim", tokenLogLine("agent", jobLabel, prompt2, systemPrompt))}`);
2287
+ const { bin, args } = buildAgentArgs(agent, prompt2, "execute", sessionId, name, resumeSession, systemPrompt, maxTurns);
2019
2288
  const child = spawn4(bin, args, { cwd: repoDir, stdio: ["ignore", "pipe", "pipe"] });
2020
2289
  child.on("error", (err) => {
2021
2290
  logError(prefix, `Failed to spawn ${agent}: ${err.message}`);
2022
2291
  if (err.code === "ENOENT") {
2023
2292
  logError(prefix, `Check that "${bin}" is on PATH and "${repoDir}" exists`);
2024
2293
  }
2294
+ onSpawnError?.(err);
2025
2295
  });
2026
2296
  if (agent === "codex") {
2027
2297
  child.stdout?.on("data", () => onActivity?.());
@@ -2061,6 +2331,7 @@ var watchCommand = new Command8("watch").description(
2061
2331
  let pollRunning = false;
2062
2332
  const approvalQueue = [];
2063
2333
  let approvalRunning = false;
2334
+ const agentAvailability = /* @__PURE__ */ new Map();
2064
2335
  const flags = [
2065
2336
  `interval=${paint("cyan", opts.interval + "s")}`,
2066
2337
  `root=${paint("cyan", rootDir)}`,
@@ -2083,6 +2354,22 @@ var watchCommand = new Command8("watch").description(
2083
2354
  console.log(banner);
2084
2355
  console.log(` ${flags}
2085
2356
  `);
2357
+ async function isAgentAvailable(candidate) {
2358
+ const cached = agentAvailability.get(candidate);
2359
+ if (cached !== void 0) {
2360
+ return cached;
2361
+ }
2362
+ const available = await commandExists(candidate);
2363
+ agentAvailability.set(candidate, available);
2364
+ return available;
2365
+ }
2366
+ async function resolveAgentChain(preferred) {
2367
+ const availability = {};
2368
+ for (const candidate of ["claude", "codex", "gemini"]) {
2369
+ availability[candidate] = await isAgentAvailable(candidate);
2370
+ }
2371
+ return getAvailableAgentFallbackChain(preferred, availability);
2372
+ }
2086
2373
  async function moveTaskToError(task, prefix, reason) {
2087
2374
  try {
2088
2375
  await api.patch(`/api/tasks/${task.id}`, { status: "error" });
@@ -2104,7 +2391,6 @@ var watchCommand = new Command8("watch").description(
2104
2391
  const vcs = detectVcs(repoDir)?.provider ?? "github";
2105
2392
  logDispatch(prefix, `"${paint("bold", task.title)}" ${paint("gray", repoDir)} ${paint("dim", `[${vcs}]`)}`);
2106
2393
  await postTaskUpdate(task.id, `Agent dispatched \u2014 starting work on "${task.title}"`, "system");
2107
- await pullLatestMain(repoDir, prefix);
2108
2394
  let subtasks = [];
2109
2395
  try {
2110
2396
  subtasks = await api.get(`/api/tasks/${task.id}/subtasks`);
@@ -2149,20 +2435,26 @@ var watchCommand = new Command8("watch").description(
2149
2435
  }
2150
2436
  const hasFeedback = feedbackUpdates.length > 0;
2151
2437
  const wtName = `${owner}-${slug}`;
2152
- const desiredWorktreePath = hasFeedback ? worktreePath(`${wtName}-fb`) : worktreePath(wtName);
2438
+ const desiredWorktreePath = worktreePath(wtName);
2439
+ const startWithoutWorktree = !hasFeedback && taskLikelyDoesNotNeedCodeChanges(task);
2153
2440
  let executionDir = repoDir;
2154
2441
  let cleanupWorktreePath;
2155
- if (isGitRepo(repoDir)) {
2156
- executionDir = createWorktree(
2442
+ if (startWithoutWorktree) {
2443
+ logInfo(prefix, `Skipping pre-created worktree; task looks like a no-code workflow`);
2444
+ } else if (isGitRepo(repoDir)) {
2445
+ const worktree = createWorktree(
2157
2446
  repoDir,
2158
2447
  branchName,
2159
2448
  worktreeNameFromPath(desiredWorktreePath)
2160
2449
  );
2161
- cleanupWorktreePath = executionDir;
2162
- logInfo(prefix, `Prepared worktree ${paint("cyan", executionDir)}`);
2450
+ executionDir = worktree.path;
2451
+ cleanupWorktreePath = worktree.created ? executionDir : void 0;
2452
+ logInfo(
2453
+ prefix,
2454
+ worktree.reusedBranchWorktree ? `Reusing existing worktree ${paint("cyan", executionDir)} for branch ${paint("dim", branchName)}` : `Prepared worktree ${paint("cyan", executionDir)}`
2455
+ );
2163
2456
  }
2164
- const prompt2 = buildExecutionPrompt(task, repoDir, subtasks, vcs, protoRefs, feedbackUpdates, existingResources, skillRefs, executionDir);
2165
- const sessionId = agent === "claude" ? randomUUID() : void 0;
2457
+ const prompt2 = buildExecutionPrompt(task, repoDir, subtasks, vcs, protoRefs, feedbackUpdates, existingResources, skillRefs, executionDir, startWithoutWorktree);
2166
2458
  const activeEntry = {
2167
2459
  process: void 0,
2168
2460
  title: task.title,
@@ -2175,93 +2467,181 @@ var watchCommand = new Command8("watch").description(
2175
2467
  const touchActivity = () => {
2176
2468
  activeEntry.lastActivityAt = Date.now();
2177
2469
  };
2178
- const child = spawnAgent(agent, executionDir, prompt2, prefix, touchActivity, sessionId, task.title);
2179
- activeEntry.process = child;
2180
- if (sessionId) {
2181
- api.patch(`/api/tasks/${task.id}`, { claudeSessionId: sessionId }).catch(() => {
2182
- });
2183
- logInfo(prefix, `Claude session: ${paint("dim", sessionId)}`);
2470
+ const attemptOrder = await resolveAgentChain(agent);
2471
+ if (attemptOrder.length === 0) {
2472
+ logError(prefix, `No available agents found for fallback chain starting at ${agent}`);
2473
+ await moveTaskToError(task, prefix, `No available agent found for fallback chain starting at ${agent}`);
2474
+ if (activeEntry.cleanupRepoDir && activeEntry.cleanupWorktreePath) {
2475
+ removeWorktree(activeEntry.cleanupRepoDir, activeEntry.cleanupWorktreePath);
2476
+ }
2477
+ queued.delete(task.id);
2478
+ return;
2184
2479
  }
2185
- active.set(task.id, activeEntry);
2186
- child.on("exit", async (code) => {
2187
- active.delete(task.id);
2188
- finishing.add(task.id);
2189
- try {
2190
- if (code === 0) {
2191
- try {
2192
- const researchPath = resolve2(executionDir, "research.md");
2193
- if (existsSync7(researchPath)) {
2194
- try {
2195
- const researchContent = readFileSync5(researchPath, "utf-8");
2196
- const existingResearch = existingResources.find((r) => r.type === "research");
2197
- if (existingResearch) {
2198
- await api.patch(`/api/tasks/${task.id}/resources/${existingResearch.id}`, {
2199
- content: researchContent
2200
- });
2201
- logSuccess(prefix, `Updated existing research resource`);
2202
- } else {
2203
- await api.post(`/api/tasks/${task.id}/resources`, {
2204
- type: "research",
2205
- title: `Research \u2014 ${task.title}`,
2206
- content: researchContent
2207
- });
2208
- logSuccess(prefix, `Uploaded research.md as task resource`);
2480
+ let attemptIndex = 0;
2481
+ const launchAttempt = async (attemptAgent) => {
2482
+ let spawnFailureReason = null;
2483
+ const shouldResumeClaudeSession = attemptAgent === "claude" && hasFeedback && !!task.claudeSessionId;
2484
+ const sessionId = attemptAgent === "claude" ? task.claudeSessionId ?? randomUUID() : void 0;
2485
+ const executionSystemPrompt = composeSystemPrompt(EXECUTION_SYSTEM_SECTIONS);
2486
+ const child = spawnAgent(
2487
+ attemptAgent,
2488
+ executionDir,
2489
+ prompt2,
2490
+ prefix,
2491
+ touchActivity,
2492
+ sessionId,
2493
+ task.title,
2494
+ shouldResumeClaudeSession,
2495
+ (err) => {
2496
+ spawnFailureReason = err.message;
2497
+ },
2498
+ executionSystemPrompt
2499
+ );
2500
+ activeEntry.process = child;
2501
+ activeEntry.currentAgent = attemptAgent;
2502
+ active.set(task.id, activeEntry);
2503
+ if (attemptAgent === "claude" && sessionId) {
2504
+ api.patch(`/api/tasks/${task.id}`, { claudeSessionId: sessionId }).catch(() => {
2505
+ });
2506
+ logInfo(
2507
+ prefix,
2508
+ shouldResumeClaudeSession ? `Resuming Claude session: ${paint("dim", sessionId)}` : `Claude session: ${paint("dim", sessionId)}`
2509
+ );
2510
+ } else {
2511
+ api.patch(`/api/tasks/${task.id}`, { claudeSessionId: null }).catch(() => {
2512
+ });
2513
+ }
2514
+ child.on("exit", async (code) => {
2515
+ if (active.get(task.id)?.process === child) {
2516
+ active.delete(task.id);
2517
+ }
2518
+ const failedAttempt = code !== 0 || spawnFailureReason !== null;
2519
+ if (failedAttempt && !activeEntry.terminatedForError) {
2520
+ const nextAgent = attemptOrder[attemptIndex + 1];
2521
+ if (nextAgent) {
2522
+ const failureDetail = spawnFailureReason ?? `exit code ${code}`;
2523
+ logWarn(prefix, `${attemptAgent} failed (${failureDetail}) \u2014 retrying with ${nextAgent}`);
2524
+ await postTaskUpdate(
2525
+ task.id,
2526
+ `${attemptAgent} failed (${failureDetail}) \u2014 retrying with ${nextAgent}`,
2527
+ "system"
2528
+ );
2529
+ attemptIndex += 1;
2530
+ await launchAttempt(nextAgent);
2531
+ return;
2532
+ }
2533
+ }
2534
+ finishing.add(task.id);
2535
+ try {
2536
+ if (code === 0) {
2537
+ try {
2538
+ const researchPath = resolve2(executionDir, "research.md");
2539
+ if (existsSync7(researchPath)) {
2540
+ try {
2541
+ const researchContent = readFileSync5(researchPath, "utf-8");
2542
+ const existingResearch = existingResources.find((r) => r.type === "research");
2543
+ if (existingResearch) {
2544
+ await api.patch(`/api/tasks/${task.id}/resources/${existingResearch.id}`, {
2545
+ content: researchContent
2546
+ });
2547
+ logSuccess(prefix, `Updated existing research resource`);
2548
+ } else {
2549
+ await api.post(`/api/tasks/${task.id}/resources`, {
2550
+ type: "research",
2551
+ title: `Research \u2014 ${task.title}`,
2552
+ content: researchContent
2553
+ });
2554
+ logSuccess(prefix, `Uploaded research.md as task resource`);
2555
+ }
2556
+ unlinkSync(researchPath);
2557
+ } catch (err) {
2558
+ logWarn(prefix, `Failed to upload research resource: ${err.message}`);
2209
2559
  }
2210
- unlinkSync(researchPath);
2211
- } catch (err) {
2212
- logWarn(prefix, `Failed to upload research resource: ${err.message}`);
2213
2560
  }
2214
- }
2215
- const noMrPath = resolve2(executionDir, ".mr-no-mr");
2216
- const noMrRequested = existsSync7(noMrPath);
2217
- let noMrDescription;
2218
- if (noMrRequested) {
2219
- noMrDescription = readFileSync5(noMrPath, "utf-8").trim();
2220
- unlinkSync(noMrPath);
2221
- logSuccess(prefix, `No ${vcs === "gitlab" ? "MR" : "PR"} needed \u2014 ${noMrDescription}`);
2222
- }
2223
- const prLabel = vcs === "gitlab" ? "MR" : "PR";
2224
- let prUrl = null;
2225
- if (!noMrRequested) {
2226
- prUrl = await findPrUrlAcrossRepos(branchName, repoDir, vcs);
2227
- if (!prUrl) {
2228
- prUrl = await findPrUrlAcrossRepos(legacyBranchName, repoDir, vcs);
2561
+ const noMrPath = resolve2(executionDir, ".mr-no-mr");
2562
+ const noMrRequested = existsSync7(noMrPath);
2563
+ let noMrDescription;
2564
+ if (noMrRequested) {
2565
+ noMrDescription = readFileSync5(noMrPath, "utf-8").trim();
2566
+ unlinkSync(noMrPath);
2567
+ logSuccess(prefix, `No ${vcs === "gitlab" ? "MR" : "PR"} needed \u2014 ${noMrDescription}`);
2229
2568
  }
2230
- if (!prUrl) {
2231
- prUrl = await extractPrUrlFromUpdates(task.id);
2569
+ const prLabel = vcs === "gitlab" ? "MR" : "PR";
2570
+ let prUrl = null;
2571
+ if (!noMrRequested) {
2572
+ prUrl = await findPrUrlAcrossRepos(branchName, repoDir, vcs);
2573
+ if (!prUrl) {
2574
+ prUrl = await findPrUrlAcrossRepos(legacyBranchName, repoDir, vcs);
2575
+ }
2576
+ if (!prUrl) {
2577
+ prUrl = await extractPrUrlFromUpdates(task.id);
2578
+ if (prUrl) {
2579
+ logInfo(prefix, `Found ${prLabel} URL from agent updates: ${paint("cyan", prUrl)}`);
2580
+ }
2581
+ }
2582
+ if (!prUrl) {
2583
+ prUrl = await createPrAcrossRepos(
2584
+ task,
2585
+ branchName,
2586
+ repoDir,
2587
+ vcs,
2588
+ subtasks,
2589
+ protoRefs,
2590
+ feedbackUpdates,
2591
+ existingResources,
2592
+ skillRefs
2593
+ );
2594
+ if (!prUrl) {
2595
+ prUrl = await createPrAcrossRepos(
2596
+ task,
2597
+ legacyBranchName,
2598
+ repoDir,
2599
+ vcs,
2600
+ subtasks,
2601
+ protoRefs,
2602
+ feedbackUpdates,
2603
+ existingResources,
2604
+ skillRefs
2605
+ );
2606
+ }
2607
+ if (prUrl) {
2608
+ logInfo(prefix, `Created missing ${prLabel} for branch ${paint("cyan", branchName)}`);
2609
+ await postTaskUpdate(task.id, `Watch created the missing ${prLabel} for branch ${branchName}`, "system");
2610
+ }
2611
+ }
2232
2612
  if (prUrl) {
2233
- logInfo(prefix, `Found ${prLabel} URL from agent updates: ${paint("cyan", prUrl)}`);
2613
+ logSuccess(prefix, `${prLabel} ready: ${paint("cyan", prUrl)}`);
2614
+ } else {
2615
+ logWarn(prefix, `No ${prLabel} found for branch ${paint("cyan", branchName)}`);
2616
+ await postTaskUpdate(task.id, `Agent finished \u2014 no ${prLabel} found for branch ${branchName}`, "system");
2234
2617
  }
2235
2618
  }
2236
- if (prUrl) {
2237
- logSuccess(prefix, `${prLabel} ready: ${paint("cyan", prUrl)}`);
2238
- } else {
2239
- logWarn(prefix, `No ${prLabel} found for branch ${paint("cyan", branchName)}`);
2240
- await postTaskUpdate(task.id, `Agent finished \u2014 no ${prLabel} found for branch ${branchName}`, "system");
2241
- }
2619
+ await api.patch(`/api/tasks/${task.id}`, {
2620
+ status: "review",
2621
+ claudeSessionId: activeEntry.currentAgent === "claude" ? void 0 : null,
2622
+ ...prUrl ? { link: prUrl } : {}
2623
+ });
2624
+ logSuccess(prefix, `"${paint("bold", task.title)}" marked ready for review`);
2625
+ await postTaskUpdate(task.id, noMrRequested ? `Task marked ready for review \u2014 no ${prLabel} needed: ${noMrDescription}` : "Task marked ready for review", "system");
2626
+ } catch (err) {
2627
+ logError(prefix, `Failed to update task: ${err.message}`);
2242
2628
  }
2243
- await api.patch(`/api/tasks/${task.id}`, {
2244
- status: "review",
2245
- ...prUrl ? { link: prUrl } : {}
2246
- });
2247
- logSuccess(prefix, `"${paint("bold", task.title)}" marked ready for review`);
2248
- await postTaskUpdate(task.id, noMrRequested ? `Task marked ready for review \u2014 no ${prLabel} needed: ${noMrDescription}` : "Task marked ready for review", "system");
2249
- } catch (err) {
2250
- logError(prefix, `Failed to update task: ${err.message}`);
2629
+ } else if (!activeEntry.terminatedForError) {
2630
+ const failureDetail = spawnFailureReason ?? `exit code ${code}`;
2631
+ const reason = `${attemptAgent} failed (${failureDetail}) \u2014 task moved to error`;
2632
+ logError(prefix, `"${paint("bold", task.title)}" failed (${failureDetail}), moving task to error`);
2633
+ await moveTaskToError(task, prefix, reason);
2251
2634
  }
2252
- } else if (!activeEntry.terminatedForError) {
2253
- const reason = `Agent failed with exit code ${code} \u2014 task moved to error`;
2254
- logError(prefix, `"${paint("bold", task.title)}" failed (exit ${code}), moving task to error`);
2255
- await moveTaskToError(task, prefix, reason);
2256
- }
2257
- } finally {
2258
- if (activeEntry.cleanupRepoDir && activeEntry.cleanupWorktreePath) {
2259
- removeWorktree(activeEntry.cleanupRepoDir, activeEntry.cleanupWorktreePath);
2635
+ } finally {
2636
+ if (activeEntry.cleanupRepoDir && activeEntry.cleanupWorktreePath) {
2637
+ removeWorktree(activeEntry.cleanupRepoDir, activeEntry.cleanupWorktreePath);
2638
+ }
2639
+ queued.delete(task.id);
2640
+ finishing.delete(task.id);
2260
2641
  }
2261
- queued.delete(task.id);
2262
- finishing.delete(task.id);
2263
- }
2264
- });
2642
+ });
2643
+ };
2644
+ await launchAttempt(attemptOrder[attemptIndex]);
2265
2645
  }
2266
2646
  async function dispatchPlanModeTask(task, repoDir) {
2267
2647
  const sid = shortId(task.id);
@@ -2292,65 +2672,122 @@ var watchCommand = new Command8("watch").description(
2292
2672
  "system"
2293
2673
  );
2294
2674
  const prompt2 = buildPrdPrompt(task, repoDir, existingPlanResource?.content, feedbackUpdates);
2295
- const child = spawnAgent(agent, repoDir, prompt2, prefix, void 0, void 0, task.title);
2296
- active.set(task.id, { process: child, title: task.title, repoDir, startedAt: Date.now() });
2297
- child.on("exit", async (code) => {
2298
- active.delete(task.id);
2299
- finishing.add(task.id);
2300
- try {
2301
- if (code === 0) {
2302
- try {
2303
- const prdPath = resolve2(repoDir, "prd.md");
2304
- let prdContent;
2675
+ const attemptOrder = await resolveAgentChain(agent);
2676
+ if (attemptOrder.length === 0) {
2677
+ logError(prefix, `No available agents found for fallback chain starting at ${agent}`);
2678
+ await api.patch(`/api/tasks/${task.id}`, { status: "error" }).catch((err) => {
2679
+ logError(prefix, `Failed to mark task as error: ${err.message}`);
2680
+ });
2681
+ await postTaskUpdate(task.id, `PRD generation could not start \u2014 no available agent found for fallback chain starting at ${agent}`, "system");
2682
+ queued.delete(task.id);
2683
+ return;
2684
+ }
2685
+ const activeEntry = {
2686
+ process: void 0,
2687
+ title: task.title,
2688
+ repoDir,
2689
+ startedAt: Date.now(),
2690
+ lastActivityAt: Date.now()
2691
+ };
2692
+ let attemptIndex = 0;
2693
+ const launchAttempt = async (attemptAgent) => {
2694
+ let spawnFailureReason = null;
2695
+ const prdSystemPrompt = composeSystemPrompt(PRD_SYSTEM_SECTIONS);
2696
+ const child = spawnAgent(
2697
+ attemptAgent,
2698
+ repoDir,
2699
+ prompt2,
2700
+ prefix,
2701
+ void 0,
2702
+ void 0,
2703
+ task.title,
2704
+ false,
2705
+ (err) => {
2706
+ spawnFailureReason = err.message;
2707
+ },
2708
+ prdSystemPrompt
2709
+ );
2710
+ activeEntry.process = child;
2711
+ activeEntry.currentAgent = attemptAgent;
2712
+ active.set(task.id, activeEntry);
2713
+ child.on("exit", async (code) => {
2714
+ if (active.get(task.id)?.process === child) {
2715
+ active.delete(task.id);
2716
+ }
2717
+ const failedAttempt = code !== 0 || spawnFailureReason !== null;
2718
+ if (failedAttempt) {
2719
+ const nextAgent = attemptOrder[attemptIndex + 1];
2720
+ if (nextAgent) {
2721
+ const failureDetail = spawnFailureReason ?? `exit code ${code}`;
2722
+ logWarn(prefix, `${attemptAgent} failed (${failureDetail}) \u2014 retrying PRD generation with ${nextAgent}`);
2723
+ await postTaskUpdate(
2724
+ task.id,
2725
+ `${attemptAgent} failed (${failureDetail}) \u2014 retrying PRD generation with ${nextAgent}`,
2726
+ "system"
2727
+ );
2728
+ attemptIndex += 1;
2729
+ await launchAttempt(nextAgent);
2730
+ return;
2731
+ }
2732
+ }
2733
+ finishing.add(task.id);
2734
+ try {
2735
+ if (code === 0) {
2305
2736
  try {
2306
- prdContent = readFileSync5(prdPath, "utf-8");
2307
- logInfo(prefix, `Read PRD from ${paint("cyan", "prd.md")} (${prdContent.length} chars)`);
2308
- unlinkSync(prdPath);
2309
- } catch {
2310
- logWarn(prefix, `No prd.md file found in ${repoDir} \u2014 PRD may have been posted inline`);
2311
- }
2312
- if (prdContent) {
2737
+ const prdPath = resolve2(repoDir, "prd.md");
2738
+ let prdContent;
2313
2739
  try {
2314
- if (existingPlanResource) {
2315
- await api.patch(`/api/tasks/${task.id}/resources/${existingPlanResource.id}`, {
2316
- content: prdContent
2317
- });
2318
- logSuccess(prefix, `Updated existing PRD resource`);
2319
- } else {
2320
- await api.post(`/api/tasks/${task.id}/resources`, {
2321
- type: "plan",
2322
- title: `PRD \u2014 ${task.title}`,
2323
- content: prdContent
2324
- });
2325
- logSuccess(prefix, `Uploaded PRD as task resource`);
2740
+ prdContent = readFileSync5(prdPath, "utf-8");
2741
+ logInfo(prefix, `Read PRD from ${paint("cyan", "prd.md")} (${prdContent.length} chars)`);
2742
+ unlinkSync(prdPath);
2743
+ } catch {
2744
+ logWarn(prefix, `No prd.md file found in ${repoDir} \u2014 PRD may have been posted inline`);
2745
+ }
2746
+ if (prdContent) {
2747
+ try {
2748
+ if (existingPlanResource) {
2749
+ await api.patch(`/api/tasks/${task.id}/resources/${existingPlanResource.id}`, {
2750
+ content: prdContent
2751
+ });
2752
+ logSuccess(prefix, `Updated existing PRD resource`);
2753
+ } else {
2754
+ await api.post(`/api/tasks/${task.id}/resources`, {
2755
+ type: "plan",
2756
+ title: `PRD \u2014 ${task.title}`,
2757
+ content: prdContent
2758
+ });
2759
+ logSuccess(prefix, `Uploaded PRD as task resource`);
2760
+ }
2761
+ } catch (err) {
2762
+ logWarn(prefix, `Failed to upload PRD resource: ${err.message}`);
2326
2763
  }
2327
- } catch (err) {
2328
- logWarn(prefix, `Failed to upload PRD resource: ${err.message}`);
2329
2764
  }
2765
+ await api.patch(`/api/tasks/${task.id}`, {
2766
+ status: "review",
2767
+ ...prdContent ? { prdContent } : {}
2768
+ });
2769
+ logSuccess(prefix, `"${paint("bold", task.title)}" PRD generated and marked ready for review`);
2770
+ await postTaskUpdate(task.id, "PRD generated \u2014 ready for review", "system");
2771
+ } catch (err) {
2772
+ logError(prefix, `Failed to update task: ${err.message}`);
2330
2773
  }
2331
- await api.patch(`/api/tasks/${task.id}`, {
2332
- status: "review",
2333
- ...prdContent ? { prdContent } : {}
2334
- });
2335
- logSuccess(prefix, `"${paint("bold", task.title)}" PRD generated and marked ready for review`);
2336
- await postTaskUpdate(task.id, "PRD generated \u2014 ready for review", "system");
2337
- } catch (err) {
2338
- logError(prefix, `Failed to update task: ${err.message}`);
2339
- }
2340
- } else {
2341
- logError(prefix, `"${paint("bold", task.title)}" PRD generation failed (exit ${code}), marked as error`);
2342
- try {
2343
- await api.patch(`/api/tasks/${task.id}`, { status: "error" });
2344
- } catch (err) {
2345
- logError(prefix, `Failed to mark task as error: ${err.message}`);
2774
+ } else {
2775
+ const failureDetail = spawnFailureReason ?? `exit code ${code}`;
2776
+ logError(prefix, `"${paint("bold", task.title)}" PRD generation failed (${failureDetail}), marked as error`);
2777
+ try {
2778
+ await api.patch(`/api/tasks/${task.id}`, { status: "error" });
2779
+ } catch (err) {
2780
+ logError(prefix, `Failed to mark task as error: ${err.message}`);
2781
+ }
2782
+ await postTaskUpdate(task.id, `PRD generation failed via ${attemptAgent} (${failureDetail}) \u2014 task moved to error`, "system");
2346
2783
  }
2347
- await postTaskUpdate(task.id, `PRD generation failed with exit code ${code} \u2014 task moved to error`, "system");
2784
+ } finally {
2785
+ queued.delete(task.id);
2786
+ finishing.delete(task.id);
2348
2787
  }
2349
- } finally {
2350
- queued.delete(task.id);
2351
- finishing.delete(task.id);
2352
- }
2353
- });
2788
+ });
2789
+ };
2790
+ await launchAttempt(attemptOrder[attemptIndex]);
2354
2791
  }
2355
2792
  async function dispatchPrototypeJob(proto, repoDir) {
2356
2793
  const sid = shortId(proto.id);
@@ -2376,53 +2813,101 @@ var watchCommand = new Command8("watch").description(
2376
2813
  } else {
2377
2814
  prompt2 = buildPrototypePrompt(proto, repoDir);
2378
2815
  }
2379
- const child = spawnAgent(agent, repoDir, prompt2, prefix, void 0, void 0, proto.title);
2380
- active.set(`proto-${proto.id}`, { process: child, title: proto.title, repoDir, startedAt: Date.now() });
2381
- child.on("exit", async (code) => {
2382
- const key = `proto-${proto.id}`;
2383
- active.delete(key);
2384
- finishing.add(key);
2385
- try {
2386
- if (code === 0) {
2387
- try {
2388
- const protoPattern = /^prototype-\d+\.html$/;
2389
- const found = readdirSync(repoDir).filter((f) => protoPattern.test(f)).sort();
2390
- const files = found.map((f) => ({
2391
- name: f,
2392
- content: readFileSync5(resolve2(repoDir, f), "utf-8")
2393
- }));
2394
- if (files.length === 0) {
2395
- logError(prefix, `No prototype HTML files found in ${repoDir}`);
2396
- await api.patch(`/api/prototypes/${proto.id}`, { status: "failed" });
2397
- return;
2398
- }
2399
- await api.patch(`/api/prototypes/${proto.id}`, { status: "completed", files });
2400
- logSuccess(prefix, `"${paint("bold", proto.title)}" uploaded ${files.length} file(s)`);
2401
- for (const file of files) {
2816
+ const key = `proto-${proto.id}`;
2817
+ const attemptOrder = await resolveAgentChain(agent);
2818
+ if (attemptOrder.length === 0) {
2819
+ logError(prefix, `No available agents found for fallback chain starting at ${agent}`);
2820
+ await api.patch(`/api/prototypes/${proto.id}`, { status: "failed" }).catch(() => {
2821
+ });
2822
+ queued.delete(key);
2823
+ return;
2824
+ }
2825
+ const activeEntry = {
2826
+ process: void 0,
2827
+ title: proto.title,
2828
+ repoDir,
2829
+ startedAt: Date.now(),
2830
+ lastActivityAt: Date.now()
2831
+ };
2832
+ let attemptIndex = 0;
2833
+ const launchAttempt = async (attemptAgent) => {
2834
+ let spawnFailureReason = null;
2835
+ const child = spawnAgent(
2836
+ attemptAgent,
2837
+ repoDir,
2838
+ prompt2,
2839
+ prefix,
2840
+ void 0,
2841
+ void 0,
2842
+ proto.title,
2843
+ false,
2844
+ (err) => {
2845
+ spawnFailureReason = err.message;
2846
+ }
2847
+ );
2848
+ activeEntry.process = child;
2849
+ activeEntry.currentAgent = attemptAgent;
2850
+ active.set(key, activeEntry);
2851
+ child.on("exit", async (code) => {
2852
+ if (active.get(key)?.process === child) {
2853
+ active.delete(key);
2854
+ }
2855
+ const failedAttempt = code !== 0 || spawnFailureReason !== null;
2856
+ if (failedAttempt) {
2857
+ const nextAgent = attemptOrder[attemptIndex + 1];
2858
+ if (nextAgent) {
2859
+ const failureDetail = spawnFailureReason ?? `exit code ${code}`;
2860
+ logWarn(prefix, `${attemptAgent} failed (${failureDetail}) \u2014 retrying prototype generation with ${nextAgent}`);
2861
+ attemptIndex += 1;
2862
+ await launchAttempt(nextAgent);
2863
+ return;
2864
+ }
2865
+ }
2866
+ finishing.add(key);
2867
+ try {
2868
+ if (code === 0) {
2869
+ try {
2870
+ const protoPattern = /^prototype-\d+\.html$/;
2871
+ const found = readdirSync(repoDir).filter((f) => protoPattern.test(f)).sort();
2872
+ const files = found.map((f) => ({
2873
+ name: f,
2874
+ content: readFileSync5(resolve2(repoDir, f), "utf-8")
2875
+ }));
2876
+ if (files.length === 0) {
2877
+ logError(prefix, `No prototype HTML files found in ${repoDir}`);
2878
+ await api.patch(`/api/prototypes/${proto.id}`, { status: "failed" });
2879
+ return;
2880
+ }
2881
+ await api.patch(`/api/prototypes/${proto.id}`, { status: "completed", files });
2882
+ logSuccess(prefix, `"${paint("bold", proto.title)}" uploaded ${files.length} file(s)`);
2883
+ for (const file of files) {
2884
+ try {
2885
+ unlinkSync(resolve2(repoDir, file.name));
2886
+ } catch {
2887
+ }
2888
+ }
2889
+ } catch (err) {
2890
+ logError(prefix, `Failed to upload prototype: ${err.message}`);
2402
2891
  try {
2403
- unlinkSync(resolve2(repoDir, file.name));
2892
+ await api.patch(`/api/prototypes/${proto.id}`, { status: "failed" });
2404
2893
  } catch {
2405
2894
  }
2406
2895
  }
2407
- } catch (err) {
2408
- logError(prefix, `Failed to upload prototype: ${err.message}`);
2896
+ } else {
2897
+ const failureDetail = spawnFailureReason ?? `exit code ${code}`;
2898
+ logError(prefix, `"${paint("bold", proto.title)}" prototype failed via ${attemptAgent} (${failureDetail})`);
2409
2899
  try {
2410
2900
  await api.patch(`/api/prototypes/${proto.id}`, { status: "failed" });
2411
2901
  } catch {
2412
2902
  }
2413
2903
  }
2414
- } else {
2415
- logError(prefix, `"${paint("bold", proto.title)}" prototype failed (exit ${code})`);
2416
- try {
2417
- await api.patch(`/api/prototypes/${proto.id}`, { status: "failed" });
2418
- } catch {
2419
- }
2904
+ } finally {
2905
+ queued.delete(key);
2906
+ finishing.delete(key);
2420
2907
  }
2421
- } finally {
2422
- queued.delete(key);
2423
- finishing.delete(key);
2424
- }
2425
- });
2908
+ });
2909
+ };
2910
+ await launchAttempt(attemptOrder[attemptIndex]);
2426
2911
  }
2427
2912
  async function dispatchRepoCreation(project, workDir) {
2428
2913
  const sid = shortId(project.id);
@@ -2433,27 +2918,87 @@ var watchCommand = new Command8("watch").description(
2433
2918
  } catch {
2434
2919
  }
2435
2920
  const prompt2 = buildRepoCreationPrompt(project, workDir);
2436
- const child = spawnAgent(agent, workDir, prompt2, prefix, void 0, void 0, project.name);
2437
- active.set(`repo-${project.id}`, { process: child, title: project.name, repoDir: workDir, startedAt: Date.now() });
2438
- child.on("exit", async (code) => {
2439
- const key = `repo-${project.id}`;
2440
- active.delete(key);
2441
- finishing.add(key);
2921
+ const key = `repo-${project.id}`;
2922
+ const attemptOrder = await resolveAgentChain(agent);
2923
+ if (attemptOrder.length === 0) {
2924
+ logError(prefix, `No available agents found for fallback chain starting at ${agent}`);
2925
+ queued.delete(key);
2442
2926
  try {
2443
- if (code === 0) {
2444
- logSuccess(prefix, `"${paint("bold", project.name)}" repo creation complete`);
2445
- } else {
2446
- logError(prefix, `"${paint("bold", project.name)}" repo creation failed (exit ${code})`);
2447
- try {
2448
- await api.patch(`/api/projects/${project.id}`, { repoCreationStatus: "failed" });
2449
- } catch {
2927
+ await api.patch(`/api/projects/${project.id}`, { repoCreationStatus: "failed" });
2928
+ } catch {
2929
+ }
2930
+ return;
2931
+ }
2932
+ const activeEntry = {
2933
+ process: void 0,
2934
+ title: project.name,
2935
+ repoDir: workDir,
2936
+ startedAt: Date.now(),
2937
+ lastActivityAt: Date.now()
2938
+ };
2939
+ let attemptIndex = 0;
2940
+ const launchAttempt = async (attemptAgent) => {
2941
+ let spawnFailureReason = null;
2942
+ const child = spawnAgent(
2943
+ attemptAgent,
2944
+ workDir,
2945
+ prompt2,
2946
+ prefix,
2947
+ void 0,
2948
+ void 0,
2949
+ project.name,
2950
+ false,
2951
+ (err) => {
2952
+ spawnFailureReason = err.message;
2953
+ },
2954
+ void 0,
2955
+ 25
2956
+ // max turns — prevent the agent from looping internally
2957
+ );
2958
+ activeEntry.process = child;
2959
+ activeEntry.currentAgent = attemptAgent;
2960
+ active.set(key, activeEntry);
2961
+ child.on("exit", async (code) => {
2962
+ if (active.get(key)?.process === child) {
2963
+ active.delete(key);
2964
+ }
2965
+ const failedAttempt = code !== 0 || spawnFailureReason !== null;
2966
+ if (failedAttempt) {
2967
+ const nextAgent = attemptOrder[attemptIndex + 1];
2968
+ if (nextAgent) {
2969
+ const failureDetail = spawnFailureReason ?? `exit code ${code}`;
2970
+ logWarn(prefix, `${attemptAgent} failed (${failureDetail}) \u2014 retrying repo creation with ${nextAgent}`);
2971
+ attemptIndex += 1;
2972
+ await launchAttempt(nextAgent);
2973
+ return;
2450
2974
  }
2451
2975
  }
2452
- } finally {
2453
- queued.delete(key);
2454
- finishing.delete(key);
2455
- }
2456
- });
2976
+ finishing.add(key);
2977
+ try {
2978
+ if (code === 0) {
2979
+ logSuccess(prefix, `"${paint("bold", project.name)}" repo creation complete`);
2980
+ try {
2981
+ await api.patch(`/api/projects/${project.id}`, { repoCreationStatus: "created" });
2982
+ } catch (err) {
2983
+ logError(prefix, `Failed to mark repo as created: ${err.message}`);
2984
+ failed.set(key, "status update failed after successful creation");
2985
+ }
2986
+ } else {
2987
+ const failureDetail = spawnFailureReason ?? `exit code ${code}`;
2988
+ logError(prefix, `"${paint("bold", project.name)}" repo creation failed via ${attemptAgent} (${failureDetail})`);
2989
+ failed.set(key, failureDetail);
2990
+ try {
2991
+ await api.patch(`/api/projects/${project.id}`, { repoCreationStatus: "failed" });
2992
+ } catch {
2993
+ }
2994
+ }
2995
+ } finally {
2996
+ queued.delete(key);
2997
+ finishing.delete(key);
2998
+ }
2999
+ });
3000
+ };
3001
+ await launchAttempt(attemptOrder[attemptIndex]);
2457
3002
  }
2458
3003
  async function dispatchIdeaJob(idea, repoDir) {
2459
3004
  const sid = shortId(idea.id);
@@ -2466,96 +3011,146 @@ var watchCommand = new Command8("watch").description(
2466
3011
  }
2467
3012
  }
2468
3013
  const prompt2 = buildIdeaPrompt(idea, repoDir);
2469
- const child = spawnAgent(agent, repoDir, prompt2, prefix, void 0, void 0, idea.title);
2470
- active.set(`idea-${idea.id}`, { process: child, title: idea.title, repoDir, startedAt: Date.now() });
2471
- child.on("exit", async (code) => {
2472
- const key = `idea-${idea.id}`;
2473
- active.delete(key);
2474
- finishing.add(key);
3014
+ const key = `idea-${idea.id}`;
3015
+ const attemptOrder = await resolveAgentChain(agent);
3016
+ if (attemptOrder.length === 0) {
3017
+ logError(prefix, `No available agents found for fallback chain starting at ${agent}`);
3018
+ queued.delete(key);
2475
3019
  try {
2476
- if (code === 0) {
2477
- try {
2478
- let plan;
2479
- let protoHtml;
2480
- let followUpTasks;
2481
- const planPath = resolve2(repoDir, "idea-plan.md");
2482
- const tasksPath = resolve2(repoDir, "idea-tasks.json");
2483
- const protoPath = resolve2(repoDir, "idea-prototype.html");
2484
- try {
2485
- plan = readFileSync5(planPath, "utf-8");
2486
- } catch {
2487
- }
2488
- try {
2489
- protoHtml = readFileSync5(protoPath, "utf-8");
2490
- } catch {
2491
- }
3020
+ await api.patch(`/api/ideas/${idea.id}`, { status: "draft" });
3021
+ } catch {
3022
+ }
3023
+ return;
3024
+ }
3025
+ const activeEntry = {
3026
+ process: void 0,
3027
+ title: idea.title,
3028
+ repoDir,
3029
+ startedAt: Date.now(),
3030
+ lastActivityAt: Date.now()
3031
+ };
3032
+ let attemptIndex = 0;
3033
+ const launchAttempt = async (attemptAgent) => {
3034
+ let spawnFailureReason = null;
3035
+ const child = spawnAgent(
3036
+ attemptAgent,
3037
+ repoDir,
3038
+ prompt2,
3039
+ prefix,
3040
+ void 0,
3041
+ void 0,
3042
+ idea.title,
3043
+ false,
3044
+ (err) => {
3045
+ spawnFailureReason = err.message;
3046
+ }
3047
+ );
3048
+ activeEntry.process = child;
3049
+ activeEntry.currentAgent = attemptAgent;
3050
+ active.set(key, activeEntry);
3051
+ child.on("exit", async (code) => {
3052
+ if (active.get(key)?.process === child) {
3053
+ active.delete(key);
3054
+ }
3055
+ const failedAttempt = code !== 0 || spawnFailureReason !== null;
3056
+ if (failedAttempt) {
3057
+ const nextAgent = attemptOrder[attemptIndex + 1];
3058
+ if (nextAgent) {
3059
+ const failureDetail = spawnFailureReason ?? `exit code ${code}`;
3060
+ logWarn(prefix, `${attemptAgent} failed (${failureDetail}) \u2014 retrying idea generation with ${nextAgent}`);
3061
+ attemptIndex += 1;
3062
+ await launchAttempt(nextAgent);
3063
+ return;
3064
+ }
3065
+ }
3066
+ finishing.add(key);
3067
+ try {
3068
+ if (code === 0) {
2492
3069
  try {
2493
- const tasksRaw = readFileSync5(tasksPath, "utf-8");
2494
- const parsed = JSON.parse(tasksRaw);
2495
- if (Array.isArray(parsed)) {
2496
- followUpTasks = parsed.filter((t) => t && typeof t === "object" && "title" in t);
3070
+ let plan;
3071
+ let protoHtml;
3072
+ let followUpTasks;
3073
+ const planPath = resolve2(repoDir, "idea-plan.md");
3074
+ const tasksPath = resolve2(repoDir, "idea-tasks.json");
3075
+ const protoPath = resolve2(repoDir, "idea-prototype.html");
3076
+ try {
3077
+ plan = readFileSync5(planPath, "utf-8");
3078
+ } catch {
2497
3079
  }
2498
- } catch {
2499
- }
2500
- if (!plan && !protoHtml) {
2501
- logError(prefix, `No output files found in ${repoDir}`);
2502
- await api.patch(`/api/ideas/${idea.id}`, { status: "draft" });
2503
- return;
2504
- }
2505
- const updateData = { status: "generated" };
2506
- if (plan) updateData.plan = plan;
2507
- if (followUpTasks) updateData.followUpTasks = followUpTasks;
2508
- if (protoHtml) {
2509
3080
  try {
2510
- const proto = await api.post("/api/prototypes", {
2511
- title: `${idea.title} \u2014 Idea Prototype`,
2512
- prompt: idea.description || idea.title,
2513
- variantCount: 1,
2514
- projectId: idea.projectId ?? null
2515
- });
2516
- await api.patch(`/api/prototypes/${proto.id}`, {
2517
- status: "completed",
2518
- files: [{ name: "idea-prototype.html", content: protoHtml }]
2519
- });
2520
- updateData.generatedPrototypeId = proto.id;
2521
- logSuccess(prefix, `Prototype created: ${paint("gray", proto.id.slice(0, 8))}`);
2522
- } catch (err) {
2523
- logError(prefix, `Failed to create prototype: ${err.message}`);
3081
+ protoHtml = readFileSync5(protoPath, "utf-8");
3082
+ } catch {
3083
+ }
3084
+ try {
3085
+ const tasksRaw = readFileSync5(tasksPath, "utf-8");
3086
+ const parsed = JSON.parse(tasksRaw);
3087
+ if (Array.isArray(parsed)) {
3088
+ followUpTasks = parsed.filter((t) => t && typeof t === "object" && "title" in t);
3089
+ }
3090
+ } catch {
3091
+ }
3092
+ if (!plan && !protoHtml) {
3093
+ logError(prefix, `No output files found in ${repoDir}`);
3094
+ await api.patch(`/api/ideas/${idea.id}`, { status: "draft" });
3095
+ return;
3096
+ }
3097
+ const updateData = { status: "generated" };
3098
+ if (plan) updateData.plan = plan;
3099
+ if (followUpTasks) updateData.followUpTasks = followUpTasks;
3100
+ if (protoHtml) {
3101
+ try {
3102
+ const proto = await api.post("/api/prototypes", {
3103
+ title: `${idea.title} \u2014 Idea Prototype`,
3104
+ prompt: idea.description || idea.title,
3105
+ variantCount: 1,
3106
+ projectId: idea.projectId ?? null
3107
+ });
3108
+ await api.patch(`/api/prototypes/${proto.id}`, {
3109
+ status: "completed",
3110
+ files: [{ name: "idea-prototype.html", content: protoHtml }]
3111
+ });
3112
+ updateData.generatedPrototypeId = proto.id;
3113
+ logSuccess(prefix, `Prototype created: ${paint("gray", proto.id.slice(0, 8))}`);
3114
+ } catch (err) {
3115
+ logError(prefix, `Failed to create prototype: ${err.message}`);
3116
+ }
3117
+ }
3118
+ await api.patch(`/api/ideas/${idea.id}`, updateData);
3119
+ logSuccess(prefix, `"${paint("bold", idea.title)}" generation complete`);
3120
+ try {
3121
+ unlinkSync(planPath);
3122
+ } catch {
3123
+ }
3124
+ try {
3125
+ unlinkSync(tasksPath);
3126
+ } catch {
3127
+ }
3128
+ try {
3129
+ unlinkSync(protoPath);
3130
+ } catch {
3131
+ }
3132
+ } catch (err) {
3133
+ logError(prefix, `Failed to upload idea output: ${err.message}`);
3134
+ try {
3135
+ await api.patch(`/api/ideas/${idea.id}`, { status: "draft" });
3136
+ } catch {
2524
3137
  }
2525
3138
  }
2526
- await api.patch(`/api/ideas/${idea.id}`, updateData);
2527
- logSuccess(prefix, `"${paint("bold", idea.title)}" generation complete`);
2528
- try {
2529
- unlinkSync(planPath);
2530
- } catch {
2531
- }
2532
- try {
2533
- unlinkSync(tasksPath);
2534
- } catch {
2535
- }
2536
- try {
2537
- unlinkSync(protoPath);
2538
- } catch {
2539
- }
2540
- } catch (err) {
2541
- logError(prefix, `Failed to upload idea output: ${err.message}`);
3139
+ } else {
3140
+ const failureDetail = spawnFailureReason ?? `exit code ${code}`;
3141
+ logError(prefix, `"${paint("bold", idea.title)}" generation failed via ${attemptAgent} (${failureDetail})`);
2542
3142
  try {
2543
3143
  await api.patch(`/api/ideas/${idea.id}`, { status: "draft" });
2544
3144
  } catch {
2545
3145
  }
2546
3146
  }
2547
- } else {
2548
- logError(prefix, `"${paint("bold", idea.title)}" generation failed (exit ${code})`);
2549
- try {
2550
- await api.patch(`/api/ideas/${idea.id}`, { status: "draft" });
2551
- } catch {
2552
- }
3147
+ } finally {
3148
+ queued.delete(key);
3149
+ finishing.delete(key);
2553
3150
  }
2554
- } finally {
2555
- queued.delete(key);
2556
- finishing.delete(key);
2557
- }
2558
- });
3151
+ });
3152
+ };
3153
+ await launchAttempt(attemptOrder[attemptIndex]);
2559
3154
  }
2560
3155
  function dispatchScan(scan, prefix, key) {
2561
3156
  logDispatch(prefix, `Running scan for project ${paint("cyan", scan.projectId.slice(0, 8))}`);
@@ -2569,7 +3164,13 @@ var watchCommand = new Command8("watch").description(
2569
3164
  queued.delete(key);
2570
3165
  failed.set(key, err.message);
2571
3166
  });
2572
- active.set(key, { process: scanProc, title: `scan-${scan.id.slice(0, 8)}`, repoDir: rootDir, startedAt: Date.now() });
3167
+ active.set(key, {
3168
+ process: scanProc,
3169
+ title: `scan-${scan.id.slice(0, 8)}`,
3170
+ repoDir: rootDir,
3171
+ startedAt: Date.now(),
3172
+ lastActivityAt: Date.now()
3173
+ });
2573
3174
  scanProc.stdout?.on("data", (d) => {
2574
3175
  const lines = d.toString().trim().split("\n");
2575
3176
  for (const line of lines) {
@@ -2601,7 +3202,28 @@ var watchCommand = new Command8("watch").description(
2601
3202
  const prefix = taskTag(sid);
2602
3203
  try {
2603
3204
  logSpinner(prefix, `Generating plan for "${paint("bold", task.title)}"\u2026`);
2604
- const plan = await runPlanningPhase(task, repoDir, agent);
3205
+ const attemptOrder = await resolveAgentChain(agent);
3206
+ if (attemptOrder.length === 0) {
3207
+ throw new Error(`No available agent found for fallback chain starting at ${agent}`);
3208
+ }
3209
+ let plan;
3210
+ let lastError;
3211
+ for (let idx = 0; idx < attemptOrder.length; idx += 1) {
3212
+ const attemptAgent = attemptOrder[idx];
3213
+ try {
3214
+ plan = await runPlanningPhase(task, repoDir, attemptAgent);
3215
+ break;
3216
+ } catch (err) {
3217
+ lastError = err;
3218
+ const nextAgent = attemptOrder[idx + 1];
3219
+ if (nextAgent) {
3220
+ logWarn(prefix, `${attemptAgent} planning failed (${lastError.message}) \u2014 retrying with ${nextAgent}`);
3221
+ }
3222
+ }
3223
+ }
3224
+ if (!plan) {
3225
+ throw lastError ?? new Error("Planning failed");
3226
+ }
2605
3227
  const width = 64;
2606
3228
  const divider = paint("gray", "\u2500".repeat(width));
2607
3229
  const header = `${paint("bold", "Plan")} "${paint("bold", task.title)}" ${taskTag(sid)}`;
@@ -2794,14 +3416,16 @@ ${divider}`);
2794
3416
  if (failed.has(key)) continue;
2795
3417
  const sid = shortId(proto.id);
2796
3418
  const prefix = protoTag(sid);
2797
- if (!proto.projectId) {
2798
- logWarn(prefix, `"${proto.title}": no projectId \u2014 skipping`);
2799
- continue;
2800
- }
2801
- const repoDir = findDirectoryForProject(config, proto.projectId, rootDir);
2802
- if (!repoDir) {
2803
- logWarn(prefix, `"${proto.title}": no linked directory found \u2014 skipping`);
2804
- continue;
3419
+ let repoDir;
3420
+ if (proto.projectId) {
3421
+ const dir = findDirectoryForProject(config, proto.projectId, rootDir);
3422
+ if (!dir) {
3423
+ logWarn(prefix, `"${proto.title}": no linked directory found \u2014 skipping`);
3424
+ continue;
3425
+ }
3426
+ repoDir = dir;
3427
+ } else {
3428
+ repoDir = rootDir;
2805
3429
  }
2806
3430
  if (!existsSync7(repoDir)) {
2807
3431
  logError(prefix, `"${proto.title}": linked directory "${repoDir}" does not exist \u2014 skipping`);
@@ -2884,9 +3508,9 @@ ${divider}`);
2884
3508
  browseRunner: runBrowseCommand2,
2885
3509
  uploadScreenshot: async (screenshotPath, message) => {
2886
3510
  try {
2887
- const { readFileSync: readFileSync12 } = await import("fs");
3511
+ const { readFileSync: readFileSync13 } = await import("fs");
2888
3512
  const cfg = loadConfig();
2889
- const imageBuffer = readFileSync12(screenshotPath);
3513
+ const imageBuffer = readFileSync13(screenshotPath);
2890
3514
  const fileName = screenshotPath.split("/").pop() || "test-screenshot.png";
2891
3515
  const formData = new FormData();
2892
3516
  const blob = new Blob([imageBuffer], { type: "image/png" });
@@ -3312,22 +3936,21 @@ var prototypeCommand = new Command13("prototype").description("Manage prototypes
3312
3936
  }
3313
3937
  })
3314
3938
  ).addCommand(
3315
- new Command13("create").description("Create a new prototype").argument("<title>", "Title of the prototype").requiredOption("--prompt <prompt>", "Design description / prompt").option("--project <projectId>", "Project ID (defaults to linked project)").option("--variants <count>", "Number of variants to generate (1-50)", "5").action(async (title, opts) => {
3939
+ new Command13("create").description("Create a new prototype").argument("<title>", "Title of the prototype").requiredOption("--prompt <prompt>", "Design description / prompt").option("--project <projectId>", "Project ID (defaults to linked project, when available)").option("--variants <count>", "Number of variants to generate (1-50)", "5").action(async (title, opts) => {
3316
3940
  const projectId = opts.project ?? getLinkedProjectId();
3317
- if (!projectId) {
3318
- console.error('No project linked. Run "mr link <project-id>" or use --project.');
3319
- process.exit(1);
3320
- }
3321
3941
  const variantCount = Math.max(1, Math.min(50, parseInt(opts.variants, 10) || 5));
3322
3942
  const prototype = await api.post("/api/prototypes", {
3323
3943
  title,
3324
3944
  prompt: opts.prompt,
3325
3945
  variantCount,
3326
- projectId
3946
+ projectId: projectId ?? null
3327
3947
  });
3328
3948
  console.log();
3329
3949
  console.log(` ${paint4("green", "\u2713")} Created prototype: ${paint4("bold", prototype.title)}`);
3330
3950
  console.log(` ${paint4("gray", "ID:")} ${prototype.id}`);
3951
+ if (!prototype.projectId) {
3952
+ console.log(` ${paint4("gray", "Project:")} none (will generate in the active watch directory)`);
3953
+ }
3331
3954
  console.log(` ${paint4("cyan", "\u27F3")} Generation will begin automatically via the watch agent.`);
3332
3955
  console.log();
3333
3956
  })
@@ -3370,20 +3993,20 @@ var c5 = {
3370
3993
  function paint5(color, text) {
3371
3994
  return `${c5[color]}${text}${c5.reset}`;
3372
3995
  }
3373
- function commandExists(cmd) {
3374
- return new Promise((resolve7) => {
3375
- exec2(`which ${cmd}`, (err) => resolve7(!err));
3996
+ function commandExists2(cmd) {
3997
+ return new Promise((resolve8) => {
3998
+ exec2(`which ${cmd}`, (err) => resolve8(!err));
3376
3999
  });
3377
4000
  }
3378
4001
  function execQuiet(cmd) {
3379
- return new Promise((resolve7) => {
4002
+ return new Promise((resolve8) => {
3380
4003
  exec2(cmd, (err, stdout, stderr) => {
3381
- resolve7({ ok: !err, stdout: stdout.trim(), stderr: stderr.trim() });
4004
+ resolve8({ ok: !err, stdout: stdout.trim(), stderr: stderr.trim() });
3382
4005
  });
3383
4006
  });
3384
4007
  }
3385
4008
  async function checkGitInstalled() {
3386
- const exists = await commandExists("git");
4009
+ const exists = await commandExists2("git");
3387
4010
  if (!exists) {
3388
4011
  return {
3389
4012
  name: "Git",
@@ -3423,7 +4046,7 @@ async function checkNodeVersion() {
3423
4046
  };
3424
4047
  }
3425
4048
  async function checkGhInstalled() {
3426
- const exists = await commandExists("gh");
4049
+ const exists = await commandExists2("gh");
3427
4050
  return {
3428
4051
  name: "GitHub CLI (gh)",
3429
4052
  ok: exists,
@@ -3432,7 +4055,7 @@ async function checkGhInstalled() {
3432
4055
  };
3433
4056
  }
3434
4057
  async function checkGhAuth() {
3435
- const exists = await commandExists("gh");
4058
+ const exists = await commandExists2("gh");
3436
4059
  if (!exists) {
3437
4060
  return {
3438
4061
  name: "GitHub CLI auth",
@@ -3450,7 +4073,7 @@ async function checkGhAuth() {
3450
4073
  };
3451
4074
  }
3452
4075
  async function checkClaudeInstalled() {
3453
- const exists = await commandExists("claude");
4076
+ const exists = await commandExists2("claude");
3454
4077
  return {
3455
4078
  name: "Claude Code (claude)",
3456
4079
  ok: exists,
@@ -3459,7 +4082,7 @@ async function checkClaudeInstalled() {
3459
4082
  };
3460
4083
  }
3461
4084
  async function checkClaudeAuth() {
3462
- const exists = await commandExists("claude");
4085
+ const exists = await commandExists2("claude");
3463
4086
  if (!exists) {
3464
4087
  return {
3465
4088
  name: "Claude Code auth",
@@ -3477,7 +4100,7 @@ async function checkClaudeAuth() {
3477
4100
  };
3478
4101
  }
3479
4102
  async function checkCodexInstalled() {
3480
- const exists = await commandExists("codex");
4103
+ const exists = await commandExists2("codex");
3481
4104
  return {
3482
4105
  name: "Codex CLI (codex)",
3483
4106
  ok: exists,
@@ -3486,7 +4109,7 @@ async function checkCodexInstalled() {
3486
4109
  };
3487
4110
  }
3488
4111
  async function checkCodexAuth() {
3489
- const exists = await commandExists("codex");
4112
+ const exists = await commandExists2("codex");
3490
4113
  if (!exists) {
3491
4114
  return {
3492
4115
  name: "Codex CLI auth",
@@ -3503,7 +4126,7 @@ async function checkCodexAuth() {
3503
4126
  };
3504
4127
  }
3505
4128
  async function checkGeminiInstalled() {
3506
- const exists = await commandExists("gemini");
4129
+ const exists = await commandExists2("gemini");
3507
4130
  return {
3508
4131
  name: "Gemini CLI (gemini)",
3509
4132
  ok: exists,
@@ -3512,7 +4135,7 @@ async function checkGeminiInstalled() {
3512
4135
  };
3513
4136
  }
3514
4137
  async function checkGeminiAuth() {
3515
- const exists = await commandExists("gemini");
4138
+ const exists = await commandExists2("gemini");
3516
4139
  if (!exists) {
3517
4140
  return {
3518
4141
  name: "Gemini CLI auth",
@@ -3529,7 +4152,7 @@ async function checkGeminiAuth() {
3529
4152
  };
3530
4153
  }
3531
4154
  async function checkGlabInstalled() {
3532
- const exists = await commandExists("glab");
4155
+ const exists = await commandExists2("glab");
3533
4156
  return {
3534
4157
  name: "GitLab CLI (glab)",
3535
4158
  ok: exists,
@@ -3539,7 +4162,7 @@ async function checkGlabInstalled() {
3539
4162
  };
3540
4163
  }
3541
4164
  async function checkGlabAuth() {
3542
- const exists = await commandExists("glab");
4165
+ const exists = await commandExists2("glab");
3543
4166
  if (!exists) {
3544
4167
  return {
3545
4168
  name: "GitLab CLI auth",
@@ -3559,7 +4182,7 @@ async function checkGlabAuth() {
3559
4182
  };
3560
4183
  }
3561
4184
  async function checkJqInstalled() {
3562
- const exists = await commandExists("jq");
4185
+ const exists = await commandExists2("jq");
3563
4186
  return {
3564
4187
  name: "jq (optional)",
3565
4188
  ok: exists,
@@ -3633,26 +4256,26 @@ async function autoFix(checks, agent) {
3633
4256
  if (claudeCheck && !claudeCheck.ok && agent === "claude") {
3634
4257
  console.log(paint5("cyan", " Installing Claude Code..."));
3635
4258
  console.log(paint5("dim", " Running: curl -fsSL https://claude.ai/install.sh | bash"));
3636
- await new Promise((resolve7) => {
4259
+ await new Promise((resolve8) => {
3637
4260
  const child = spawn8("bash", ["-c", "curl -fsSL https://claude.ai/install.sh | bash"], { stdio: "inherit" });
3638
- child.on("exit", () => resolve7());
4261
+ child.on("exit", () => resolve8());
3639
4262
  });
3640
4263
  console.log("");
3641
4264
  }
3642
4265
  if (ghInstalled && !ghAuthed) {
3643
4266
  console.log(paint5("cyan", " Running gh auth login..."));
3644
- await new Promise((resolve7) => {
4267
+ await new Promise((resolve8) => {
3645
4268
  const child = spawn8("gh", ["auth", "login"], { stdio: "inherit" });
3646
- child.on("exit", () => resolve7());
4269
+ child.on("exit", () => resolve8());
3647
4270
  });
3648
4271
  console.log("");
3649
4272
  }
3650
4273
  if (!mrAuthed) {
3651
4274
  console.log(paint5("cyan", " Running mr login..."));
3652
4275
  const entry = process.argv[1];
3653
- await new Promise((resolve7) => {
4276
+ await new Promise((resolve8) => {
3654
4277
  const child = spawn8(process.execPath, [entry, "login"], { stdio: "inherit" });
3655
- child.on("exit", () => resolve7());
4278
+ child.on("exit", () => resolve8());
3656
4279
  });
3657
4280
  console.log("");
3658
4281
  }
@@ -3900,7 +4523,7 @@ var resumeCommand = new Command17("resume").description("Resume an interactive C
3900
4523
  // cli/commands/browse.ts
3901
4524
  import { Command as Command18 } from "commander";
3902
4525
  import { execSync as execSync5, spawn as spawn6 } from "child_process";
3903
- import { existsSync as existsSync9, readFileSync as readFileSync7, writeFileSync as writeFileSync4 } from "fs";
4526
+ import { existsSync as existsSync9, readFileSync as readFileSync7, writeFileSync as writeFileSync5 } from "fs";
3904
4527
  import { join as join8 } from "path";
3905
4528
  var BROWSE_DIR2 = join8(import.meta.dirname, "..", "..", "browse");
3906
4529
  function isProcessAlive(pid) {
@@ -3947,7 +4570,7 @@ async function ensureDevServer() {
3947
4570
  env: { ...process.env }
3948
4571
  });
3949
4572
  devProc.unref();
3950
- writeFileSync4(
4573
+ writeFileSync5(
3951
4574
  devStateFile,
3952
4575
  JSON.stringify({ pid: devProc.pid, port, startedAt: (/* @__PURE__ */ new Date()).toISOString() }),
3953
4576
  { mode: 384 }
@@ -4189,7 +4812,7 @@ var testCommand = new Command20("test").description("Run automated browser test
4189
4812
 
4190
4813
  // cli/commands/features.ts
4191
4814
  import { Command as Command21 } from "commander";
4192
- import { readFileSync as readFileSync9, writeFileSync as writeFileSync5, existsSync as existsSync12 } from "fs";
4815
+ import { readFileSync as readFileSync9, writeFileSync as writeFileSync6, existsSync as existsSync12 } from "fs";
4193
4816
  import { resolve as resolve5, sep as sep2 } from "path";
4194
4817
  var FEATURES_FILE3 = ".mr-features.md";
4195
4818
  var c7 = {
@@ -4230,13 +4853,13 @@ var featuresCommand = new Command21("features").description("View or update the
4230
4853
  if (opts.file) {
4231
4854
  const content2 = readFileSync9(resolve5(opts.file), "utf-8");
4232
4855
  const featuresPath = getFeaturesPath();
4233
- writeFileSync5(featuresPath, content2);
4856
+ writeFileSync6(featuresPath, content2);
4234
4857
  console.log(`${paint7("green", "\u2713")} Updated ${paint7("cyan", featuresPath)} from ${paint7("cyan", opts.file)}`);
4235
4858
  return;
4236
4859
  }
4237
4860
  if (opts.update) {
4238
4861
  const featuresPath = getFeaturesPath();
4239
- writeFileSync5(featuresPath, opts.update);
4862
+ writeFileSync6(featuresPath, opts.update);
4240
4863
  console.log(`${paint7("green", "\u2713")} Updated ${paint7("cyan", featuresPath)}`);
4241
4864
  return;
4242
4865
  }
@@ -4251,12 +4874,12 @@ var featuresCommand = new Command21("features").description("View or update the
4251
4874
 
4252
4875
  // cli/commands/no-mr.ts
4253
4876
  import { Command as Command22 } from "commander";
4254
- import { writeFileSync as writeFileSync6 } from "fs";
4877
+ import { writeFileSync as writeFileSync7 } from "fs";
4255
4878
  import { resolve as resolve6 } from "path";
4256
4879
  var NO_MR_FILE = ".mr-no-mr";
4257
4880
  var noMrCommand = new Command22("no-mr").description("Signal that a task does not require a merge/pull request and describe what was done instead").argument("<task-id>", "Task ID").argument("<description>", "Description of what was done instead of creating an MR/PR").action(async (taskId, description) => {
4258
4881
  const filePath = resolve6(process.cwd(), NO_MR_FILE);
4259
- writeFileSync6(filePath, description, "utf-8");
4882
+ writeFileSync7(filePath, description, "utf-8");
4260
4883
  await api.post(`/api/tasks/${taskId}/updates`, {
4261
4884
  message: `No MR/PR needed \u2014 ${description}`,
4262
4885
  source: "agent"
@@ -4495,8 +5118,8 @@ function matchesIgnorePattern(route, patterns) {
4495
5118
  }
4496
5119
  async function uploadScreenshot(imagePath, apiUrl, apiKey) {
4497
5120
  try {
4498
- const { readFileSync: readFileSync12 } = await import("fs");
4499
- const imageBuffer = readFileSync12(imagePath);
5121
+ const { readFileSync: readFileSync13 } = await import("fs");
5122
+ const imageBuffer = readFileSync13(imagePath);
4500
5123
  const blob = new Blob([imageBuffer], { type: "image/webp" });
4501
5124
  const formData = new FormData();
4502
5125
  formData.append("file", blob, `scan-${Date.now()}.webp`);
@@ -4703,22 +5326,19 @@ function buildSynthesisPrompt(config, context, codebaseAnalysis, crawlResults, p
4703
5326
  const promotedFindings = priorFindings.filter((f) => f.status === "promoted");
4704
5327
  const crawlSummary = crawlResults.map((r) => {
4705
5328
  let summary = `Route: ${r.route}
4706
- Title: ${r.pageTitle}
4707
- Headings: ${r.headings.join(", ") || "none"}`;
5329
+ Title: ${r.pageTitle}`;
4708
5330
  if (r.consoleErrors.length > 0) {
4709
5331
  summary += `
4710
- Console Errors: ${r.consoleErrors.slice(0, 5).join("; ")}`;
5332
+ Console Errors: ${r.consoleErrors.slice(0, 3).join("; ")}`;
4711
5333
  }
4712
5334
  if (r.consoleWarnings.length > 0) {
4713
5335
  summary += `
4714
- Console Warnings: ${r.consoleWarnings.slice(0, 3).join("; ")}`;
5336
+ Console Warnings: ${r.consoleWarnings.slice(0, 2).join("; ")}`;
4715
5337
  }
4716
- if (r.screenshotUrl) {
5338
+ if (r.loadTimeMs > 1e3) {
4717
5339
  summary += `
4718
- Screenshot: ${r.screenshotUrl}`;
5340
+ Load time: ${r.loadTimeMs}ms (slow)`;
4719
5341
  }
4720
- summary += `
4721
- Load time: ${r.loadTimeMs}ms`;
4722
5342
  return summary;
4723
5343
  }).join("\n\n");
4724
5344
  return `You are an autonomous product manager reviewing a web application. Your job is to produce actionable, specific findings that a developer can use to improve their product.
@@ -4735,16 +5355,16 @@ ${codebaseAnalysis.routes.map((r) => `- ${r}`).join("\n")}
4735
5355
  ${codebaseAnalysis.prismaModels.map((m) => `- ${m}`).join("\n")}
4736
5356
 
4737
5357
  **Components:**
4738
- ${codebaseAnalysis.components.slice(0, 30).map((c10) => `- ${c10}`).join("\n")}
5358
+ ${codebaseAnalysis.components.slice(0, 15).map((c10) => `- ${c10}`).join("\n")}
4739
5359
 
4740
5360
  **Recent Git Commits:**
4741
- ${codebaseAnalysis.recentCommits.slice(0, 15).map((c10) => `- ${c10}`).join("\n")}
5361
+ ${codebaseAnalysis.recentCommits.slice(0, 8).map((c10) => `- ${c10}`).join("\n")}
4742
5362
 
4743
5363
  **Completed Tasks:**
4744
- ${context.completedTasks.slice(0, 20).map((t) => `- ${t.title}`).join("\n") || "None"}
5364
+ ${context.completedTasks.slice(0, 10).map((t) => `- ${t.title}`).join("\n") || "None"}
4745
5365
 
4746
5366
  **Open Tasks:**
4747
- ${context.openTasks.slice(0, 10).map((t) => `- ${t.title}${t.notes ? ` (${t.notes})` : ""}`).join("\n") || "None"}
5367
+ ${context.openTasks.slice(0, 5).map((t) => `- ${t.title}`).join("\n") || "None"}
4748
5368
 
4749
5369
  ${config.focusAreas.length > 0 ? `**Focus Areas (user-specified):**
4750
5370
  ${config.focusAreas.map((a) => `- ${a}`).join("\n")}` : ""}
@@ -4755,11 +5375,9 @@ ${crawlResults.length > 0 ? crawlSummary : "Live crawl was not performed (app ma
4755
5375
 
4756
5376
  ## Prior Findings Context
4757
5377
 
4758
- ${dismissedFindings.length > 0 ? `**Previously Dismissed (do NOT re-suggest these):**
4759
- ${dismissedFindings.map((f) => `- [${f.type}] ${f.title}`).join("\n")}` : "No dismissed findings."}
5378
+ ${dismissedFindings.length > 0 ? `**Previously Dismissed (do NOT re-suggest):** ${dismissedFindings.map((f) => f.title).join("; ")}` : "No dismissed findings."}
4760
5379
 
4761
- ${promotedFindings.length > 0 ? `**Already Being Worked On (reference as "still present" if detected):**
4762
- ${promotedFindings.map((f) => `- [${f.type}] ${f.title}`).join("\n")}` : "No promoted findings."}
5380
+ ${promotedFindings.length > 0 ? `**Already Being Worked On:** ${promotedFindings.map((f) => f.title).join("; ")}` : "No promoted findings."}
4763
5381
 
4764
5382
  ## Instructions
4765
5383
 
@@ -4947,7 +5565,7 @@ async function fetchScanContext(opts) {
4947
5565
  };
4948
5566
  }
4949
5567
  function runClaude(prompt2) {
4950
- return new Promise((resolve7, reject) => {
5568
+ return new Promise((resolve8, reject) => {
4951
5569
  const child = spawn7("claude", ["-p", "--dangerously-skip-permissions", prompt2], {
4952
5570
  stdio: ["ignore", "pipe", "pipe"]
4953
5571
  });
@@ -4960,7 +5578,7 @@ function runClaude(prompt2) {
4960
5578
  errOutput += d.toString();
4961
5579
  });
4962
5580
  child.on("exit", (code) => {
4963
- if (code === 0) resolve7(output.trim());
5581
+ if (code === 0) resolve8(output.trim());
4964
5582
  else reject(new Error(`claude exited with code ${code}
4965
5583
  ${errOutput.trim()}`));
4966
5584
  });
@@ -5398,9 +6016,229 @@ var doctorCommand = new Command25("doctor").description("Diagnose Mr. Manager CL
5398
6016
  process.exit(1);
5399
6017
  });
5400
6018
 
6019
+ // cli/commands/prompt-audit.ts
6020
+ import { Command as Command26 } from "commander";
6021
+ import { resolve as resolve7 } from "path";
6022
+ import { existsSync as existsSync16, readFileSync as readFileSync12 } from "fs";
6023
+ function auditLine(label, tokens) {
6024
+ const bar = "\u2588".repeat(Math.min(60, Math.round(tokens / 200)));
6025
+ return ` ${label.padEnd(30)} ${formatTokenCount(tokens).padStart(8)} ${bar}`;
6026
+ }
6027
+ var promptAuditCommand = new Command26("prompt-audit").description("Dry-run prompt construction and report estimated token counts by job type").option("--task <id>", "Audit prompts for a specific task ID").option("--all", "Audit all supported job types with representative data", false).option("--json", "Output as JSON instead of plain text", false).action(async (opts) => {
6028
+ const results = [];
6029
+ if (opts.task) {
6030
+ try {
6031
+ const task = await api.get(`/api/tasks/${opts.task}`);
6032
+ const [_subtasks, protoRefs, updates, resources, skills] = await Promise.all([
6033
+ api.get(`/api/tasks/${task.id}/subtasks`).catch(() => []),
6034
+ api.get(`/api/tasks/${task.id}/prototypes`).catch(() => []),
6035
+ api.get(`/api/tasks/${task.id}/updates`).catch(() => []),
6036
+ api.get(`/api/tasks/${task.id}/resources`).catch(() => []),
6037
+ api.get(`/api/tasks/${task.id}/skills`).catch(() => [])
6038
+ ]);
6039
+ const feedbackUpdates = updates.filter((u) => u.source === "user");
6040
+ const sections = [];
6041
+ const notesContent = task.prdContent ? `
6042
+
6043
+ ## PRD (Product Requirements Document)
6044
+
6045
+ ${task.prdContent}` : task.notes ? `
6046
+
6047
+ Task notes:
6048
+ ${task.notes}` : "";
6049
+ sections.push({ name: "task-notes/prd", tokens: estimateTokens(notesContent) });
6050
+ let protoContent = "";
6051
+ for (const ref of protoRefs) {
6052
+ const files = ref.prototype?.files ?? [];
6053
+ for (const f of files) {
6054
+ protoContent += f.content;
6055
+ }
6056
+ }
6057
+ sections.push({ name: "prototypes", tokens: estimateTokens(protoContent) });
6058
+ let skillContent = "";
6059
+ for (const s of skills) {
6060
+ skillContent += s.skill.content;
6061
+ }
6062
+ sections.push({ name: "skills", tokens: estimateTokens(skillContent) });
6063
+ let resourceContent = "";
6064
+ for (const r of resources) {
6065
+ resourceContent += r.content.slice(0, 8e3);
6066
+ }
6067
+ sections.push({ name: "resources", tokens: estimateTokens(resourceContent) });
6068
+ let feedbackContent = "";
6069
+ for (const f of feedbackUpdates) {
6070
+ feedbackContent += f.message;
6071
+ }
6072
+ sections.push({ name: "feedback", tokens: estimateTokens(feedbackContent) });
6073
+ const config = loadConfig();
6074
+ const repoDir = Object.entries(config.directories).find(([, pid]) => pid === task.projectId)?.[0];
6075
+ if (repoDir) {
6076
+ const featuresPath = resolve7(repoDir, ".mr-features.md");
6077
+ if (existsSync16(featuresPath)) {
6078
+ const featuresContent = readFileSync12(featuresPath, "utf-8");
6079
+ sections.push({ name: "features-doc", tokens: estimateTokens(featuresContent) });
6080
+ }
6081
+ }
6082
+ sections.push({ name: "static-instructions (system)", tokens: estimateTokens(
6083
+ "status-updates + screenshots + test-plan + no-mr + features-workflow"
6084
+ ) });
6085
+ const totalTokens = sections.reduce((sum, s) => sum + s.tokens, 0);
6086
+ const promptTokens = sections.filter((s) => !s.name.includes("system")).reduce((sum, s) => sum + s.tokens, 0);
6087
+ const systemTokens = totalTokens - promptTokens;
6088
+ results.push({
6089
+ jobType: "execution",
6090
+ identifier: task.id.slice(0, 8),
6091
+ promptTokens,
6092
+ systemTokens,
6093
+ totalTokens,
6094
+ sections
6095
+ });
6096
+ if (task.prdContent && feedbackUpdates.length > 0) {
6097
+ const prdSections = [
6098
+ { name: "task-notes", tokens: estimateTokens(task.notes ?? "") },
6099
+ { name: "existing-prd", tokens: estimateTokens(task.prdContent) },
6100
+ { name: "feedback", tokens: estimateTokens(feedbackContent) },
6101
+ { name: "prd-format (system)", tokens: estimateTokens("prd-format + open-questions") }
6102
+ ];
6103
+ const prdTotal = prdSections.reduce((sum, s) => sum + s.tokens, 0);
6104
+ results.push({
6105
+ jobType: "prd-revision",
6106
+ identifier: task.id.slice(0, 8),
6107
+ promptTokens: prdTotal,
6108
+ systemTokens: 0,
6109
+ totalTokens: prdTotal,
6110
+ sections: prdSections
6111
+ });
6112
+ }
6113
+ } catch (err) {
6114
+ console.error(`Failed to fetch task: ${err.message}`);
6115
+ process.exit(1);
6116
+ }
6117
+ } else if (opts.all) {
6118
+ const syntheticSections = [
6119
+ {
6120
+ jobType: "execution",
6121
+ description: "Task execution prompt (baseline without attachments)",
6122
+ sections: [
6123
+ { name: "core-prompt", tokens: 800 },
6124
+ { name: "instructions", tokens: 600 },
6125
+ { name: "pr-template", tokens: 400 },
6126
+ { name: "features-ref", tokens: 50 }
6127
+ ]
6128
+ },
6129
+ {
6130
+ jobType: "execution+prd",
6131
+ description: "Task execution with full PRD",
6132
+ sections: [
6133
+ { name: "core-prompt", tokens: 800 },
6134
+ { name: "prd-content", tokens: 4e3 },
6135
+ { name: "instructions", tokens: 600 }
6136
+ ]
6137
+ },
6138
+ {
6139
+ jobType: "prd-generation",
6140
+ description: "PRD generation prompt",
6141
+ sections: [
6142
+ { name: "core-prompt", tokens: 300 },
6143
+ { name: "task-notes", tokens: 500 },
6144
+ { name: "format-ref", tokens: 50 }
6145
+ ]
6146
+ },
6147
+ {
6148
+ jobType: "prd-revision",
6149
+ description: "PRD revision (delta mode)",
6150
+ sections: [
6151
+ { name: "core-prompt", tokens: 300 },
6152
+ { name: "prd-summary", tokens: 200 },
6153
+ { name: "feedback", tokens: 300 },
6154
+ { name: "prd-file-ref", tokens: 30 }
6155
+ ]
6156
+ },
6157
+ {
6158
+ jobType: "prototype",
6159
+ description: "Prototype generation prompt",
6160
+ sections: [
6161
+ { name: "core-prompt", tokens: 600 },
6162
+ { name: "variant-steps", tokens: 200 }
6163
+ ]
6164
+ },
6165
+ {
6166
+ jobType: "refinement",
6167
+ description: "Prototype refinement (file-ref mode)",
6168
+ sections: [
6169
+ { name: "core-prompt", tokens: 600 },
6170
+ { name: "parent-file-refs", tokens: 50 },
6171
+ { name: "feedback", tokens: 200 }
6172
+ ]
6173
+ },
6174
+ {
6175
+ jobType: "scanner-synthesis",
6176
+ description: "Scanner synthesis prompt (tightened caps)",
6177
+ sections: [
6178
+ { name: "context", tokens: 400 },
6179
+ { name: "routes+models", tokens: 300 },
6180
+ { name: "components", tokens: 150 },
6181
+ { name: "commits", tokens: 160 },
6182
+ { name: "crawl-results", tokens: 500 },
6183
+ { name: "prior-findings", tokens: 100 },
6184
+ { name: "instructions", tokens: 500 }
6185
+ ]
6186
+ },
6187
+ {
6188
+ jobType: "idea",
6189
+ description: "Idea generation prompt",
6190
+ sections: [
6191
+ { name: "core-prompt", tokens: 500 },
6192
+ { name: "idea-desc", tokens: 200 }
6193
+ ]
6194
+ },
6195
+ {
6196
+ jobType: "repo-creation",
6197
+ description: "Repository creation prompt",
6198
+ sections: [
6199
+ { name: "core-prompt", tokens: 400 },
6200
+ { name: "project-desc", tokens: 200 }
6201
+ ]
6202
+ }
6203
+ ];
6204
+ console.log("Estimated prompt sizes by job type (representative baselines)");
6205
+ console.log("\u2550".repeat(70));
6206
+ for (const entry of syntheticSections) {
6207
+ const total = entry.sections.reduce((sum, s) => sum + s.tokens, 0);
6208
+ console.log(`
6209
+ ${entry.jobType} \u2014 ${entry.description}`);
6210
+ console.log(` Total: ${formatTokenCount(total)} tokens`);
6211
+ for (const s of entry.sections) {
6212
+ console.log(auditLine(s.name, s.tokens));
6213
+ }
6214
+ }
6215
+ console.log("");
6216
+ return;
6217
+ } else {
6218
+ console.log("Usage: mr prompt-audit --task <id> or mr prompt-audit --all");
6219
+ console.log("\nDry-run prompt construction and report estimated token counts.");
6220
+ return;
6221
+ }
6222
+ if (opts.json) {
6223
+ console.log(JSON.stringify(results, null, 2));
6224
+ } else {
6225
+ console.log("Prompt Audit Report");
6226
+ console.log("\u2550".repeat(70));
6227
+ for (const r of results) {
6228
+ console.log(`
6229
+ ${r.jobType} [${r.identifier}]`);
6230
+ console.log(` Total: ${formatTokenCount(r.totalTokens)} tokens (prompt=${formatTokenCount(r.promptTokens)} system=${formatTokenCount(r.systemTokens)})`);
6231
+ for (const s of r.sections) {
6232
+ console.log(auditLine(s.name, s.tokens));
6233
+ }
6234
+ }
6235
+ console.log("");
6236
+ }
6237
+ });
6238
+
5401
6239
  // cli/index.ts
5402
6240
  var configPath = join12(homedir3(), ".mr-manager", "config.json");
5403
- var isFirstRun = !existsSync16(configPath);
6241
+ var isFirstRun = !existsSync17(configPath);
5404
6242
  var userArgs = process.argv.slice(2);
5405
6243
  var bypassCommands = /* @__PURE__ */ new Set(["login", "init", "auth", "help", "--help", "-h", "--version", "-V", "doctor", "setup"]);
5406
6244
  var shouldBypass = userArgs.length > 0 && bypassCommands.has(userArgs[0]);
@@ -5436,7 +6274,7 @@ if (isFirstRun && !shouldBypass) {
5436
6274
  console.log("");
5437
6275
  process.exit(0);
5438
6276
  }
5439
- var program = new Command26();
6277
+ var program = new Command27();
5440
6278
  program.name("mr").description("Mr. Manager - Task and project management CLI").version(CLI_VERSION);
5441
6279
  program.addCommand(initCommand);
5442
6280
  program.addCommand(authCommand);
@@ -5466,4 +6304,5 @@ program.addCommand(noMrCommand);
5466
6304
  program.addCommand(scanCommand);
5467
6305
  program.addCommand(ideaCommand);
5468
6306
  program.addCommand(doctorCommand);
6307
+ program.addCommand(promptAuditCommand);
5469
6308
  program.parse();