@difflab/pi 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/README.md +11 -9
  2. package/agents/diffpi-orchestrator.md +6 -4
  3. package/agents/diffpi-planner.md +3 -3
  4. package/agents/diffpi-reviewer.md +4 -4
  5. package/agents/diffpi-worker.md +1 -1
  6. package/dist/assets.d.ts +0 -1
  7. package/dist/assets.d.ts.map +1 -1
  8. package/dist/cli.js +417 -84
  9. package/dist/commands/plan.d.ts +2 -2
  10. package/dist/commands/plan.d.ts.map +1 -1
  11. package/dist/commands/review.d.ts +2 -2
  12. package/dist/commands/review.d.ts.map +1 -1
  13. package/dist/environment.d.ts +2 -0
  14. package/dist/environment.d.ts.map +1 -1
  15. package/dist/extensions/index.js +1778 -3799
  16. package/dist/extensions/tuicrx.d.ts +8 -1
  17. package/dist/extensions/tuicrx.d.ts.map +1 -1
  18. package/dist/index.d.ts +8 -7
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +891 -292
  21. package/dist/plan/markdown.d.ts +4 -1
  22. package/dist/plan/markdown.d.ts.map +1 -1
  23. package/dist/{tools/plan-schema.d.ts → plan/schema.d.ts} +113 -75
  24. package/dist/plan/schema.d.ts.map +1 -0
  25. package/dist/plan/store.d.ts +39 -1
  26. package/dist/plan/store.d.ts.map +1 -1
  27. package/dist/plan/types.d.ts +27 -3
  28. package/dist/plan/types.d.ts.map +1 -1
  29. package/dist/review/github-review-backend.d.ts.map +1 -1
  30. package/dist/review/gitlab-review-backend.d.ts.map +1 -1
  31. package/dist/review/index.d.ts +6 -6
  32. package/dist/review/index.d.ts.map +1 -1
  33. package/dist/review/local-review-backend.d.ts +3 -0
  34. package/dist/review/local-review-backend.d.ts.map +1 -0
  35. package/dist/review/review-backend.d.ts +3 -2
  36. package/dist/review/review-backend.d.ts.map +1 -1
  37. package/dist/review/review-markdown.d.ts +4 -1
  38. package/dist/review/review-markdown.d.ts.map +1 -1
  39. package/dist/review/review-state.d.ts +20 -0
  40. package/dist/review/review-state.d.ts.map +1 -0
  41. package/dist/review/types.d.ts +28 -0
  42. package/dist/review/types.d.ts.map +1 -1
  43. package/dist/store.d.ts +2 -0
  44. package/dist/store.d.ts.map +1 -1
  45. package/dist/tools/index.js +1632 -575
  46. package/dist/tools/plan.d.ts.map +1 -1
  47. package/dist/tools/review.d.ts +38 -0
  48. package/dist/tools/review.d.ts.map +1 -1
  49. package/package.json +2 -4
  50. package/skills/plan/SKILL.md +8 -14
  51. package/skills/plan/references/design-quality.md +41 -0
  52. package/skills/plan/references/workflows/annotate.md +11 -0
  53. package/skills/plan/references/workflows/finalize.md +7 -0
  54. package/skills/plan/references/workflows/go.md +8 -0
  55. package/skills/plan/references/workflows/help.md +10 -0
  56. package/skills/plan/references/workflows/init.md +5 -0
  57. package/skills/plan/references/workflows/new.md +7 -0
  58. package/skills/plan/references/workflows/update.md +7 -0
  59. package/skills/review/SKILL.md +7 -7
  60. package/skills/review/references/review-standards.md +8 -1
  61. package/skills/review/references/workflows/address.md +11 -0
  62. package/skills/review/references/workflows/auto.md +18 -0
  63. package/skills/review/references/workflows/complete.md +7 -0
  64. package/skills/review/references/workflows/edit.md +7 -0
  65. package/skills/review/references/workflows/help.md +36 -0
  66. package/skills/review/references/workflows/merge.md +6 -0
  67. package/skills/review/references/workflows/new.md +19 -0
  68. package/skills/review/references/workflows/open.md +3 -0
  69. package/skills/review/references/workflows/publish.md +8 -0
  70. package/skills/review/references/workflows/status.md +3 -0
  71. package/templates/plan/PLAN.md +2 -2
  72. package/templates/plan/implementation.md +16 -10
  73. package/dist/commands.d.ts +0 -22
  74. package/dist/commands.d.ts.map +0 -1
  75. package/dist/extensions/cmdtsx.d.ts +0 -2
  76. package/dist/extensions/cmdtsx.d.ts.map +0 -1
  77. package/dist/tools/plan-schema.d.ts.map +0 -1
  78. package/dist/workflow.d.ts +0 -80
  79. package/dist/workflow.d.ts.map +0 -1
  80. package/workflows/plan/annotate.md +0 -13
  81. package/workflows/plan/finalize.md +0 -15
  82. package/workflows/plan/go.md +0 -20
  83. package/workflows/plan/help.md +0 -20
  84. package/workflows/plan/init.md +0 -13
  85. package/workflows/plan/new.md +0 -20
  86. package/workflows/plan/update.md +0 -18
  87. package/workflows/review/address.md +0 -8
  88. package/workflows/review/auto.md +0 -8
  89. package/workflows/review/complete.md +0 -7
  90. package/workflows/review/edit.md +0 -7
  91. package/workflows/review/help.md +0 -14
  92. package/workflows/review/merge.md +0 -6
  93. package/workflows/review/new.md +0 -7
  94. package/workflows/review/publish.md +0 -6
@@ -503,6 +503,16 @@ function diffpiLaunchName(cwd, workflow) {
503
503
  }
504
504
  async function openFileAdjacent(path, opts) {
505
505
  const env = opts.env ?? process.env;
506
+ const mux = detectMux(env);
507
+ if (mux !== "none") {
508
+ const editor = await resolveEditor(env);
509
+ if (editor) {
510
+ const command = persistentEditorArgs(editor, path, opts.cwd, env.SHELL);
511
+ const opened = await openMuxTab(mux, command, opts.cwd, opts.name ?? "plan", [editor, path].join(" "), command);
512
+ if (opened)
513
+ return opened;
514
+ }
515
+ }
506
516
  const ide = detectIde(env);
507
517
  if (ide !== "unknown") {
508
518
  const ideCommand = { zed: "zed", vscode: "code", cursor: "cursor", windsurf: "windsurf", jetbrains: "idea" }[ide];
@@ -512,16 +522,6 @@ async function openFileAdjacent(path, opts) {
512
522
  return { launched: true, via: ide, command: `${ideCommand} ${path}` };
513
523
  }
514
524
  }
515
- const mux = detectMux(env);
516
- if (mux !== "none") {
517
- const editor = await resolveEditor(env);
518
- if (editor) {
519
- const command = [editor, path];
520
- const opened = await openMuxTab(mux, command, opts.cwd, opts.name ?? "plan", command.join(" "));
521
- if (opened)
522
- return opened;
523
- }
524
- }
525
525
  return { launched: false, via: "print", command: path, reason: "No supported IDE or multiplexer was available." };
526
526
  }
527
527
  async function openInNewTab(command, opts) {
@@ -556,10 +556,15 @@ async function openInNewTab(command, opts) {
556
556
  function screenWindowArgs(command, cwd, name) {
557
557
  return ["-X", "screen", "-t", name, "sh", "-lc", 'cd -- "$1" && shift && exec "$@"', "sh", cwd, ...command];
558
558
  }
559
+ function persistentEditorArgs(editor, path, cwd, shell = "sh") {
560
+ return ["bash", "-lc", 'cd -- "$1" && shift && "$@"; exec "$0" -i', shell, cwd, editor, path];
561
+ }
559
562
  async function resolveEditor(env) {
560
- const configured = (env.VISUAL ?? env.EDITOR)?.trim().split(/\s+/)[0];
561
- if (configured && await findExecutable(configured))
562
- return configured;
563
+ for (const configured of [env.EDITOR, env.VISUAL]) {
564
+ const editor = configured?.trim();
565
+ if (editor && await findExecutable(editor))
566
+ return editor;
567
+ }
563
568
  for (const candidate of ["hx", "nvim", "vim"])
564
569
  if (await findExecutable(candidate))
565
570
  return candidate;
@@ -576,7 +581,7 @@ async function packageVersion() {
576
581
  throw new Error("Cannot resolve the installed @difflab/pi version.");
577
582
  return value.version;
578
583
  }
579
- async function openMuxTab(mux, command, cwd, name, printable) {
584
+ async function openMuxTab(mux, command, cwd, name, printable, tmuxCommand) {
580
585
  if (mux === "zellij" && await findExecutable("zellij")) {
581
586
  const result = await run("zellij", ["action", "new-tab", "--cwd", cwd, "--name", name, "--", ...command]);
582
587
  if (result.code === 0)
@@ -586,7 +591,7 @@ async function openMuxTab(mux, command, cwd, name, printable) {
586
591
  return { launched: true, via: "zellij-run", command: printable };
587
592
  }
588
593
  if (mux === "tmux" && await findExecutable("tmux")) {
589
- const result = await run("tmux", ["new-window", "-c", cwd, "-n", name, printable]);
594
+ const result = tmuxCommand ? await run("tmux", ["new-window", "-c", cwd, "-n", name, ...tmuxCommand]) : await run("tmux", ["new-window", "-c", cwd, "-n", name, printable]);
590
595
  if (result.code === 0)
591
596
  return { launched: true, via: "tmux", command: printable };
592
597
  }
@@ -1069,6 +1074,18 @@ async function reviewsDir(cwd, homeDir = homedir2()) {
1069
1074
  await mkdir2(dir, { recursive: true });
1070
1075
  return dir;
1071
1076
  }
1077
+ async function completedReviewsDir(cwd, homeDir = homedir2()) {
1078
+ const store = await ensureStore(cwd, homeDir);
1079
+ const dir = join6(store.link, "reviews");
1080
+ await mkdir2(dir, { recursive: true });
1081
+ return dir;
1082
+ }
1083
+ async function sessionsDir(cwd, homeDir = homedir2()) {
1084
+ const store = await ensureStore(cwd, homeDir);
1085
+ const dir = join6(store.link, "sessions");
1086
+ await mkdir2(dir, { recursive: true });
1087
+ return dir;
1088
+ }
1072
1089
  async function assertStoreLink(path, dest) {
1073
1090
  const entry = await lstat(path);
1074
1091
  if (!entry.isSymbolicLink())
@@ -1273,7 +1290,7 @@ function sanitize(value) {
1273
1290
  }
1274
1291
 
1275
1292
  // src/tools/plan.ts
1276
- import { join as join14 } from "node:path";
1293
+ import { join as join15 } from "node:path";
1277
1294
  import { pathToFileURL } from "node:url";
1278
1295
  import { defineTool as defineTool5 } from "@earendil-works/pi-coding-agent";
1279
1296
  import { z as z7 } from "zod";
@@ -1510,6 +1527,9 @@ async function discoverMiseTasks(cwd) {
1510
1527
 
1511
1528
  // src/plan/markdown.ts
1512
1529
  var import_mdast_builder = __toESM(require_src(), 1);
1530
+ import { createHash as createHash2 } from "node:crypto";
1531
+ import { readFile as readFile5, readdir } from "node:fs/promises";
1532
+ import { join as join10 } from "node:path";
1513
1533
 
1514
1534
  // ../../node_modules/zwitch/index.js
1515
1535
  var own = {}.hasOwnProperty;
@@ -6149,6 +6169,8 @@ function isUint8Array2(value) {
6149
6169
  var PLAN_MARKER = /<!-- diffpi-plan: (\{[^\n]+\}) -->/;
6150
6170
  var PHASE_MARKER = /<!-- diffpi-phase: (\{[^\n]+\}) -->/g;
6151
6171
  var TASK_MARKER = /<!-- diffpi-task: (\{[^\n]+\}) -->/g;
6172
+ var BRIEF_MARKER = /<!-- diffpi-implementation: (\{[^\n]+\}) -->/;
6173
+ var BRIEF_TASK_MARKER = /<!-- diffpi-brief-task: (\{[^\n]+\}) -->/g;
6152
6174
  var SUPPORTED_SCHEMA = 1;
6153
6175
  function countDesignWords(plan) {
6154
6176
  return [plan.design.bigIdeas, plan.design.keyApiUpdates, plan.design.consequences].join(" ").trim().split(/\s+/).filter(Boolean).length;
@@ -6177,11 +6199,13 @@ function validatePlanDocument(plan, options = {}) {
6177
6199
  if (!taskIds.has(dependency))
6178
6200
  add("dangling-dependency", "error", `Task ${task.id} depends on missing ${dependency}.`);
6179
6201
  }
6180
- if (options.strict && task.acceptanceCriteria.length === 0)
6181
- add("acceptance", "error", `Task ${task.id} has no acceptance criteria.`, task.id);
6202
+ if (options.strict && isPlaceholder(task.title))
6203
+ add("placeholder", "error", `Task ${task.id} has placeholder content.`, task.id);
6182
6204
  }
6183
6205
  if (options.strict && phase.tasks.length === 0)
6184
6206
  add("empty-phase", "error", `Phase ${phase.id} has no tasks.`, phase.id);
6207
+ if (options.strict && (isPlaceholder(phase.title) || isPlaceholder(phase.objective)))
6208
+ add("placeholder", "error", `Phase ${phase.id} has placeholder content.`, phase.id);
6185
6209
  }
6186
6210
  for (const cycle of dependencyCycles(plan))
6187
6211
  add("dependency-cycle", "error", `Dependency cycle: ${cycle.join(" -> ")}.`);
@@ -6190,10 +6214,140 @@ function validatePlanDocument(plan, options = {}) {
6190
6214
  add("design-length", "warning", `Design is ${designWords} words; prefer 300 or fewer.`);
6191
6215
  if (options.strict && designWords > 800)
6192
6216
  add("design-too-long", "error", `Design is ${designWords} words; finalization allows at most 800.`);
6193
- if (options.strict && plan.phases.length === 0)
6194
- add("no-phases", "error", "Finalization requires at least one phase.");
6217
+ if (options.strict) {
6218
+ if (plan.phases.length === 0)
6219
+ add("no-phases", "error", "Finalization requires at least one phase.");
6220
+ if (isPlaceholder(plan.intent))
6221
+ add("placeholder", "error", "Intent must contain concrete content.", "intent");
6222
+ if (!plan.requirements.length || plan.requirements.some(isPlaceholder))
6223
+ add("requirements", "error", "Requirements must contain concrete content.", "requirements");
6224
+ for (const [key, value] of Object.entries(plan.design)) {
6225
+ if (isPlaceholder(value))
6226
+ add("design", "error", `Design/${key} must contain concrete content.`, `design.${key}`);
6227
+ }
6228
+ }
6229
+ return issues;
6230
+ }
6231
+ function validatePlanBriefs(plan, briefs) {
6232
+ const issues = [];
6233
+ const phaseIds = plan.phases.map((phase) => phase.id);
6234
+ const briefIds = briefs.map((brief) => brief.phaseId);
6235
+ if (!sameIds(phaseIds, briefIds))
6236
+ issues.push({
6237
+ code: "brief-phase-ids",
6238
+ severity: "error",
6239
+ message: `Brief phase IDs must exactly match plan phases in order: ${phaseIds.join(", ")}.`
6240
+ });
6241
+ for (const [index, phase] of plan.phases.entries()) {
6242
+ const brief = briefs[index];
6243
+ if (!brief || brief.phaseId !== phase.id)
6244
+ continue;
6245
+ if (isPlaceholder(brief.summary))
6246
+ issues.push({ code: "brief-placeholder", severity: "error", message: `Brief ${phase.id} needs a summary.` });
6247
+ const taskIds = phase.tasks.map((task) => task.id);
6248
+ const briefTaskIds = brief.tasks.map((task) => task.taskId);
6249
+ if (!sameIds(taskIds, briefTaskIds))
6250
+ issues.push({
6251
+ code: "brief-task-ids",
6252
+ severity: "error",
6253
+ message: `Brief ${phase.id} task IDs must exactly match phase tasks in order: ${taskIds.join(", ")}.`
6254
+ });
6255
+ for (const task of brief.tasks) {
6256
+ for (const [field, values] of [
6257
+ ["ordered steps", task.steps],
6258
+ ["file scopes", task.fileScopes],
6259
+ ["acceptance criteria", task.acceptanceCriteria]
6260
+ ]) {
6261
+ if (!values.length || values.some(isPlaceholder))
6262
+ issues.push({
6263
+ code: "brief-incomplete",
6264
+ severity: "error",
6265
+ message: `Brief task ${task.taskId} needs concrete ${field}.`,
6266
+ path: task.taskId
6267
+ });
6268
+ }
6269
+ }
6270
+ for (const [field, values] of [
6271
+ ["API changes", brief.apiChanges],
6272
+ ["libraries", brief.libraries],
6273
+ ["constraints", brief.constraints]
6274
+ ]) {
6275
+ if (values.some(isPlaceholder))
6276
+ issues.push({
6277
+ code: "brief-placeholder",
6278
+ severity: "error",
6279
+ message: `Brief ${phase.id} has placeholder ${field}.`,
6280
+ path: phase.id
6281
+ });
6282
+ }
6283
+ }
6284
+ return issues;
6285
+ }
6286
+ async function validatePlanRecord(record, options = {}) {
6287
+ const issues = validatePlanDocument(record.document, options);
6288
+ if (!options.strict)
6289
+ return issues;
6290
+ await validateImplementationDirectory(record.dir, record.document, issues, "latest");
6291
+ if (options.checkSnapshots !== false)
6292
+ await validateRevisionSnapshots(record, issues);
6195
6293
  return issues;
6196
6294
  }
6295
+ function renderImplementationBrief(planRevision, ordinal, phase, brief) {
6296
+ const marker = { schemaVersion: 1, planRevision, ordinal, phaseId: phase.id };
6297
+ const tasks = phase.tasks.map((task, index) => {
6298
+ const details = brief.tasks[index];
6299
+ if (!details || details.taskId !== task.id)
6300
+ throw new Error(`Missing implementation details for ${task.id}.`);
6301
+ return `<!-- diffpi-brief-task: ${json({ id: task.id })} -->
6302
+ ### Task: ${task.title}
6303
+
6304
+ #### Ordered Steps
6305
+
6306
+ ${bulletList(details.steps)}
6307
+
6308
+ #### File Scopes
6309
+
6310
+ ${bulletList(details.fileScopes)}
6311
+
6312
+ #### Acceptance Criteria
6313
+
6314
+ ${bulletList(details.acceptanceCriteria)}
6315
+
6316
+ <!-- /diffpi-brief-task -->`;
6317
+ }).join(`
6318
+
6319
+ `);
6320
+ return `<!-- diffpi-implementation: ${json(marker)} -->
6321
+ # Phase ${ordinal}: ${phase.title}
6322
+
6323
+ - **Phase ID:** ${phase.id}
6324
+ - **Plan Revision:** ${planRevision}
6325
+
6326
+ ## Summary
6327
+
6328
+ ${brief.summary}
6329
+
6330
+ ## Objective
6331
+
6332
+ ${phase.objective}
6333
+
6334
+ ## Tasks
6335
+
6336
+ ${tasks}
6337
+
6338
+ ## API Changes
6339
+
6340
+ ${bulletList(brief.apiChanges, "None.")}
6341
+
6342
+ ## Libraries and Algorithms
6343
+
6344
+ ${bulletList(brief.libraries, "None.")}
6345
+
6346
+ ## Implementation Constraints
6347
+
6348
+ ${bulletList(brief.constraints, "None.")}
6349
+ `;
6350
+ }
6197
6351
  function renderPlanDocument(plan, previousSource) {
6198
6352
  if (previousSource && canPatch(previousSource, plan))
6199
6353
  return patchMarkers(previousSource, plan);
@@ -6202,6 +6356,8 @@ function renderPlanDocument(plan, previousSource) {
6202
6356
  id: plan.id,
6203
6357
  revision: plan.revision,
6204
6358
  branch: plan.branch,
6359
+ issueId: plan.issueId,
6360
+ issueUrl: plan.issueUrl,
6205
6361
  status: plan.status,
6206
6362
  execution: plan.execution,
6207
6363
  createdAt: plan.createdAt,
@@ -6210,6 +6366,8 @@ function renderPlanDocument(plan, previousSource) {
6210
6366
  const metadata = import_mdast_builder.list("unordered", [
6211
6367
  ["Plan ID", plan.id],
6212
6368
  ["Branch", plan.branch],
6369
+ ...plan.issueId ? [["Issue", plan.issueId]] : [],
6370
+ ...plan.issueUrl ? [["Issue URL", plan.issueUrl]] : [],
6213
6371
  ["Status", plan.status],
6214
6372
  ["Revision", String(plan.revision)]
6215
6373
  ].map(([label, value]) => import_mdast_builder.listItem(import_mdast_builder.paragraph([import_mdast_builder.strong(import_mdast_builder.text(`${label}:`)), import_mdast_builder.text(` ${value}`)]))));
@@ -6231,7 +6389,7 @@ function renderPlanDocument(plan, previousSource) {
6231
6389
  import_mdast_builder.heading(3, import_mdast_builder.text("Consequences")),
6232
6390
  import_mdast_builder.html(plan.design.consequences || "<!-- Describe trade-offs and limitations. -->"),
6233
6391
  import_mdast_builder.heading(2, import_mdast_builder.text("Implementation")),
6234
- ...plan.phases.length ? plan.phases.flatMap((phase) => [import_mdast_builder.html(renderPhase(phase))]) : [import_mdast_builder.html("<!-- Add phases with plan_add_phase. -->")],
6392
+ ...plan.phases.length ? plan.phases.flatMap((phase) => [import_mdast_builder.html(renderPhase(phase))]) : [import_mdast_builder.html("<!-- Add phases with plan_apply_revision. -->")],
6235
6393
  import_mdast_builder.heading(2, import_mdast_builder.text("References")),
6236
6394
  references
6237
6395
  ]);
@@ -6305,10 +6463,7 @@ function renderTask(task) {
6305
6463
  const checked = task.status === "completed" || task.status === "skipped" ? "x" : " ";
6306
6464
  return `<!-- diffpi-task: ${json(marker)} -->
6307
6465
  - [${checked}] **${task.title}**
6308
- ${taskList("Steps", task.steps ?? [])}
6309
6466
  - Dependencies: ${list3(task.dependencies)}
6310
- ${taskList("File scopes", task.fileScopes)}
6311
- ${taskList("Acceptance criteria", task.acceptanceCriteria)}
6312
6467
  <!-- /diffpi-task -->`;
6313
6468
  }
6314
6469
  function parsePhases(input, ref) {
@@ -6358,10 +6513,7 @@ function parseTasks(input, ref) {
6358
6513
  return {
6359
6514
  ...marker,
6360
6515
  title,
6361
- steps: parseListValue(body, "Steps"),
6362
- dependencies: parseListValue(body, "Dependencies"),
6363
- fileScopes: parseListValue(body, "File scopes"),
6364
- acceptanceCriteria: parseListValue(body, "Acceptance criteria")
6516
+ dependencies: parseListValue(body, "Dependencies")
6365
6517
  };
6366
6518
  });
6367
6519
  assertUniqueIds(tasks.map((task) => task.id), "task id");
@@ -6388,6 +6540,8 @@ function patchMarkers(source, plan) {
6388
6540
  id: plan.id,
6389
6541
  revision: plan.revision,
6390
6542
  branch: plan.branch,
6543
+ issueId: plan.issueId,
6544
+ issueUrl: plan.issueUrl,
6391
6545
  status: plan.status,
6392
6546
  execution: plan.execution,
6393
6547
  createdAt: plan.createdAt,
@@ -6437,19 +6591,12 @@ function contentShape(plan) {
6437
6591
  requirements: plan.requirements,
6438
6592
  design: plan.design,
6439
6593
  references: plan.references,
6440
- phases: plan.phases.map(({ id, title, objective, dependencies, tasks }) => ({
6441
- id,
6442
- title,
6443
- objective,
6444
- dependencies,
6445
- tasks: tasks.map(({ id: taskId, title: taskTitle, steps, dependencies: taskDependencies, fileScopes, acceptanceCriteria }) => ({
6446
- id: taskId,
6447
- title: taskTitle,
6448
- steps,
6449
- dependencies: taskDependencies,
6450
- fileScopes,
6451
- acceptanceCriteria
6452
- }))
6594
+ phases: plan.phases.map((phase) => ({
6595
+ id: phase.id,
6596
+ title: phase.title,
6597
+ objective: phase.objective,
6598
+ dependencies: phase.dependencies,
6599
+ tasks: phase.tasks.map(({ id, title, dependencies }) => ({ id, title, dependencies }))
6453
6600
  }))
6454
6601
  };
6455
6602
  }
@@ -6479,6 +6626,152 @@ function dependencyCycles(plan) {
6479
6626
  walk(id, []);
6480
6627
  return cycles;
6481
6628
  }
6629
+ async function validateRevisionSnapshots(record, issues) {
6630
+ const revisionsDir = join10(record.dir, "revisions");
6631
+ let entries;
6632
+ try {
6633
+ entries = await readdir(revisionsDir);
6634
+ } catch {
6635
+ issues.push({ code: "snapshot-missing", severity: "error", message: "Missing revisions directory." });
6636
+ return;
6637
+ }
6638
+ const expected = Array.from({ length: record.document.revision + 1 }, (_, index) => String(index));
6639
+ if (!sameIds(expected, entries.filter((entry) => /^\d+$/.test(entry)).sort((a, b) => Number(a) - Number(b))))
6640
+ issues.push({
6641
+ code: "snapshot-sequence",
6642
+ severity: "error",
6643
+ message: `Revision snapshots must be exactly ${expected.join(", ")}.`,
6644
+ path: revisionsDir
6645
+ });
6646
+ for (const entry of entries) {
6647
+ if (!/^\d+$/.test(entry))
6648
+ issues.push({ code: "snapshot-entry", severity: "error", message: `Unexpected revisions entry: ${entry}.` });
6649
+ }
6650
+ for (const revision of expected) {
6651
+ const dir = join10(revisionsDir, revision);
6652
+ try {
6653
+ const [request, metadataSource, planSource] = await Promise.all([
6654
+ readFile5(join10(dir, "request.md"), "utf8"),
6655
+ readFile5(join10(dir, "metadata.json"), "utf8"),
6656
+ readFile5(join10(dir, "PLAN.md"), "utf8")
6657
+ ]);
6658
+ if (isPlaceholder(request))
6659
+ issues.push({ code: "snapshot-request", severity: "error", message: `Revision ${revision} request is empty.` });
6660
+ const metadata = JSON.parse(metadataSource);
6661
+ const annotation = metadata.requestKind === "annotation" ? /^## Original annotation\n([\s\S]*?)\n\n## LLM response\n([\s\S]*)$/.exec(request) : undefined;
6662
+ const requestText = annotation?.[1];
6663
+ const responseText = annotation?.[2];
6664
+ if (metadata.schemaVersion !== 1 || metadata.id !== record.id || metadata.revision !== Number(revision) || !["user", "annotation", "blocker"].includes(metadata.requestKind) || (metadata.requestKind === "annotation" ? !annotation || !requestText?.trim() || !responseText?.trim() || metadata.requestSha256 !== sha256(requestText) || metadata.originalAnnotationSha256 !== sha256(requestText) || metadata.responseSha256 !== sha256(responseText) : metadata.requestSha256 !== sha256(request)))
6665
+ issues.push({
6666
+ code: "snapshot-metadata",
6667
+ severity: "error",
6668
+ message: `Revision ${revision} metadata does not match its immutable request.`
6669
+ });
6670
+ const snapshotPlan = parsePlanDocument(planSource, join10(dir, "PLAN.md"));
6671
+ if (snapshotPlan.id !== record.id || snapshotPlan.revision !== Number(revision))
6672
+ issues.push({
6673
+ code: "snapshot-plan",
6674
+ severity: "error",
6675
+ message: `Revision ${revision} PLAN.md has mismatched identity or revision.`
6676
+ });
6677
+ await validateImplementationDirectory(dir, snapshotPlan, issues, `revision ${revision}`);
6678
+ } catch (error) {
6679
+ issues.push({
6680
+ code: "snapshot-missing",
6681
+ severity: "error",
6682
+ message: `Revision ${revision} is incomplete: ${error.message}`,
6683
+ path: dir
6684
+ });
6685
+ }
6686
+ }
6687
+ }
6688
+ async function validateImplementationDirectory(baseDir, plan, issues, label) {
6689
+ const dir = join10(baseDir, "implementation");
6690
+ let entries;
6691
+ try {
6692
+ entries = await readdir(dir);
6693
+ } catch {
6694
+ issues.push({
6695
+ code: "brief-directory",
6696
+ severity: "error",
6697
+ message: `${label} is missing implementation/.`,
6698
+ path: dir
6699
+ });
6700
+ return;
6701
+ }
6702
+ const expected = plan.phases.map((_phase, index) => `phase-${index + 1}.md`);
6703
+ const actual = entries.filter((entry) => entry.endsWith(".md")).sort((left, right) => left.localeCompare(right));
6704
+ if (!sameIds([...expected].sort((left, right) => left.localeCompare(right)), actual))
6705
+ issues.push({
6706
+ code: "brief-filenames",
6707
+ severity: "error",
6708
+ message: `${label} briefs must use exactly: ${expected.join(", ") || "(none)"}.`,
6709
+ path: dir
6710
+ });
6711
+ for (const [index, phase] of plan.phases.entries()) {
6712
+ const path = join10(dir, `phase-${index + 1}.md`);
6713
+ try {
6714
+ validateBriefSource(await readFile5(path, "utf8"), plan.revision, index + 1, phase, path, issues);
6715
+ } catch (error) {
6716
+ issues.push({
6717
+ code: "brief-missing",
6718
+ severity: "error",
6719
+ message: `${label} brief phase-${index + 1}.md is missing: ${error.message}`,
6720
+ path
6721
+ });
6722
+ }
6723
+ }
6724
+ }
6725
+ function validateBriefSource(source, planRevision, ordinal, phase, path, issues) {
6726
+ const matches = source.match(new RegExp(BRIEF_MARKER.source, "g")) ?? [];
6727
+ const markerMatch = source.match(BRIEF_MARKER);
6728
+ if (matches.length !== 1 || !markerMatch) {
6729
+ issues.push({ code: "brief-marker", severity: "error", message: `${path} needs one implementation marker.`, path });
6730
+ return;
6731
+ }
6732
+ const marker = parseMarker(markerMatch[1], `${path} implementation`);
6733
+ if (marker.schemaVersion !== 1 || marker.planRevision !== planRevision || marker.ordinal !== ordinal || marker.phaseId !== phase.id)
6734
+ issues.push({
6735
+ code: "brief-marker",
6736
+ severity: "error",
6737
+ message: `${path} marker must identify phase ${ordinal} (${phase.id}) at revision ${planRevision}.`,
6738
+ path
6739
+ });
6740
+ const taskIds = [...source.matchAll(BRIEF_TASK_MARKER)].map((match) => parseMarker(match[1], `${path} task`).id);
6741
+ if (!sameIds(phase.tasks.map((task) => task.id), taskIds))
6742
+ issues.push({
6743
+ code: "brief-task-ids",
6744
+ severity: "error",
6745
+ message: `${path} task markers must exactly match phase task IDs in order.`,
6746
+ path
6747
+ });
6748
+ const prose = source.replace(BRIEF_MARKER, "").replace(BRIEF_TASK_MARKER, "").replace(/<!-- \/diffpi-brief-task -->/g, "");
6749
+ if (/<!--[^]*?-->|\b(?:TODO|TBD)\b|define during implementation/i.test(prose))
6750
+ issues.push({
6751
+ code: "brief-placeholder",
6752
+ severity: "error",
6753
+ message: `${path} contains placeholder content.`,
6754
+ path
6755
+ });
6756
+ try {
6757
+ if (isPlaceholder(section(source, "Summary")))
6758
+ throw new Error("Summary is empty.");
6759
+ for (const task of phase.tasks) {
6760
+ const taskStart = source.indexOf(`<!-- diffpi-brief-task: ${json({ id: task.id })} -->`);
6761
+ const taskEnd = source.indexOf("<!-- /diffpi-brief-task -->", taskStart);
6762
+ if (taskStart < 0 || taskEnd < 0)
6763
+ throw new Error(`Task ${task.id} body is missing.`);
6764
+ const body = source.slice(taskStart, taskEnd);
6765
+ for (const heading of ["Ordered Steps", "File Scopes", "Acceptance Criteria"]) {
6766
+ const content = briefSubsection(body, heading);
6767
+ if (!parseBullets(content).length || parseBullets(content).some(isPlaceholder))
6768
+ throw new Error(`Task ${task.id} ${heading} is incomplete.`);
6769
+ }
6770
+ }
6771
+ } catch (error) {
6772
+ issues.push({ code: "brief-incomplete", severity: "error", message: `${path}: ${error.message}`, path });
6773
+ }
6774
+ }
6482
6775
  function section(source, heading) {
6483
6776
  const match = source.match(new RegExp(`^## ${escapeRegExp(heading)}\\s*$`, "m"));
6484
6777
  if (!match?.index) {
@@ -6503,6 +6796,14 @@ function subsection(source, parent, heading) {
6503
6796
  function parseBullets(input) {
6504
6797
  return [...input.matchAll(/^- (?!<!--)(.+)$/gm)].map((match) => match[1].trim());
6505
6798
  }
6799
+ function briefSubsection(source, heading) {
6800
+ const match = source.match(new RegExp(`^#### ${escapeRegExp(heading)}\\s*$`, "m"));
6801
+ if (match?.index === undefined)
6802
+ throw new Error(`Missing required brief heading: ${heading}.`);
6803
+ const rest = source.slice(match.index + match[0].length);
6804
+ const end = rest.search(/^#### |^<!-- \/diffpi-brief-task -->/m);
6805
+ return (end < 0 ? rest : rest.slice(0, end)).trim();
6806
+ }
6506
6807
  function parseListValue(body, label) {
6507
6808
  const match = new RegExp(`^ {2}- ${escapeRegExp(label)}:[ \\t]*(.*)$`, "m").exec(body);
6508
6809
  if (!match)
@@ -6549,6 +6850,16 @@ function assertUniqueIds(ids, label) {
6549
6850
  function cleanPlaceholder(value) {
6550
6851
  return value.replace(/<!--[^]*?-->/g, "").trim();
6551
6852
  }
6853
+ function isPlaceholder(value) {
6854
+ const normalized = cleanPlaceholder(value).trim();
6855
+ return normalized.length === 0 || /^(?:todo|tbd|none|n\/a)$/i.test(normalized) || /define during implementation|describe the|add requirements|add implementation/i.test(normalized);
6856
+ }
6857
+ function sameIds(expected, actual) {
6858
+ return expected.length === actual.length && expected.every((value, index) => actual[index] === value);
6859
+ }
6860
+ function sha256(value) {
6861
+ return createHash2("sha256").update(value).digest("hex");
6862
+ }
6552
6863
  function parseMarker(value, label) {
6553
6864
  try {
6554
6865
  return JSON.parse(value);
@@ -6556,15 +6867,14 @@ function parseMarker(value, label) {
6556
6867
  throw new Error(`Malformed ${label} marker JSON.`);
6557
6868
  }
6558
6869
  }
6559
- function taskList(label, values) {
6870
+ function bulletList(values, empty = "") {
6560
6871
  if (!values.length)
6561
- return ` - ${label}: none`;
6562
- const items = values.flatMap((value) => {
6872
+ return empty;
6873
+ return values.flatMap((value) => {
6563
6874
  const [first = "", ...continuations] = value.split(`
6564
6875
  `);
6565
- return [` - ${first}`, ...continuations.map((line) => ` ${line}`)];
6566
- });
6567
- return [` - ${label}:`, ...items].join(`
6876
+ return [`- ${first}`, ...continuations.map((line) => ` ${line}`)];
6877
+ }).join(`
6568
6878
  `);
6569
6879
  }
6570
6880
  function list3(values) {
@@ -6890,13 +7200,13 @@ function heartbeat(plan) {
6890
7200
  }
6891
7201
 
6892
7202
  // src/plan/reviews.ts
6893
- import { mkdir as mkdir4, readFile as readFile5, writeFile as writeFile3 } from "node:fs/promises";
6894
- import { dirname as dirname5, join as join10 } from "node:path";
7203
+ import { mkdir as mkdir4, readFile as readFile6, writeFile as writeFile3 } from "node:fs/promises";
7204
+ import { dirname as dirname5, join as join11 } from "node:path";
6895
7205
  async function readPlanReview(record) {
6896
7206
  const path = reviewPath(record);
6897
7207
  let source;
6898
7208
  try {
6899
- source = await readFile5(path, "utf8");
7209
+ source = await readFile6(path, "utf8");
6900
7210
  } catch (error) {
6901
7211
  if (error.code === "ENOENT")
6902
7212
  return;
@@ -6913,7 +7223,7 @@ async function readPlanReview(record) {
6913
7223
  return { path, dump };
6914
7224
  }
6915
7225
  function reviewPath(record) {
6916
- return join10(record.dir, "reviews", `${record.document.revision}.json`);
7226
+ return join11(record.dir, "reviews", `${record.document.revision}.json`);
6917
7227
  }
6918
7228
  function isPlanReviewDump(value) {
6919
7229
  if (!value || typeof value !== "object")
@@ -6923,14 +7233,15 @@ function isPlanReviewDump(value) {
6923
7233
  }
6924
7234
 
6925
7235
  // src/plan/store.ts
6926
- import { mkdir as mkdir6, readdir, readFile as readFile7, realpath as realpath3, rm as rm2 } from "node:fs/promises";
6927
- import { basename as basename5, dirname as dirname7, join as join13, resolve as resolve3, sep } from "node:path";
7236
+ import { createHash as createHash3, randomUUID as randomUUID2 } from "node:crypto";
7237
+ import { mkdir as mkdir6, readdir as readdir2, readFile as readFile8, realpath as realpath3, rename as rename2, rm as rm2 } from "node:fs/promises";
7238
+ import { basename as basename5, dirname as dirname7, join as join14, resolve as resolve3, sep } from "node:path";
6928
7239
 
6929
7240
  // src/extensions/fsx.ts
6930
7241
  import { mkdir as mkdir5, rename, rm, writeFile as writeFile4 } from "node:fs/promises";
6931
- import { basename as basename4, dirname as dirname6, join as join11 } from "node:path";
7242
+ import { basename as basename4, dirname as dirname6, join as join12 } from "node:path";
6932
7243
  async function atomicWrite(path, content) {
6933
- const temp = join11(dirname6(path), `.${basename4(path)}.${crypto.randomUUID()}.tmp`);
7244
+ const temp = join12(dirname6(path), `.${basename4(path)}.${crypto.randomUUID()}.tmp`);
6934
7245
  await writeFile4(temp, content, { encoding: "utf8", mode: 384, flag: "wx" });
6935
7246
  await rename(temp, path);
6936
7247
  }
@@ -6961,13 +7272,13 @@ function sleep(ms) {
6961
7272
  }
6962
7273
 
6963
7274
  // src/templates.ts
6964
- import { readFile as readFile6 } from "node:fs/promises";
7275
+ import { readFile as readFile7 } from "node:fs/promises";
6965
7276
  import { homedir as homedir4 } from "node:os";
6966
- import { join as join12, normalize } from "node:path";
7277
+ import { join as join13, normalize } from "node:path";
6967
7278
  async function loadTemplate(name, options = {}) {
6968
7279
  const relative = templateRelativePath(name);
6969
- const userPath = join12(options.homeDir ?? homedir4(), ".difflab", "diffpi", "templates", relative);
6970
- const bundledPath = join12(options.bundledDir ?? resolveBundledTemplatesDir(), relative);
7280
+ const userPath = join13(options.homeDir ?? homedir4(), ".difflab", "diffpi", "templates", relative);
7281
+ const bundledPath = join13(options.bundledDir ?? resolveBundledTemplatesDir(), relative);
6971
7282
  const user = await readOptionalFile(userPath);
6972
7283
  if (user !== undefined)
6973
7284
  return { name, path: userPath, source: "user", content: user };
@@ -6988,7 +7299,7 @@ function templateRelativePath(name) {
6988
7299
  }
6989
7300
  async function readOptionalFile(path) {
6990
7301
  try {
6991
- return await readFile6(path, "utf8");
7302
+ return await readFile7(path, "utf8");
6992
7303
  } catch (error) {
6993
7304
  if (error.code === "ENOENT")
6994
7305
  return;
@@ -7003,7 +7314,7 @@ function planRecordName(shortSlug, date = new Date) {
7003
7314
  }
7004
7315
  async function resolvePlan(cwd, query, filters = {}, options = {}) {
7005
7316
  const root = await plansDir(cwd, options.homeDir);
7006
- const entries = await readdir(root, { withFileTypes: true });
7317
+ const entries = await readdir2(root, { withFileTypes: true });
7007
7318
  const normalizedQuery = query ? normalizeQuery(query) : undefined;
7008
7319
  const records = [];
7009
7320
  for (const entry of entries) {
@@ -7011,7 +7322,7 @@ async function resolvePlan(cwd, query, filters = {}, options = {}) {
7011
7322
  continue;
7012
7323
  if (normalizedQuery && entry.name !== normalizedQuery && stripDate(entry.name) !== normalizedQuery)
7013
7324
  continue;
7014
- const dir = join13(root, entry.name);
7325
+ const dir = join14(root, entry.name);
7015
7326
  await assertContained(root, dir);
7016
7327
  try {
7017
7328
  const record = await readRecord(dir);
@@ -7030,6 +7341,15 @@ async function resolvePlan(cwd, query, filters = {}, options = {}) {
7030
7341
  }
7031
7342
  function createPlanStore(options = {}) {
7032
7343
  const now = options.now ?? (() => new Date);
7344
+ const read = async (cwd, query, filters) => {
7345
+ const result = await resolvePlan(cwd, query, filters, options);
7346
+ if (!result.record) {
7347
+ if (result.ambiguous)
7348
+ throw new Error(`Plan query "${query}" is ambiguous: ${result.candidates.map((item) => item.id).join(", ")}.`);
7349
+ throw new Error(`Plan "${query}" was not found.`);
7350
+ }
7351
+ return result.record;
7352
+ };
7033
7353
  return {
7034
7354
  context(cwd, query, filters) {
7035
7355
  return resolvePlan(cwd, query, filters, options);
@@ -7037,120 +7357,318 @@ function createPlanStore(options = {}) {
7037
7357
  async init(input) {
7038
7358
  const root = await plansDir(input.cwd, options.homeDir);
7039
7359
  const id = planRecordName(input.shortSlug, now());
7040
- const dir = join13(root, id);
7041
- await assertContained(root, dirname7(dir));
7042
- try {
7043
- await mkdir6(dir);
7044
- } catch (error) {
7045
- if (error.code === "EEXIST")
7046
- throw new Error(`Plan ${id} already exists.`);
7047
- throw error;
7048
- }
7360
+ const dir = join14(root, id);
7361
+ await createPlanDirectory(root, dir, id);
7049
7362
  try {
7050
7363
  const timestamp = now().toISOString();
7051
7364
  const template = await loadTemplate("plan/PLAN", {
7052
7365
  homeDir: options.homeDir,
7053
7366
  bundledDir: options.bundledTemplatesDir
7054
7367
  });
7368
+ const title = input.title?.trim() || titleFromSlug(input.shortSlug);
7055
7369
  const source = renderTemplate(template.content, {
7056
7370
  id,
7057
7371
  branch: input.branch,
7058
- title: input.title?.trim() || titleFromSlug(input.shortSlug),
7372
+ title,
7059
7373
  intent: input.intent?.trim() || "<!-- Describe the intended outcome. -->",
7060
- issue_id: input.issueId?.trim() || "<!-- Add issue tracker ID. -->",
7061
- issue_url: input.issueUrl?.trim() || "<!-- Add issue tracker URL. -->",
7374
+ issue_id: input.issueId?.trim() || "",
7375
+ issue_url: input.issueUrl?.trim() || "",
7062
7376
  created_at: timestamp,
7063
7377
  updated_at: timestamp
7064
7378
  });
7065
- const document = parsePlanDocument(source, join13(dir, "PLAN.md"));
7066
- await atomicWrite(join13(dir, "PLAN.md"), source);
7067
- return {
7068
- id,
7069
- dir,
7070
- planPath: join13(dir, "PLAN.md"),
7071
- logPath: join13(dir, "logs.txt"),
7072
- implementationDir: join13(dir, "implementation"),
7073
- document,
7074
- source
7075
- };
7379
+ const document = parsePlanDocument(source, join14(dir, "PLAN.md"));
7380
+ const authoringRequest = input.request ?? { kind: "user", text: input.intent?.trim() || `Initialize phase-less plan ${title}.` };
7381
+ await writeRevisionSnapshot(dir, document, source, authoringRequest, []);
7382
+ await writeLatestView(dir, document, source, []);
7383
+ return await readRecord(dir);
7076
7384
  } catch (error) {
7077
7385
  await rm2(dir, { recursive: true, force: true });
7078
7386
  throw error;
7079
7387
  }
7080
7388
  },
7081
- async read(cwd, query, filters) {
7082
- const result = await resolvePlan(cwd, query, filters, options);
7083
- if (!result.record) {
7084
- if (result.ambiguous)
7085
- throw new Error(`Plan query "${query}" is ambiguous: ${result.candidates.map((item) => item.id).join(", ")}.`);
7086
- throw new Error(`Plan "${query}" was not found.`);
7389
+ read,
7390
+ async applyRevision(cwd, request) {
7391
+ if (request.mode === "create") {
7392
+ const root = await plansDir(cwd, options.homeDir);
7393
+ const id = planRecordName(request.shortSlug, now());
7394
+ const dir = join14(root, id);
7395
+ await createPlanDirectory(root, dir, id);
7396
+ try {
7397
+ const timestamp = now().toISOString();
7398
+ const document = normalizeRevision(undefined, request, id, 0, timestamp);
7399
+ assertCompleteRevision(document, request.briefs);
7400
+ const source = renderPlanDocument(document);
7401
+ parsePlanDocument(source, join14(dir, "PLAN.md"));
7402
+ await writeRevisionSnapshot(dir, document, source, request.request, request.briefs);
7403
+ await writeLatestView(dir, document, source, request.briefs);
7404
+ return await readRecord(dir);
7405
+ } catch (error) {
7406
+ await rm2(dir, { recursive: true, force: true });
7407
+ throw error;
7408
+ }
7087
7409
  }
7088
- return result.record;
7410
+ const initial = await read(cwd, request.plan);
7411
+ return withDirectoryLock(join14(initial.dir, ".lock"), async () => {
7412
+ const current = await readRecord(initial.dir);
7413
+ if (current.document.revision !== request.expectedPlanRevision)
7414
+ throw new Error(`Expected plan revision ${request.expectedPlanRevision}, found ${current.document.revision}.`);
7415
+ const revision = current.document.revision + 1;
7416
+ const document = normalizeRevision(current.document, request, current.id, revision, now().toISOString());
7417
+ assertCompleteRevision(document, request.briefs);
7418
+ const source = renderPlanDocument(document);
7419
+ parsePlanDocument(source, current.planPath);
7420
+ await writeRevisionSnapshot(current.dir, document, source, request.request, request.briefs);
7421
+ try {
7422
+ await writeLatestView(current.dir, document, source, request.briefs);
7423
+ } catch (error) {
7424
+ await rm2(join14(current.dir, "revisions", String(revision)), { recursive: true, force: true });
7425
+ throw error;
7426
+ }
7427
+ return await readRecord(current.dir);
7428
+ }, { operation: "apply revision" });
7089
7429
  },
7090
7430
  async mutate(cwd, query, operation, update) {
7091
- const initial = await this.read(cwd, query);
7092
- return withDirectoryLock(join13(initial.dir, ".lock"), async () => {
7431
+ const initial = await read(cwd, query);
7432
+ return withDirectoryLock(join14(initial.dir, ".lock"), async () => {
7093
7433
  const current = await readRecord(initial.dir);
7094
7434
  const next = await update(structuredClone(current.document));
7095
7435
  if (next.id !== current.id)
7096
7436
  throw new Error("A plan mutation cannot change the plan ID.");
7097
7437
  const document = {
7098
7438
  ...next,
7099
- revision: current.document.revision + 1,
7439
+ revision: current.document.revision,
7100
7440
  updatedAt: now().toISOString()
7101
7441
  };
7102
7442
  const source = renderPlanDocument(document, current.source);
7103
7443
  parsePlanDocument(source, current.planPath);
7104
7444
  await atomicWrite(current.planPath, source);
7105
- await ensureImplementationFiles(current.dir, document, options);
7106
- return { ...current, document, source, implementationDir: join13(current.dir, "implementation") };
7445
+ return { ...current, document, source };
7107
7446
  }, { operation });
7108
7447
  },
7109
7448
  async log(cwd, query, event) {
7110
- const record = await this.read(cwd, query);
7449
+ const record = await read(cwd, query);
7111
7450
  return appendLogEntry(record.logPath, event);
7112
7451
  }
7113
7452
  };
7114
7453
  }
7115
7454
  async function readRecord(dir) {
7116
- const planPath = join13(dir, "PLAN.md");
7117
- const logPath = join13(dir, "logs.txt");
7118
- const source = await readFile7(planPath, "utf8");
7455
+ const planPath = join14(dir, "PLAN.md");
7456
+ const logPath = join14(dir, "logs.txt");
7457
+ const source = await readFile8(planPath, "utf8");
7119
7458
  const document = parsePlanDocument(source, planPath);
7120
7459
  return {
7121
7460
  id: basename5(dir),
7122
7461
  dir,
7123
7462
  planPath,
7124
7463
  logPath,
7125
- implementationDir: join13(dir, "implementation"),
7464
+ implementationDir: join14(dir, "implementation"),
7126
7465
  document,
7127
7466
  source
7128
7467
  };
7129
7468
  }
7130
- async function ensureImplementationFiles(dir, document, options) {
7131
- const implementationDir = join13(dir, "implementation");
7132
- await mkdir6(implementationDir, { recursive: true });
7133
- const template = await loadTemplate("plan/implementation", {
7134
- homeDir: options.homeDir,
7135
- bundledDir: options.bundledTemplatesDir
7136
- });
7137
- for (const phase of document.phases) {
7138
- const path = join13(implementationDir, `phase-${phase.id}.md`);
7469
+ async function createPlanDirectory(root, dir, id) {
7470
+ await assertContained(root, dirname7(dir));
7471
+ try {
7472
+ await mkdir6(dir);
7473
+ } catch (error) {
7474
+ if (error.code === "EEXIST")
7475
+ throw new Error(`Plan ${id} already exists.`);
7476
+ throw error;
7477
+ }
7478
+ }
7479
+ async function writeRevisionSnapshot(planDir, document, source, request, briefs) {
7480
+ if (!request.text.trim())
7481
+ throw new Error("An exact non-empty authoring request is required.");
7482
+ if (request.kind === "annotation" && !request.response?.trim())
7483
+ throw new Error("Annotation requests require a non-empty response.");
7484
+ const revisionsDir = join14(planDir, "revisions");
7485
+ await mkdir6(revisionsDir, { recursive: true });
7486
+ const target = join14(revisionsDir, String(document.revision));
7487
+ try {
7488
+ await readFile8(join14(target, "metadata.json"), "utf8");
7489
+ throw new Error(`Revision ${document.revision} already exists and is immutable.`);
7490
+ } catch (error) {
7491
+ if (error.code !== "ENOENT")
7492
+ throw error;
7493
+ }
7494
+ const staging = join14(revisionsDir, `.tmp-${document.revision}-${randomUUID2()}`);
7495
+ await mkdir6(staging);
7496
+ try {
7497
+ const requestSource = request.kind === "annotation" ? `## Original annotation
7498
+ ${request.text}
7499
+
7500
+ ## LLM response
7501
+ ${request.response}` : request.text;
7502
+ await atomicWrite(join14(staging, "request.md"), requestSource);
7503
+ await atomicWrite(join14(staging, "metadata.json"), `${JSON.stringify({
7504
+ schemaVersion: 1,
7505
+ id: document.id,
7506
+ revision: document.revision,
7507
+ requestKind: request.kind,
7508
+ requestSha256: sha2562(request.text),
7509
+ ...request.kind === "annotation" ? { originalAnnotationSha256: sha2562(request.text), responseSha256: sha2562(request.response) } : {},
7510
+ createdAt: document.updatedAt
7511
+ }, null, 2)}
7512
+ `);
7513
+ await atomicWrite(join14(staging, "PLAN.md"), source);
7514
+ await writeImplementationDirectory(staging, document, briefs);
7515
+ await rename2(staging, target);
7516
+ } catch (error) {
7517
+ await rm2(staging, { recursive: true, force: true });
7518
+ throw error;
7519
+ }
7520
+ }
7521
+ async function writeLatestView(planDir, document, source, briefs) {
7522
+ const current = join14(planDir, "implementation");
7523
+ const stagingRoot = join14(planDir, `.latest-${randomUUID2()}`);
7524
+ const stagedImplementation = join14(stagingRoot, "implementation");
7525
+ const backup = join14(planDir, `.implementation-backup-${randomUUID2()}`);
7526
+ await mkdir6(stagingRoot);
7527
+ await writeImplementationDirectory(stagingRoot, document, briefs);
7528
+ let backedUp = false;
7529
+ try {
7139
7530
  try {
7140
- await readFile7(path, "utf8");
7531
+ await rename2(current, backup);
7532
+ backedUp = true;
7141
7533
  } catch (error) {
7142
7534
  if (error.code !== "ENOENT")
7143
7535
  throw error;
7144
- const tasks = phase.tasks.map((task) => `- ${task.id}: ${task.title}`).join("\\n") || "- Add implementation tasks.";
7145
- await atomicWrite(path, renderTemplate(template.content, {
7146
- phase_id: phase.id,
7147
- phase_title: phase.title,
7148
- phase_objective: phase.objective,
7149
- phase_tasks: tasks
7150
- }));
7151
7536
  }
7537
+ await rename2(stagedImplementation, current);
7538
+ await atomicWrite(join14(planDir, "PLAN.md"), source);
7539
+ if (backedUp)
7540
+ await rm2(backup, { recursive: true, force: true });
7541
+ } catch (error) {
7542
+ await rm2(current, { recursive: true, force: true });
7543
+ if (backedUp)
7544
+ await rename2(backup, current);
7545
+ throw error;
7546
+ } finally {
7547
+ await rm2(stagingRoot, { recursive: true, force: true });
7152
7548
  }
7153
7549
  }
7550
+ async function writeImplementationDirectory(baseDir, document, briefs) {
7551
+ const implementationDir = join14(baseDir, "implementation");
7552
+ await mkdir6(implementationDir, { recursive: true });
7553
+ for (const [index, phase] of document.phases.entries()) {
7554
+ const brief = briefs[index];
7555
+ if (!brief)
7556
+ throw new Error(`Missing implementation brief for phase ${phase.id}.`);
7557
+ await atomicWrite(join14(implementationDir, `phase-${index + 1}.md`), renderImplementationBrief(document.revision, index + 1, phase, brief));
7558
+ }
7559
+ }
7560
+ function normalizeRevision(current, request, id, revision, updatedAt) {
7561
+ if (current?.status === "completed")
7562
+ throw new Error("Completed plans cannot be amended.");
7563
+ if (current?.execution?.active && request.request.kind !== "blocker")
7564
+ throw new Error("An active execution accepts only a blocker amendment.");
7565
+ const currentPhases = new Map(current?.phases.map((phase) => [phase.id, phase]) ?? []);
7566
+ for (const phase of current?.phases ?? []) {
7567
+ if (!request.phases.some((candidate) => candidate.id === phase.id) && (phase.status === "completed" || phase.status === "in_progress"))
7568
+ throw new Error(`${phase.status === "completed" ? "Completed" : "Active"} phase ${phase.id} cannot be removed.`);
7569
+ }
7570
+ const phases = request.phases.map((draft) => reconcilePhase(currentPhases.get(draft.id), draft, current));
7571
+ const createdAt = current?.createdAt ?? updatedAt;
7572
+ return {
7573
+ schemaVersion: 1,
7574
+ id,
7575
+ revision,
7576
+ title: request.title,
7577
+ branch: current?.branch ?? (request.mode === "create" ? request.branch : ""),
7578
+ issueId: current?.issueId ?? (request.mode === "create" ? request.issueId : undefined),
7579
+ issueUrl: current?.issueUrl ?? (request.mode === "create" ? request.issueUrl : undefined),
7580
+ intent: request.intent,
7581
+ requirements: request.requirements,
7582
+ design: request.design,
7583
+ references: request.references,
7584
+ phases,
7585
+ status: nextPlanStatus(current),
7586
+ execution: current?.execution,
7587
+ createdAt,
7588
+ updatedAt
7589
+ };
7590
+ }
7591
+ function reconcilePhase(current, draft, plan) {
7592
+ if (!current)
7593
+ return {
7594
+ ...draft,
7595
+ revision: 0,
7596
+ status: "pending",
7597
+ gate: { phaseRevision: 0, status: "pending", results: [] },
7598
+ tasks: draft.tasks.map(newTask)
7599
+ };
7600
+ if (current.status === "completed") {
7601
+ if (JSON.stringify(phaseContent(current)) !== JSON.stringify(draft))
7602
+ throw new Error(`Completed phase ${current.id} cannot be changed.`);
7603
+ return current;
7604
+ }
7605
+ const byId = new Map(current.tasks.map((task) => [task.id, task]));
7606
+ for (const task of current.tasks) {
7607
+ if (!draft.tasks.some((candidate) => candidate.id === task.id) && (task.status === "completed" || task.status === "in_progress"))
7608
+ throw new Error(`${task.status === "completed" ? "Completed" : "Active"} task ${task.id} cannot be removed.`);
7609
+ }
7610
+ const tasks = draft.tasks.map((task) => reconcileTask(byId.get(task.id), task));
7611
+ const changed = JSON.stringify(phaseContent(current)) !== JSON.stringify(draft);
7612
+ const revision = changed ? current.revision + 1 : current.revision;
7613
+ const wasBlocked = current.status === "blocked";
7614
+ return {
7615
+ ...current,
7616
+ ...draft,
7617
+ revision,
7618
+ tasks,
7619
+ status: wasBlocked ? plan?.execution?.active ? "in_progress" : "pending" : current.status,
7620
+ gate: changed || wasBlocked ? { phaseRevision: revision, status: "stale", results: [] } : current.gate,
7621
+ blocker: wasBlocked ? undefined : current.blocker
7622
+ };
7623
+ }
7624
+ function reconcileTask(current, draft) {
7625
+ if (!current)
7626
+ return newTask(draft);
7627
+ const changed = JSON.stringify(taskContent(current)) !== JSON.stringify(draft);
7628
+ if ((current.status === "completed" || current.status === "in_progress") && changed)
7629
+ throw new Error(`${current.status === "completed" ? "Completed" : "Active"} task ${current.id} cannot be changed.`);
7630
+ if (current.status === "completed" || current.status === "in_progress")
7631
+ return current;
7632
+ return {
7633
+ ...current,
7634
+ ...draft,
7635
+ revision: changed ? current.revision + 1 : current.revision,
7636
+ status: current.status === "blocked" ? "pending" : current.status,
7637
+ owner: current.status === "blocked" ? undefined : current.owner,
7638
+ executionId: current.status === "blocked" ? undefined : current.executionId,
7639
+ blocker: current.status === "blocked" ? undefined : current.blocker
7640
+ };
7641
+ }
7642
+ function newTask(draft) {
7643
+ return { ...draft, revision: 0, status: "pending" };
7644
+ }
7645
+ function phaseContent(phase) {
7646
+ return {
7647
+ id: phase.id,
7648
+ title: phase.title,
7649
+ objective: phase.objective,
7650
+ dependencies: phase.dependencies,
7651
+ tasks: phase.tasks.map(taskContent)
7652
+ };
7653
+ }
7654
+ function taskContent(task) {
7655
+ return { id: task.id, title: task.title, dependencies: task.dependencies };
7656
+ }
7657
+ function nextPlanStatus(current) {
7658
+ if (!current)
7659
+ return "draft";
7660
+ if (current.execution?.active)
7661
+ return current.status === "blocked" ? "in_progress" : current.status;
7662
+ return current.status === "ready" || current.status === "blocked" ? "draft" : current.status;
7663
+ }
7664
+ function assertCompleteRevision(document, briefs) {
7665
+ const errors = [...validatePlanDocument(document, { strict: true }), ...validatePlanBriefs(document, briefs)].filter((issue) => issue.severity === "error");
7666
+ if (errors.length)
7667
+ throw new Error(`Invalid plan revision: ${errors.map((issue) => issue.message).join(" ")}`);
7668
+ }
7669
+ function sha2562(value) {
7670
+ return createHash3("sha256").update(value).digest("hex");
7671
+ }
7154
7672
  async function assertContained(root, candidate) {
7155
7673
  const canonicalRoot = await realpath3(root);
7156
7674
  let canonicalCandidate;
@@ -7182,34 +7700,54 @@ function stripDate(value) {
7182
7700
  return value.replace(/^\d{6}-/, "");
7183
7701
  }
7184
7702
  function titleFromSlug(value) {
7185
- return normalizeSlug(value).replace(/^(?:[a-z]+-\d+-)/, "").split("-").map((part) => part[0].toUpperCase() + part.slice(1)).join(" ");
7703
+ const slug = normalizeSlug(value).replace(/^(?:[a-z]+-\d+-)/, "");
7704
+ return slug.replace(/(^|-)([a-z])/g, (_match, separator, letter) => {
7705
+ return `${separator ? " " : ""}${letter.toUpperCase()}`;
7706
+ });
7186
7707
  }
7187
7708
 
7188
- // src/tools/plan-schema.ts
7709
+ // src/plan/schema.ts
7189
7710
  import { z as z6 } from "zod";
7190
7711
  var planStatusSchema = z6.enum(["draft", "ready", "in_progress", "blocked", "completed"]);
7191
7712
  var planUnitStatusSchema = z6.enum(["draft", "ready", "in_progress", "blocked", "completed", "pending", "skipped"]);
7192
- var planTaskDraftSchema = z6.object({
7193
- id: zx.id,
7194
- title: zx.text,
7195
- steps: z6.array(zx.text).optional(),
7196
- dependencies: z6.array(zx.id).optional(),
7197
- fileScopes: z6.array(zx.text).optional(),
7198
- acceptanceCriteria: z6.array(zx.text).optional()
7199
- }).strict();
7713
+ var planTaskDraftSchema = z6.object({ id: zx.id, title: zx.text, dependencies: z6.array(zx.id) }).strict();
7200
7714
  var planPhaseDraftSchema = z6.object({
7201
7715
  id: zx.id,
7202
7716
  title: zx.text,
7203
7717
  objective: zx.text,
7204
- dependencies: z6.array(zx.id).optional(),
7205
- tasks: z6.array(planTaskDraftSchema).optional()
7718
+ dependencies: z6.array(zx.id),
7719
+ tasks: z6.array(planTaskDraftSchema).min(1)
7206
7720
  }).strict();
7207
- var planReferenceSchema = z6.object({ id: zx.id, value: zx.text }).strict();
7208
- var planDesignSchema = z6.object({
7209
- bigIdeas: z6.string(),
7210
- keyApiUpdates: z6.string(),
7211
- consequences: z6.string()
7721
+ var planBriefSchema = z6.object({
7722
+ phaseId: zx.id,
7723
+ summary: zx.text,
7724
+ apiChanges: z6.array(zx.text),
7725
+ libraries: z6.array(zx.text),
7726
+ constraints: z6.array(zx.text),
7727
+ tasks: z6.array(z6.object({
7728
+ taskId: zx.id,
7729
+ steps: z6.array(zx.text).min(1),
7730
+ fileScopes: z6.array(zx.text).min(1),
7731
+ acceptanceCriteria: z6.array(zx.text).min(1)
7732
+ }).strict()).min(1)
7212
7733
  }).strict();
7734
+ var planReferenceSchema = z6.object({ id: zx.id, value: zx.text }).strict();
7735
+ var planDesignSchema = z6.object({ bigIdeas: zx.text, keyApiUpdates: zx.text, consequences: zx.text }).strict();
7736
+ var planRequestSchema = z6.discriminatedUnion("kind", [
7737
+ z6.object({ kind: z6.literal("annotation"), text: zx.text, response: zx.text }).strict(),
7738
+ z6.object({ kind: z6.literal("user"), text: zx.text, response: zx.text.optional() }).strict(),
7739
+ z6.object({ kind: z6.literal("blocker"), text: zx.text, response: zx.text.optional() }).strict()
7740
+ ]);
7741
+ var revisionContentFields = {
7742
+ request: planRequestSchema,
7743
+ title: zx.text,
7744
+ intent: zx.text,
7745
+ requirements: z6.array(zx.text).min(1),
7746
+ design: planDesignSchema,
7747
+ references: z6.array(planReferenceSchema),
7748
+ phases: z6.array(planPhaseDraftSchema).min(1),
7749
+ briefs: z6.array(planBriefSchema).min(1)
7750
+ };
7213
7751
  var planContextParametersSchema = z6.object({
7214
7752
  cwd: zx.cwd,
7215
7753
  plan: z6.string().optional(),
@@ -7223,46 +7761,28 @@ var planInitParametersSchema = z6.object({
7223
7761
  title: zx.text.optional(),
7224
7762
  intent: zx.text.optional(),
7225
7763
  issueId: zx.text.optional(),
7226
- issueUrl: z6.string().url().optional(),
7764
+ issueUrl: z6.url().optional(),
7765
+ request: planRequestSchema.optional(),
7227
7766
  open: z6.boolean().optional()
7228
7767
  }).strict();
7229
- var planUpdateOverviewParametersSchema = z6.object({
7230
- cwd: zx.cwd,
7231
- plan: zx.text,
7232
- expectedPlanRevision: zx.revision,
7233
- intent: zx.text.optional(),
7234
- requirements: z6.array(zx.text).optional(),
7235
- design: planDesignSchema.optional(),
7236
- references: z6.array(planReferenceSchema).optional()
7237
- }).strict().refine((value) => value.intent || value.requirements || value.design || value.references, {
7238
- message: "At least one overview field is required."
7239
- });
7240
- var planAddPhaseParametersSchema = z6.object({
7241
- cwd: zx.cwd,
7242
- plan: zx.text,
7243
- expectedPlanRevision: zx.revision,
7244
- afterPhaseId: zx.id.optional(),
7245
- phase: planPhaseDraftSchema
7246
- }).strict();
7247
- var planRemovePhaseParametersSchema = z6.object({
7248
- cwd: zx.cwd,
7249
- plan: zx.text,
7250
- expectedPlanRevision: zx.revision,
7251
- phaseId: zx.id,
7252
- reason: zx.text
7253
- }).strict();
7254
- var planUpdatePhaseParametersSchema = z6.object({
7255
- cwd: zx.cwd,
7256
- plan: zx.text,
7257
- expectedPlanRevision: zx.revision,
7258
- phaseId: zx.id,
7259
- patch: z6.object({
7260
- title: zx.text.optional(),
7261
- objective: zx.text.optional(),
7262
- dependencies: z6.array(zx.id).optional(),
7263
- tasks: z6.array(planTaskDraftSchema).optional()
7768
+ var planApplyRevisionParametersSchema = z6.discriminatedUnion("mode", [
7769
+ z6.object({
7770
+ mode: z6.literal("create"),
7771
+ cwd: zx.cwd,
7772
+ shortSlug: zx.id,
7773
+ branch: z6.string().min(1).optional(),
7774
+ issueId: zx.text.optional(),
7775
+ issueUrl: z6.url().optional(),
7776
+ ...revisionContentFields
7777
+ }).strict(),
7778
+ z6.object({
7779
+ mode: z6.literal("amend"),
7780
+ cwd: zx.cwd,
7781
+ plan: zx.text,
7782
+ expectedPlanRevision: zx.revision,
7783
+ ...revisionContentFields
7264
7784
  }).strict()
7265
- }).strict();
7785
+ ]);
7266
7786
  var planValidateParametersSchema = z6.object({ cwd: zx.cwd, plan: zx.text, strict: z6.boolean().optional() }).strict();
7267
7787
  var planLogProgressParametersSchema = z6.object({
7268
7788
  cwd: zx.cwd,
@@ -7362,116 +7882,17 @@ function createPlanTools(_pi, _modes, store = createPlanStore()) {
7362
7882
  }
7363
7883
  }),
7364
7884
  defineTool5({
7365
- name: "plan_update_overview",
7366
- label: "plan update overview",
7367
- description: "Replace selected plan overview fields using an expected plan revision.",
7368
- parameters: parameters(planUpdateOverviewParametersSchema),
7369
- executionMode: "sequential",
7370
- async execute(_id, input) {
7371
- const params = planUpdateOverviewParametersSchema.parse(input);
7372
- const record = await store.mutate(params.cwd ?? process.cwd(), params.plan, "update overview", (plan) => {
7373
- assertAuthoringRevision(plan, params.expectedPlanRevision);
7374
- assertAuthorable(plan);
7375
- return resetDraft({
7376
- ...plan,
7377
- intent: params.intent ?? plan.intent,
7378
- requirements: params.requirements ?? plan.requirements,
7379
- design: params.design ?? plan.design,
7380
- references: params.references ?? plan.references
7381
- });
7382
- });
7383
- return result2(`Updated ${record.id} to revision ${record.document.revision}.`, { record });
7384
- }
7385
- }),
7386
- defineTool5({
7387
- name: "plan_add_phase",
7388
- label: "plan add phase",
7389
- description: "Add an ordered phase with stable IDs.",
7390
- parameters: parameters(planAddPhaseParametersSchema),
7391
- executionMode: "sequential",
7392
- async execute(_id, input) {
7393
- const params = planAddPhaseParametersSchema.parse(input);
7394
- const record = await store.mutate(params.cwd ?? process.cwd(), params.plan, "add phase", (plan) => {
7395
- assertAuthoringRevision(plan, params.expectedPlanRevision);
7396
- assertAuthorable(plan);
7397
- if (allIds(plan).has(params.phase.id))
7398
- throw new Error(`Duplicate stable ID: ${params.phase.id}.`);
7399
- const phase = newPhase(params.phase);
7400
- const phases = [...plan.phases];
7401
- if (params.afterPhaseId) {
7402
- const index = phases.findIndex((item) => item.id === params.afterPhaseId);
7403
- if (index < 0)
7404
- throw new Error(`Unknown phase: ${params.afterPhaseId}.`);
7405
- phases.splice(index + 1, 0, phase);
7406
- } else
7407
- phases.push(phase);
7408
- assertNewIds(plan, phase);
7409
- return resetDraft({ ...plan, phases });
7410
- });
7411
- return result2(`Added phase ${params.phase.id} to ${record.id}.`, { record });
7412
- }
7413
- }),
7414
- defineTool5({
7415
- name: "plan_remove_phase",
7416
- label: "plan remove phase",
7417
- description: "Remove an unfinished phase that has no dependents.",
7418
- parameters: parameters(planRemovePhaseParametersSchema),
7419
- executionMode: "sequential",
7420
- async execute(_id, input) {
7421
- const params = planRemovePhaseParametersSchema.parse(input);
7422
- const record = await store.mutate(params.cwd ?? process.cwd(), params.plan, "remove phase", (plan) => {
7423
- assertAuthoringRevision(plan, params.expectedPlanRevision);
7424
- assertAuthorable(plan);
7425
- const phase = getPhase2(plan, params.phaseId);
7426
- if (phase.status === "completed" || phase.tasks.some((task) => task.status === "completed"))
7427
- throw new Error(`Completed phase ${phase.id} cannot be removed.`);
7428
- if (plan.phases.some((item) => item.dependencies.includes(phase.id)))
7429
- throw new Error(`Phase ${phase.id} has dependents and cannot be removed.`);
7430
- return resetDraft({ ...plan, phases: plan.phases.filter((item) => item.id !== phase.id) });
7431
- });
7432
- await store.log(params.cwd ?? process.cwd(), record.id, {
7433
- planRevision: record.document.revision,
7434
- kind: "updated",
7435
- actor: "planner",
7436
- message: `Removed phase ${params.phaseId}: ${params.reason}`,
7437
- phaseId: params.phaseId
7438
- });
7439
- return result2(`Removed phase ${params.phaseId}.`, { record });
7440
- }
7441
- }),
7442
- defineTool5({
7443
- name: "plan_update_phase",
7444
- label: "plan update phase",
7445
- description: "Update an unfinished phase and its ordered tasks.",
7446
- parameters: parameters(planUpdatePhaseParametersSchema),
7885
+ name: "plan_apply_revision",
7886
+ label: "plan apply revision",
7887
+ description: "Create mode writes a complete revision 0 without plan_init; amend mode atomically writes the next complete authoring revision.",
7888
+ parameters: parameters(planApplyRevisionParametersSchema),
7447
7889
  executionMode: "sequential",
7448
7890
  async execute(_id, input) {
7449
- const params = planUpdatePhaseParametersSchema.parse(input);
7450
- const record = await store.mutate(params.cwd ?? process.cwd(), params.plan, "update phase", (plan) => {
7451
- assertAuthoringRevision(plan, params.expectedPlanRevision);
7452
- assertAuthorable(plan, params.phaseId);
7453
- const existing = getPhase2(plan, params.phaseId);
7454
- if (existing.status === "completed")
7455
- throw new Error(`Completed phase ${existing.id} cannot be changed.`);
7456
- const tasks = params.patch.tasks ? reconcileTasks(existing.tasks, params.patch.tasks) : existing.tasks;
7457
- const updated = {
7458
- ...existing,
7459
- title: params.patch.title ?? existing.title,
7460
- objective: params.patch.objective ?? existing.objective,
7461
- dependencies: params.patch.dependencies ?? existing.dependencies,
7462
- tasks,
7463
- revision: existing.revision + 1,
7464
- status: existing.status === "blocked" ? "in_progress" : existing.status,
7465
- gate: { ...existing.gate, status: "stale" },
7466
- blocker: existing.status === "blocked" ? undefined : existing.blocker
7467
- };
7468
- assertNewIds({ ...plan, phases: plan.phases.filter((phase) => phase.id !== existing.id) }, updated);
7469
- return resetDraft({
7470
- ...plan,
7471
- phases: plan.phases.map((phase) => phase.id === existing.id ? updated : phase)
7472
- });
7473
- });
7474
- return result2(`Updated phase ${params.phaseId}.`, { record });
7891
+ const params = planApplyRevisionParametersSchema.parse(input);
7892
+ const workingDirectory = params.cwd ?? process.cwd();
7893
+ const request = params.mode === "create" ? { ...params, branch: params.branch ?? await currentBranch(workingDirectory) } : params;
7894
+ const record = await store.applyRevision(workingDirectory, request);
7895
+ return result2(`Applied revision ${record.document.revision} to ${record.id}.`, { record });
7475
7896
  }
7476
7897
  }),
7477
7898
  defineTool5({
@@ -7483,7 +7904,7 @@ function createPlanTools(_pi, _modes, store = createPlanStore()) {
7483
7904
  async execute(_id, input) {
7484
7905
  const params = planValidateParametersSchema.parse(input);
7485
7906
  const record = await store.read(params.cwd ?? process.cwd(), params.plan);
7486
- const issues = validatePlanDocument(record.document, { strict: params.strict });
7907
+ const issues = await validatePlanRecord(record, { strict: params.strict });
7487
7908
  const words = countDesignWords(record.document);
7488
7909
  return result2(issues.length ? issues.map((issue) => `- ${issue.severity}: ${issue.message}`).join(`
7489
7910
  `) : "Plan is valid.", { record, issues, designWordCount: words, ready: !issues.some((issue) => issue.severity === "error") });
@@ -7619,7 +8040,7 @@ function createPlanTools(_pi, _modes, store = createPlanStore()) {
7619
8040
  const resolution = await store.context(workingDirectory, params.plan);
7620
8041
  if (!resolution.record)
7621
8042
  throw new Error(resolution.ambiguous ? `Plan is ambiguous: ${resolution.candidates.map((item) => item.id).join(", ")}.` : "No matching plan.");
7622
- const cliPath = join14(resolveBundledAgentsDir(), "..", "dist", "cli.js");
8043
+ const cliPath = join15(resolveBundledAgentsDir(), "..", "dist", "cli.js");
7623
8044
  const command = [
7624
8045
  process.execPath,
7625
8046
  cliPath,
@@ -7714,8 +8135,8 @@ function renderExecutionPrompt(packet) {
7714
8135
  return [
7715
8136
  `Execute the durable Diffpi plan using this packet: ${JSON.stringify(packet)}.`,
7716
8137
  "Call plan_context first and keep plan tools as the source of truth for eligibility, ownership, status, gates, and commits.",
7717
- "Use SubagentWorkflow for deterministic multi-task coordination: pipeline dependent work, parallelize only tasks with non-overlapping declared file scopes, and use structured schemas for worker outcomes.",
7718
- "The extension cannot launch workflow children over RPC, so the active orchestrator must invoke SubagentWorkflow itself.",
8138
+ "Use bounded Agent delegation for eligible tasks. Run dependent tasks in order; parallelize only tasks with non-overlapping declared file scopes. Collect and verify worker results before changing plan state.",
8139
+ "Use a multi-agent SubagentWorkflow only when the user explicitly opts into that orchestration.",
7719
8140
  "Persist every transition, progress event, issue, and deviation. Do not edit PLAN.md directly. Delegated implementation workers never commit or restructure the plan.",
7720
8141
  "In commit mode, create one local commit after each phase passes its gates and do not push. In push mode, commit and push each phase, record pending CI, and launch a bounded background Worker to call watch_ci for the exact SHA and then plan_record_ci for the phase while the next phase executes. Collect that monitor before the next push and collect all monitors before plan completion; failed or timed-out CI blocks execution."
7721
8142
  ].join(" ");
@@ -7779,81 +8200,6 @@ ${dirty.stdout.trim()}`);
7779
8200
  prompt: renderExecutionPrompt(packet)
7780
8201
  });
7781
8202
  }
7782
- function newPhase(input) {
7783
- return {
7784
- id: input.id,
7785
- revision: 0,
7786
- title: input.title,
7787
- objective: input.objective,
7788
- dependencies: input.dependencies ?? [],
7789
- tasks: (input.tasks ?? []).map(newTask),
7790
- status: "pending",
7791
- gate: { phaseRevision: 0, status: "pending", results: [] }
7792
- };
7793
- }
7794
- function newTask(input) {
7795
- return {
7796
- id: input.id,
7797
- revision: 0,
7798
- title: input.title,
7799
- steps: input.steps,
7800
- dependencies: input.dependencies ?? [],
7801
- fileScopes: input.fileScopes ?? [],
7802
- acceptanceCriteria: input.acceptanceCriteria ?? [],
7803
- status: "pending"
7804
- };
7805
- }
7806
- function reconcileTasks(existing, drafts) {
7807
- const byId = new Map(existing.map((task) => [task.id, task]));
7808
- const requested = new Set(drafts.map((task) => task.id));
7809
- const protectedTask = existing.find((task) => (task.status === "completed" || task.status === "in_progress") && !requested.has(task.id));
7810
- if (protectedTask)
7811
- throw new Error(`${protectedTask.status === "completed" ? "Completed" : "Active"} task ${protectedTask.id} cannot be removed.`);
7812
- return drafts.map((draft) => {
7813
- const current = byId.get(draft.id);
7814
- if (current?.status === "completed" || current?.status === "in_progress")
7815
- return current;
7816
- return current ? {
7817
- ...newTask(draft),
7818
- revision: current.revision + 1,
7819
- status: current.status === "blocked" ? "pending" : current.status,
7820
- owner: current.status === "blocked" ? undefined : current.owner,
7821
- executionId: current.status === "blocked" ? undefined : current.executionId,
7822
- blocker: current.status === "blocked" ? undefined : current.blocker
7823
- } : newTask(draft);
7824
- });
7825
- }
7826
- function assertAuthoringRevision(plan, expected) {
7827
- if (plan.revision !== expected)
7828
- throw new Error(`Stale plan revision: expected ${expected}, found ${plan.revision}.`);
7829
- }
7830
- function assertAuthorable(plan, blockedPhaseId) {
7831
- if (plan.status === "completed")
7832
- throw new Error("Completed plans cannot be structurally changed.");
7833
- if (!plan.execution?.active)
7834
- return;
7835
- if (!blockedPhaseId)
7836
- throw new Error("An active execution owns this plan.");
7837
- const phase = getPhase2(plan, blockedPhaseId);
7838
- if (phase.status !== "blocked" && !phase.tasks.some((task) => task.status === "blocked"))
7839
- throw new Error("Planner may amend only blocked work during an active execution.");
7840
- }
7841
- function resetDraft(plan) {
7842
- if (plan.status === "blocked" && plan.execution?.active)
7843
- return { ...plan, status: "in_progress" };
7844
- return plan.status === "ready" || plan.status === "blocked" ? { ...plan, status: "draft" } : plan;
7845
- }
7846
- function allIds(plan) {
7847
- return new Set([plan.id, ...plan.phases.flatMap((phase) => [phase.id, ...phase.tasks.map((task) => task.id)])]);
7848
- }
7849
- function assertNewIds(plan, phase) {
7850
- const known = allIds(plan);
7851
- for (const candidate of [phase.id, ...phase.tasks.map((task) => task.id)]) {
7852
- if (known.has(candidate))
7853
- throw new Error(`Duplicate stable ID: ${candidate}.`);
7854
- known.add(candidate);
7855
- }
7856
- }
7857
8203
  function getPhase2(plan, phaseId) {
7858
8204
  const phase = plan.phases.find((item) => item.id === phaseId);
7859
8205
  if (!phase)
@@ -7891,10 +8237,10 @@ function result2(text, details = {}) {
7891
8237
 
7892
8238
  // src/tools/review.ts
7893
8239
  import { existsSync as existsSync2 } from "node:fs";
7894
- import { mkdir as mkdir8, writeFile as writeFile6 } from "node:fs/promises";
7895
- import { join as join16 } from "node:path";
8240
+ import { mkdir as mkdir7, readdir as readdir3, readFile as readFile12, rename as rename4, stat, unlink as unlink2, writeFile as writeFile7 } from "node:fs/promises";
8241
+ import { join as join17 } from "node:path";
7896
8242
  import { defineTool as defineTool6 } from "@earendil-works/pi-coding-agent";
7897
- import { z as z9 } from "zod";
8243
+ import { z as z11 } from "zod";
7898
8244
 
7899
8245
  // src/review/types.ts
7900
8246
  import { z as z8 } from "zod";
@@ -7919,9 +8265,24 @@ function yymmdd(date = new Date) {
7919
8265
  function reviewRecordName(target, date = new Date) {
7920
8266
  return `${yymmdd(date)}-${reviewSlug(target) || "uncommitted"}`;
7921
8267
  }
7922
- function dedupeFindings(findings) {
7923
- const rank = { BLOCKING: 3, CONSIDER: 2, NOTE: 1 };
7924
- const byKey = new Map;
8268
+ function localResponseMarker(threadId) {
8269
+ return `<!-- diffpi -->`;
8270
+ }
8271
+ function isLocalResponse(body) {
8272
+ return /^<!-- diffpi(?:-local-response:[A-Za-z0-9_-]+)? -->\n/m.test(body);
8273
+ }
8274
+ function parseReviewThreadAction(body) {
8275
+ const match = body.match(/^\[(REOPEN|RESOLVE|DELETE)\]\s*/i);
8276
+ if (!match)
8277
+ return { body };
8278
+ return {
8279
+ action: match[1].toLowerCase(),
8280
+ body: body.slice(match[0].length)
8281
+ };
8282
+ }
8283
+ function dedupeFindings(findings) {
8284
+ const rank = { BLOCKING: 3, CONSIDER: 2, NOTE: 1 };
8285
+ const byKey = new Map;
7925
8286
  for (const finding of findings) {
7926
8287
  const key = `${finding.file}:${finding.line}`;
7927
8288
  const existing = byKey.get(key);
@@ -7964,6 +8325,18 @@ function renderCommentBody(finding) {
7964
8325
  return `${prefix}${finding.body}${reference}`;
7965
8326
  }
7966
8327
  // src/review/review-markdown.ts
8328
+ import { z as z9 } from "zod";
8329
+ var reviewThreadRecordSchema = z9.object({
8330
+ id: z9.string().min(1),
8331
+ file: z9.string().nullable().optional().transform((value) => value ?? undefined),
8332
+ line: z9.number().int().positive().nullable().optional().transform((value) => value ?? undefined),
8333
+ body: z9.string(),
8334
+ author: z9.string().optional(),
8335
+ resolved: z9.boolean(),
8336
+ addressed: z9.boolean().optional(),
8337
+ question: z9.boolean(),
8338
+ replies: z9.array(z9.string()).optional()
8339
+ });
7967
8340
  function renderReviewDoc(input) {
7968
8341
  const anchored = dedupeFindings(input.findings).filter((finding) => finding.line > 0);
7969
8342
  const lines = [`# Review: ${input.title}`, "", "## Metadata"];
@@ -8005,6 +8378,88 @@ function renderReviewDoc(input) {
8005
8378
  `).trimEnd()}
8006
8379
  `;
8007
8380
  }
8381
+ function renderThreadArtifact(title, target, threads, options = {}) {
8382
+ const records = threads.map((thread) => ({
8383
+ id: thread.id,
8384
+ file: thread.file,
8385
+ line: thread.line,
8386
+ body: thread.body,
8387
+ author: thread.author,
8388
+ resolved: thread.resolved,
8389
+ addressed: thread.addressed,
8390
+ question: thread.question,
8391
+ replies: thread.replies
8392
+ }));
8393
+ const payload = Buffer.from(JSON.stringify(records), "utf8").toString("base64url");
8394
+ const lines = [
8395
+ `<!-- diffpi-threads:${payload} -->`,
8396
+ `# Review threads: ${title}`,
8397
+ "",
8398
+ "## Metadata",
8399
+ "",
8400
+ `- Target: ${target}`,
8401
+ `- Pulled: ${options.timestamp ?? new Date().toISOString()}`
8402
+ ];
8403
+ if (options.number !== undefined)
8404
+ lines.push(`- PR/MR: #${options.number}${options.url ? ` — ${options.url}` : ""}`);
8405
+ lines.push("", "## Replies", "");
8406
+ for (const thread of threads) {
8407
+ const id = Buffer.from(thread.id, "utf8").toString("base64url");
8408
+ lines.push(`### ${thread.file ?? "review"}:${thread.line ?? "n/a"} (${thread.id})`, "", `<!-- diffpi-reply-start:${id} -->`, thread.reply ?? "", `<!-- diffpi-reply-end:${id} -->`, "");
8409
+ }
8410
+ lines.push("## Source comments", "");
8411
+ for (const thread of threads) {
8412
+ lines.push(`### ${thread.file ?? "review"}:${thread.line ?? "n/a"} — ${thread.author ?? "unknown"}`, "", `Thread: ${thread.id}`, `Status: ${thread.resolved ? "resolved" : thread.addressed ? "addressed" : "open"}`, "", "**Source comment**", "", thread.body, "", "**Recorded response**", "", thread.reply?.trim() || "_No response recorded._", "", "---", "");
8413
+ }
8414
+ return `${lines.join(`
8415
+ `).trimEnd()}
8416
+ `;
8417
+ }
8418
+ function parseThreadArtifact(content) {
8419
+ const payload = content.match(/^<!-- diffpi-threads:([A-Za-z0-9_-]+) -->$/m)?.[1];
8420
+ if (!payload)
8421
+ throw new Error("This file is not a Diffpi thread artifact.");
8422
+ let threads;
8423
+ try {
8424
+ const decoded = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
8425
+ threads = z9.array(reviewThreadRecordSchema).parse(decoded);
8426
+ } catch {
8427
+ throw new Error("Cannot parse the Diffpi thread artifact payload.");
8428
+ }
8429
+ const replies = content.split(/^## Source comments$/m, 1)[0] ?? "";
8430
+ return threads.map((thread) => {
8431
+ const id = Buffer.from(thread.id, "utf8").toString("base64url");
8432
+ const startMarker = `<!-- diffpi-reply-start:${id} -->
8433
+ `;
8434
+ const endMarker = `
8435
+ <!-- diffpi-reply-end:${id} -->`;
8436
+ const start = replies.indexOf(startMarker);
8437
+ const end = start < 0 ? -1 : replies.indexOf(endMarker, start + startMarker.length);
8438
+ const reply = start >= 0 && end >= 0 ? replies.slice(start + startMarker.length, end).trim() : "";
8439
+ return reply ? { ...thread, reply } : thread;
8440
+ });
8441
+ }
8442
+ function upsertThreadReply(content, threadId, body, question, resolved) {
8443
+ const threads = parseThreadArtifact(content);
8444
+ const thread = threads.find((candidate) => candidate.id === threadId);
8445
+ if (!thread)
8446
+ throw new Error(`Review thread ${threadId} was not found in the local artifact.`);
8447
+ thread.reply = body;
8448
+ thread.addressed = true;
8449
+ if (question !== undefined)
8450
+ thread.question = question;
8451
+ if (resolved !== undefined)
8452
+ thread.resolved = resolved;
8453
+ const title = content.match(/^# Review threads: (.+)$/m)?.[1] ?? "review";
8454
+ const target = content.match(/^- Target: (.+)$/m)?.[1] ?? "local";
8455
+ const timestamp = content.match(/^- Pulled: (.+)$/m)?.[1];
8456
+ const pr = content.match(/^- PR\/MR: #(\d+)(?: — (.+))?$/m);
8457
+ return renderThreadArtifact(title, target, threads, {
8458
+ timestamp,
8459
+ number: pr ? Number.parseInt(pr[1], 10) : undefined,
8460
+ url: pr?.[2]
8461
+ });
8462
+ }
8008
8463
  // src/review/github-review-backend.ts
8009
8464
  function GitHubReviewBackend(vcs, number) {
8010
8465
  const pendingReview = async () => {
@@ -8066,6 +8521,9 @@ function GitHubReviewBackend(vcs, number) {
8066
8521
  id: thread.id,
8067
8522
  file: thread.path ?? undefined,
8068
8523
  line: thread.line ?? undefined,
8524
+ rootCommentId: comment?.id,
8525
+ commentIds: nodes.flatMap((node) => [node.id, node.databaseId?.toString()].filter((id) => Boolean(id))),
8526
+ commentNodeIds: nodes.flatMap((node) => node.id ? [node.id] : []),
8069
8527
  body,
8070
8528
  author: comment?.author?.login,
8071
8529
  resolved: thread.isResolved,
@@ -8075,6 +8533,7 @@ function GitHubReviewBackend(vcs, number) {
8075
8533
  });
8076
8534
  };
8077
8535
  return {
8536
+ kind: "remote",
8078
8537
  async stage(draft) {
8079
8538
  const pending = await pendingReview();
8080
8539
  if (!pending) {
@@ -8132,6 +8591,33 @@ function GitHubReviewBackend(vcs, number) {
8132
8591
  await ghChecked(args);
8133
8592
  }
8134
8593
  },
8594
+ async readDraft() {
8595
+ const pending = await pendingReview();
8596
+ if (!pending)
8597
+ return { comments: [], body: "" };
8598
+ const review = await ghChecked(["api", `/repos/${vcs.owner}/${vcs.repo}/pulls/${number}/reviews/${pending.id}`]);
8599
+ const comments = await ghChecked([
8600
+ "api",
8601
+ `/repos/${vcs.owner}/${vcs.repo}/pulls/${number}/reviews/${pending.id}/comments`
8602
+ ]);
8603
+ let reviewData;
8604
+ let commentData;
8605
+ try {
8606
+ reviewData = JSON.parse(review.stdout);
8607
+ commentData = JSON.parse(comments.stdout);
8608
+ } catch {
8609
+ throw new Error("Cannot parse the pending GitHub review as JSON.");
8610
+ }
8611
+ return {
8612
+ body: reviewData.body ?? "",
8613
+ comments: commentData.map((comment) => ({
8614
+ file: comment.path,
8615
+ line: comment.line ?? comment.original_line ?? undefined,
8616
+ side: comment.side ?? undefined,
8617
+ body: comment.body
8618
+ }))
8619
+ };
8620
+ },
8135
8621
  listThreads,
8136
8622
  async reply(input) {
8137
8623
  const threads = await listThreads();
@@ -8148,14 +8634,32 @@ function GitHubReviewBackend(vcs, number) {
8148
8634
  `body=${input.body}`
8149
8635
  ]);
8150
8636
  }
8151
- if (input.resolve) {
8637
+ if (input.resolve)
8638
+ await this.setResolved?.(input.threadId, true);
8639
+ },
8640
+ async setResolved(threadId, resolved) {
8641
+ await ghChecked([
8642
+ "api",
8643
+ "graphql",
8644
+ "-f",
8645
+ `query=${resolved ? GITHUB_RESOLVE_MUTATION : GITHUB_UNRESOLVE_MUTATION}`,
8646
+ "-f",
8647
+ `threadId=${threadId}`
8648
+ ]);
8649
+ },
8650
+ async deleteThread(threadId) {
8651
+ const thread = (await listThreads()).find((candidate) => candidate.id === threadId);
8652
+ const commentNodeIds = thread?.commentNodeIds ?? (thread?.rootCommentId ? [thread.rootCommentId] : []);
8653
+ if (!commentNodeIds.length)
8654
+ throw new Error(`Cannot delete GitHub thread ${threadId}: comment node IDs are missing.`);
8655
+ for (const commentId of commentNodeIds) {
8152
8656
  await ghChecked([
8153
8657
  "api",
8154
8658
  "graphql",
8155
8659
  "-f",
8156
- `query=${GITHUB_RESOLVE_MUTATION}`,
8660
+ `query=${GITHUB_DELETE_COMMENT_MUTATION}`,
8157
8661
  "-f",
8158
- `threadId=${input.threadId}`
8662
+ `commentId=${commentId}`
8159
8663
  ]);
8160
8664
  }
8161
8665
  },
@@ -8174,11 +8678,13 @@ function GitHubReviewBackend(vcs, number) {
8174
8678
  function githubReviewSubmissionEndpoint(owner, repo, id, pendingReviewId) {
8175
8679
  return pendingReviewId ? `/repos/${owner}/${repo}/pulls/${id}/reviews/${pendingReviewId}/events` : `/repos/${owner}/${repo}/pulls/${id}/reviews`;
8176
8680
  }
8177
- var GITHUB_THREADS_QUERY = `query($owner:String!,$repo:String!,$number:Int!,$after:String){repository(owner:$owner,name:$repo){pullRequest(number:$number){reviewThreads(first:100,after:$after){nodes{id,isResolved,path,line,comments(first:100){nodes{body,author{login}}}}pageInfo{hasNextPage,endCursor}}}}}`;
8681
+ var GITHUB_THREADS_QUERY = `query($owner:String!,$repo:String!,$number:Int!,$after:String){repository(owner:$owner,name:$repo){pullRequest(number:$number){reviewThreads(first:100,after:$after){nodes{id,isResolved,path,line,comments(first:100){nodes{id,databaseId,body,author{login}}}}pageInfo{hasNextPage,endCursor}}}}}`;
8178
8682
  var GITHUB_ADD_THREAD_MUTATION = `mutation($reviewId:ID!,$body:String!,$path:String!,$line:Int!,$side:DiffSide!){addPullRequestReviewThread(input:{pullRequestReviewId:$reviewId,body:$body,path:$path,line:$line,side:$side}){thread{id}}}`;
8179
8683
  var GITHUB_ADD_FILE_THREAD_MUTATION = `mutation($reviewId:ID!,$body:String!,$path:String!){addPullRequestReviewThread(input:{pullRequestReviewId:$reviewId,body:$body,path:$path,subjectType:FILE}){thread{id}}}`;
8180
8684
  var GITHUB_REPLY_MUTATION = `mutation($threadId:ID!,$body:String!){addPullRequestReviewThreadReply(input:{pullRequestReviewThreadId:$threadId,body:$body}){comment{id}}}`;
8181
8685
  var GITHUB_RESOLVE_MUTATION = `mutation($threadId:ID!){resolveReviewThread(input:{threadId:$threadId}){thread{isResolved}}}`;
8686
+ var GITHUB_UNRESOLVE_MUTATION = `mutation($threadId:ID!){unresolveReviewThread(input:{threadId:$threadId}){thread{isResolved}}}`;
8687
+ var GITHUB_DELETE_COMMENT_MUTATION = `mutation($commentId:ID!){deletePullRequestReviewComment(input:{id:$commentId}){clientMutationId}}`;
8182
8688
 
8183
8689
  // src/review/gitlab-review-backend.ts
8184
8690
  function GitLabReviewBackend(vcs, number) {
@@ -8215,6 +8721,7 @@ function GitLabReviewBackend(vcs, number) {
8215
8721
  });
8216
8722
  };
8217
8723
  return {
8724
+ kind: "remote",
8218
8725
  async stage(draft) {
8219
8726
  const endpoint = `${mergeRequestEndpoint()}/draft_notes`;
8220
8727
  if (draft.body.trim()) {
@@ -8243,6 +8750,36 @@ function GitLabReviewBackend(vcs, number) {
8243
8750
  });
8244
8751
  }
8245
8752
  },
8753
+ async readDraft() {
8754
+ const result = await glabChecked(["api", `${mergeRequestEndpoint()}/draft_notes`]);
8755
+ let notes;
8756
+ try {
8757
+ notes = JSON.parse(result.stdout);
8758
+ } catch {
8759
+ throw new Error("Cannot parse GitLab draft notes as JSON.");
8760
+ }
8761
+ const comments = [];
8762
+ const body = [];
8763
+ for (const note of notes) {
8764
+ if (!note.note)
8765
+ continue;
8766
+ const file = note.position?.new_path ?? note.position?.old_path;
8767
+ const line = note.position?.new_line ?? note.position?.old_line;
8768
+ if (file && line) {
8769
+ comments.push({
8770
+ file,
8771
+ line,
8772
+ side: note.position?.new_line ? "RIGHT" : "LEFT",
8773
+ body: note.note
8774
+ });
8775
+ } else {
8776
+ body.push(note.note);
8777
+ }
8778
+ }
8779
+ return { comments, body: body.join(`
8780
+
8781
+ `) };
8782
+ },
8246
8783
  listThreads,
8247
8784
  async reply(input) {
8248
8785
  const endpoint = `${mergeRequestEndpoint()}/discussions/${encodeURIComponent(input.threadId)}`;
@@ -8254,7 +8791,15 @@ function GitLabReviewBackend(vcs, number) {
8254
8791
  });
8255
8792
  }
8256
8793
  if (input.resolve)
8257
- await glabChecked(["api", "--method", "PUT", `${endpoint}?resolved=true`]);
8794
+ await this.setResolved?.(input.threadId, true);
8795
+ },
8796
+ async setResolved(threadId, resolved) {
8797
+ const endpoint = `${mergeRequestEndpoint()}/discussions/${encodeURIComponent(threadId)}`;
8798
+ await glabChecked(["api", "--method", "PUT", `${endpoint}?resolved=${resolved}`]);
8799
+ },
8800
+ async deleteThread(threadId) {
8801
+ const endpoint = `${mergeRequestEndpoint()}/discussions/${encodeURIComponent(threadId)}`;
8802
+ await glabChecked(["api", "--method", "DELETE", endpoint]);
8258
8803
  },
8259
8804
  async publish(event) {
8260
8805
  assertReviewEventSupported(vcs.provider, event);
@@ -8294,20 +8839,11 @@ function hasGitlabDraftNotes(input) {
8294
8839
  }
8295
8840
  }
8296
8841
 
8297
- // src/review/review-backend.ts
8298
- function createRemoteReviewBackend(vcs, number) {
8299
- if (vcs.provider === "github")
8300
- return GitHubReviewBackend(vcs, number);
8301
- if (vcs.provider === "gitlab")
8302
- return GitLabReviewBackend(vcs, number);
8303
- throw new Error("A remote review backend requires a GitHub or GitLab repository.");
8304
- }
8305
- // src/review/local-reviews.ts
8306
- import { mkdir as mkdir7, readdir as readdir2, readFile as readFile9, unlink as unlink2, writeFile as writeFile5 } from "node:fs/promises";
8307
- import { join as join15 } from "node:path";
8842
+ // src/review/local-review-backend.ts
8843
+ import { readFile as readFile10, writeFile as writeFile5 } from "node:fs/promises";
8308
8844
 
8309
8845
  // src/extensions/tuicrx.ts
8310
- import { readFile as readFile8, realpath as realpath4 } from "node:fs/promises";
8846
+ import { readFile as readFile9, realpath as realpath4 } from "node:fs/promises";
8311
8847
  import { resolve as resolve4 } from "node:path";
8312
8848
  async function tuicrAvailable() {
8313
8849
  return Boolean(await findExecutable("tuicr"));
@@ -8375,6 +8911,11 @@ async function resolveReviewSession(cwd, target) {
8375
8911
  }
8376
8912
  return resolveSession(cwd, target.branch);
8377
8913
  }
8914
+ async function resolvePublishSession(cwd, target) {
8915
+ if (target.owner && target.repo && target.number !== undefined)
8916
+ return resolvePrSession(cwd, target.owner, target.repo, target.number);
8917
+ return resolveSession(cwd, target.branch);
8918
+ }
8378
8919
  async function resolvePrSession(cwd, owner, repo, number) {
8379
8920
  const coordinate = `${owner}/${repo}`.toLowerCase();
8380
8921
  const sessions = await listSessions(cwd);
@@ -8399,7 +8940,7 @@ async function findMatchingSession(sessions, cwd, branch) {
8399
8940
  return;
8400
8941
  }
8401
8942
  async function readSession(path) {
8402
- const content = await readFile8(path, "utf8");
8943
+ const content = await readFile9(path, "utf8");
8403
8944
  try {
8404
8945
  return JSON.parse(content);
8405
8946
  } catch {
@@ -8409,6 +8950,8 @@ async function readSession(path) {
8409
8950
  function toLocalReviewThreads(session) {
8410
8951
  const threads = [];
8411
8952
  const add = (comment, location = {}) => {
8953
+ if (isLocalResponse(comment.content))
8954
+ return;
8412
8955
  const author = commentAuthor(comment);
8413
8956
  threads.push({
8414
8957
  id: comment.id ?? `local-${threads.length + 1}`,
@@ -8434,6 +8977,54 @@ function toLocalReviewThreads(session) {
8434
8977
  }
8435
8978
  return threads;
8436
8979
  }
8980
+ function toFindings(session, options = {}) {
8981
+ const comments = [];
8982
+ const include = (comment) => (!options.agentOnly || commentAuthor(comment)?.startsWith("Agent: ")) && (!options.excludeLocalResponses || !isLocalResponse(comment.content));
8983
+ const publishableBody = (comment) => {
8984
+ const author = commentAuthor(comment);
8985
+ const route = author?.match(/^Agent:\s*(.+)$/)?.[1];
8986
+ return route ? withRemoteProvenance(comment.content, route) : comment.content;
8987
+ };
8988
+ const bodyParts = (session.review_comments ?? []).flatMap((comment) => include(comment) ? [publishableBody(comment)] : []);
8989
+ for (const [file, entry] of Object.entries(session.files ?? {})) {
8990
+ for (const fileComment of entry.file_comments ?? []) {
8991
+ if (!include(fileComment))
8992
+ continue;
8993
+ const comment = {
8994
+ file,
8995
+ body: fileComment.content,
8996
+ ...fileComment.id ? { sourceCommentId: String(fileComment.id) } : {}
8997
+ };
8998
+ const author = commentAuthor(fileComment);
8999
+ if (author)
9000
+ comment.author = author;
9001
+ comments.push(comment);
9002
+ }
9003
+ for (const [lineKey, lineComments] of Object.entries(entry.line_comments ?? {})) {
9004
+ const line = Number.parseInt(lineKey, 10);
9005
+ if (!Number.isFinite(line))
9006
+ continue;
9007
+ for (const lineComment of lineComments) {
9008
+ if (!include(lineComment))
9009
+ continue;
9010
+ const comment = {
9011
+ file,
9012
+ line,
9013
+ side: lineComment.side === "old" ? "LEFT" : "RIGHT",
9014
+ body: lineComment.content,
9015
+ ...lineComment.id ? { sourceCommentId: String(lineComment.id) } : {}
9016
+ };
9017
+ const author = commentAuthor(lineComment);
9018
+ if (author)
9019
+ comment.author = author;
9020
+ comments.push(comment);
9021
+ }
9022
+ }
9023
+ }
9024
+ return { comments, body: bodyParts.join(`
9025
+
9026
+ `) };
9027
+ }
8437
9028
  async function requireTuicr() {
8438
9029
  if (!await tuicrAvailable())
8439
9030
  throw new Error("tuicr is not installed or is not available on PATH.");
@@ -8449,83 +9040,195 @@ async function canonicalPath3(path) {
8449
9040
  }
8450
9041
  }
8451
9042
 
8452
- // src/review/local-reviews.ts
8453
- async function captureLocalReview(input) {
8454
- const id = reviewSlug(input.branch) || "local-review";
8455
- const dir = join15(await reviewsDir(input.cwd, input.homeDir), id);
8456
- await mkdir7(dir, { recursive: true });
8457
- const revision = await nextRevision(dir);
8458
- const output = await readFile9(input.session.path, "utf8");
8459
- const comments = toLocalReviewThreads(await readSession(input.session.path));
8460
- const dump = {
8461
- schemaVersion: 1,
8462
- id,
8463
- revision,
8464
- branch: input.branch,
8465
- base: input.base,
8466
- createdAt: (input.now ?? (() => new Date))().toISOString(),
8467
- diff: input.diff,
8468
- comments,
8469
- tuicr: { slug: input.session.slug, output }
9043
+ // src/review/local-review-backend.ts
9044
+ function LocalReviewBackend(options) {
9045
+ return {
9046
+ kind: "local",
9047
+ async stage(draft) {
9048
+ for (const comment of draft.comments) {
9049
+ await addComment(options.session, comment.body, {
9050
+ targetFile: comment.file,
9051
+ line: comment.line,
9052
+ side: comment.side === "LEFT" ? "old" : "new",
9053
+ username: options.author
9054
+ });
9055
+ }
9056
+ if (draft.body.trim())
9057
+ await addComment(options.session, draft.body, { username: options.author });
9058
+ },
9059
+ async readDraft() {
9060
+ return toFindings(await readSession(options.session), { excludeLocalResponses: true });
9061
+ },
9062
+ async listThreads() {
9063
+ try {
9064
+ return parseThreadArtifact(await readFile10(options.artifactPath, "utf8"));
9065
+ } catch (error) {
9066
+ if (error.code === "ENOENT")
9067
+ return [];
9068
+ throw error;
9069
+ }
9070
+ },
9071
+ async reply(input) {
9072
+ const content = await readFile10(options.artifactPath, "utf8");
9073
+ await writeFile5(options.artifactPath, upsertThreadReply(content, input.threadId, input.body, input.question, input.resolve), "utf8");
9074
+ },
9075
+ async publish() {
9076
+ throw new Error("Promote a local draft through a remote review backend before publishing it.");
9077
+ }
8470
9078
  };
8471
- const path = join15(dir, `${revision}.json`);
8472
- await writeFile5(path, `${JSON.stringify(dump, null, 2)}
8473
- `, { encoding: "utf8", flag: "wx" });
8474
- await unlink2(input.session.path);
8475
- return { path, dump };
8476
9079
  }
8477
- async function nextRevision(dir) {
8478
- return await latestRevision(dir) + 1;
9080
+
9081
+ // src/review/review-backend.ts
9082
+ function createRemoteReviewBackend(vcs, number) {
9083
+ if (vcs.provider === "github")
9084
+ return GitHubReviewBackend(vcs, number);
9085
+ if (vcs.provider === "gitlab")
9086
+ return GitLabReviewBackend(vcs, number);
9087
+ throw new Error("A remote review backend requires a GitHub or GitLab repository.");
9088
+ }
9089
+ function createLocalReviewBackend(options) {
9090
+ return LocalReviewBackend(options);
9091
+ }
9092
+ // src/review/review-state.ts
9093
+ import { createHash as createHash4 } from "node:crypto";
9094
+ import { readFile as readFile11, rename as rename3, writeFile as writeFile6 } from "node:fs/promises";
9095
+ import { join as join16 } from "node:path";
9096
+ import { z as z10 } from "zod";
9097
+ var reviewPublicationStateSchema = z10.object({
9098
+ target: z10.string().optional(),
9099
+ bodies: z10.array(z10.string()).default([]),
9100
+ comments: z10.array(z10.string()).default([]),
9101
+ stagedComments: z10.array(z10.string()).default([]),
9102
+ replies: z10.array(z10.string()).default([]),
9103
+ overlayPath: z10.string().optional()
9104
+ });
9105
+ function reviewBodyFingerprint(body) {
9106
+ return digest(body);
8479
9107
  }
8480
- async function latestRevision(dir) {
9108
+ function reviewCommentFingerprint(comment) {
9109
+ return digest([comment.file, String(comment.line), comment.side ?? "RIGHT", comment.body].join("\x00"));
9110
+ }
9111
+ function reviewReplyFingerprint(threadId, body) {
9112
+ return digest(`${threadId}\x00${body}`);
9113
+ }
9114
+ function unpublishedReviewComments(comments, knownFingerprints) {
9115
+ return comments.filter((comment) => !knownFingerprints.has(reviewCommentFingerprint(comment)));
9116
+ }
9117
+ async function loadReviewPublicationState(cwd, vcs, number, homeDir) {
9118
+ const target = `${vcs.provider}:${vcs.owner}/${vcs.repo}#${number}`;
9119
+ const path = join16(await sessionsDir(cwd, homeDir), `review-publish-${digest(target).slice(0, 16)}.json`);
8481
9120
  try {
8482
- return (await readdir2(dir)).reduce((latest, name) => {
8483
- const match = name.match(/^(\d+)\.json$/);
8484
- return match ? Math.max(latest, Number(match[1])) : latest;
8485
- }, 0);
9121
+ const parsed = reviewPublicationStateSchema.parse(JSON.parse(await readFile11(path, "utf8")));
9122
+ return { path, state: { ...parsed, target } };
8486
9123
  } catch (error) {
8487
- if (error.code === "ENOENT")
8488
- return 0;
9124
+ if (error.code === "ENOENT") {
9125
+ return { path, state: { target, bodies: [], comments: [], stagedComments: [], replies: [] } };
9126
+ }
9127
+ if (error instanceof SyntaxError || error instanceof z10.ZodError) {
9128
+ throw new Error(`Cannot parse review publication state: ${path}`);
9129
+ }
8489
9130
  throw error;
8490
9131
  }
8491
9132
  }
9133
+ async function saveReviewPublicationState(path, state) {
9134
+ const temp = `${path}.${process.pid}.tmp`;
9135
+ await writeFile6(temp, `${JSON.stringify(state, null, 2)}
9136
+ `, "utf8");
9137
+ await rename3(temp, path);
9138
+ }
9139
+ function digest(value) {
9140
+ return createHash4("sha256").update(value).digest("hex");
9141
+ }
8492
9142
  // src/tools/review.ts
8493
- var contextSchema = z9.object({
8494
- cwd: z9.string().optional(),
8495
- target: z9.string().optional(),
8496
- workingTree: z9.boolean().optional()
9143
+ var contextSchema = z11.object({
9144
+ cwd: z11.string().optional(),
9145
+ target: z11.string().optional(),
9146
+ workingTree: z11.boolean().optional()
8497
9147
  });
8498
- var localSchema = contextSchema.extend({ local: z9.boolean().optional() });
9148
+ var localSchema = contextSchema.extend({ local: z11.boolean().optional() });
8499
9149
  var openSchema = localSchema.extend({
8500
- title: z9.string().optional(),
8501
- intent: z9.string().optional(),
8502
- issueUrl: z9.string().url().optional(),
8503
- base: z9.string().optional()
9150
+ title: z11.string().optional(),
9151
+ intent: z11.string().optional(),
9152
+ issueUrl: z11.string().url().optional(),
9153
+ base: z11.string().optional()
8504
9154
  });
8505
9155
  var submitSchema = localSchema.extend({
8506
9156
  findings: findingsSchema,
8507
- overallIssues: z9.array(z9.string()).optional(),
8508
- notVerified: z9.array(z9.string()).optional(),
8509
- title: z9.string().optional()
9157
+ overallIssues: z11.array(z11.string()).optional(),
9158
+ notVerified: z11.array(z11.string()).optional(),
9159
+ title: z11.string().optional()
8510
9160
  });
8511
9161
  var addCommentSchema = localSchema.extend({
8512
- body: z9.string().min(1),
8513
- file: z9.string().min(1),
8514
- line: z9.number().int().positive(),
8515
- side: z9.enum(["LEFT", "RIGHT"]).optional()
9162
+ body: z11.string().min(1),
9163
+ file: z11.string().min(1),
9164
+ line: z11.number().int().positive(),
9165
+ side: z11.enum(["LEFT", "RIGHT"]).optional()
8516
9166
  });
8517
9167
  var respondSchema = localSchema.extend({
8518
- threadId: z9.string().min(1),
8519
- body: z9.string().min(1),
8520
- question: z9.boolean().optional(),
8521
- resolve: z9.boolean().optional()
9168
+ threadId: z11.string().min(1),
9169
+ body: z11.string().min(1),
9170
+ question: z11.boolean().optional(),
9171
+ resolve: z11.boolean().optional()
8522
9172
  });
8523
9173
  var publishSchema = localSchema.extend({
8524
- status: z9.enum(["COMMENT", "APPROVE", "REQUEST_CHANGES", "CLOSE"]).optional()
9174
+ status: z11.enum(["COMMENT", "APPROVE", "REQUEST_CHANGES", "CLOSE"]).optional()
8525
9175
  });
8526
9176
  var completeSchema = localSchema.extend({
8527
- action: z9.enum(["approve", "reject", "abandon"]).optional()
9177
+ action: z11.enum(["approve", "reject", "abandon"]).optional()
8528
9178
  });
9179
+ function hasReviewDraft(comments, body) {
9180
+ return comments.length > 0 || body.trim().length > 0;
9181
+ }
9182
+ function reviewBrowserCommand(url, platform = process.platform) {
9183
+ return platform === "darwin" ? { command: "open", args: [url] } : platform === "win32" ? { command: "cmd", args: ["/c", "start", "", url] } : { command: "xdg-open", args: [url] };
9184
+ }
9185
+ async function openReviewUrl(url, execute = run, platform = process.platform) {
9186
+ const launch = reviewBrowserCommand(url, platform);
9187
+ try {
9188
+ return (await execute(launch.command, launch.args)).code === 0;
9189
+ } catch {
9190
+ return false;
9191
+ }
9192
+ }
9193
+ function partitionReviewComments(comments, knownFingerprints, model) {
9194
+ const normalized = comments.map((comment) => {
9195
+ const published = { ...comment, body: withCommentProvenance(comment, model) };
9196
+ return { source: comment, published, fingerprint: reviewCommentFingerprint(published) };
9197
+ });
9198
+ return {
9199
+ checkpointed: normalized.filter((comment) => knownFingerprints.has(comment.fingerprint)),
9200
+ candidates: normalized.filter((comment) => !knownFingerprints.has(comment.fingerprint))
9201
+ };
9202
+ }
9203
+ function reviewResponseResolution(question, requested) {
9204
+ return question ? false : requested ?? false;
9205
+ }
9206
+ function workingTreeReplyDraft(thread, body) {
9207
+ if (!thread.file)
9208
+ return { comments: [], body };
9209
+ return {
9210
+ comments: [
9211
+ {
9212
+ file: thread.file,
9213
+ ...thread.line === undefined ? {} : { line: thread.line, side: "RIGHT" },
9214
+ body
9215
+ }
9216
+ ],
9217
+ body: ""
9218
+ };
9219
+ }
9220
+ function resolveReviewThread(comment, threads) {
9221
+ const sourceCommentId = comment.sourceCommentId;
9222
+ if (sourceCommentId) {
9223
+ const identified = threads.find((thread) => thread.id === sourceCommentId || thread.rootCommentId === sourceCommentId || thread.commentIds?.includes(sourceCommentId));
9224
+ if (identified)
9225
+ return identified;
9226
+ }
9227
+ const matches = threads.filter((thread) => thread.file === comment.file && (thread.line ?? undefined) === (comment.line ?? undefined));
9228
+ if (matches.length > 1)
9229
+ throw new Error(`Ambiguous remote review threads at ${comment.file}:${comment.line ?? "file"}: ${matches.map((thread) => thread.id).join(", ")}.`);
9230
+ return matches[0];
9231
+ }
8529
9232
  async function workingTreeDiff(cwd) {
8530
9233
  const tracked = await run("git", ["-C", cwd, "diff", "HEAD"], { capture: "unbounded" });
8531
9234
  if (tracked.code !== 0)
@@ -8558,7 +9261,9 @@ function createReviewTools() {
8558
9261
  const review = await resolveReviewContext(resolveWorkingDirectory(params), params.target);
8559
9262
  const store = await ensureStore(review.cwd);
8560
9263
  const env = { ide: detectIde(), mux: detectMux(), shell: detectShell() };
8561
- const session = await resolveTuicrSession(review, Boolean(params.local || params.workingTree));
9264
+ const session = await resolveTuicrSession(review, Boolean(params.local || params.workingTree)).catch(() => {
9265
+ return;
9266
+ });
8562
9267
  const baseRef = review.pr?.baseRef ?? (review.forge ? await review.forge.defaultBranch() : "local");
8563
9268
  const backend = params.local || params.workingTree ? "tuicr" : review.forge?.provider ?? "unsupported";
8564
9269
  return result3([
@@ -8582,6 +9287,21 @@ function createReviewTools() {
8582
9287
  });
8583
9288
  }
8584
9289
  }),
9290
+ defineTool6({
9291
+ name: "review_status",
9292
+ label: "review status",
9293
+ description: "Report local and remote review lifecycle status without requiring a forge or tuicr.",
9294
+ promptSnippet: "Call review_status for review lifecycle state",
9295
+ promptGuidelines: ["Use this for status even when no forge or tuicr binary is available."],
9296
+ parameters: parameters2(localSchema),
9297
+ executionMode: "parallel",
9298
+ async execute(_id, input) {
9299
+ const params = localSchema.parse(input);
9300
+ const review = await resolveReviewContext(resolveWorkingDirectory(params), params.target);
9301
+ const status = await collectReviewStatus(review);
9302
+ return result3(status.text, status.details);
9303
+ }
9304
+ }),
8585
9305
  defineTool6({
8586
9306
  name: "review_new",
8587
9307
  label: "review new",
@@ -8625,6 +9345,31 @@ ${openMessage}`, {
8625
9345
  });
8626
9346
  }
8627
9347
  }),
9348
+ defineTool6({
9349
+ name: "review_open",
9350
+ label: "review open",
9351
+ description: "Open an existing remote PR/MR in the system browser; never creates one.",
9352
+ promptSnippet: "Call review_open to open an existing PR/MR",
9353
+ promptGuidelines: ["Direct users to review_new when no remote review exists."],
9354
+ parameters: parameters2(localSchema),
9355
+ executionMode: "sequential",
9356
+ async execute(_id, input) {
9357
+ const params = localSchema.parse(input);
9358
+ const review = await resolveReviewContext(resolveWorkingDirectory(params), params.target);
9359
+ if (params.local || params.workingTree)
9360
+ return launchLocalReview(review, true);
9361
+ if (!review.forge)
9362
+ return result3(`${unsupportedForgeMessage()} Use review_new with local=true for an offline review.`);
9363
+ if (!review.pr)
9364
+ return result3("No remote PR/MR exists. Use review_new to create a draft review first.");
9365
+ const opened = await openReviewUrl(review.pr.url);
9366
+ return result3(`${opened ? "Opened" : "Open this URL"} PR/MR #${review.pr.number}: ${review.pr.url}`, {
9367
+ pr: review.pr,
9368
+ opened,
9369
+ url: review.pr.url
9370
+ });
9371
+ }
9372
+ }),
8628
9373
  defineTool6({
8629
9374
  name: "review_edit",
8630
9375
  label: "review edit",
@@ -8721,7 +9466,7 @@ ${openMessage}`, {
8721
9466
  const gates = await runMiseGates(review.cwd);
8722
9467
  const baseRef = review.pr?.baseRef ?? (review.forge ? await review.forge.defaultBranch() : "local");
8723
9468
  const artifact = await newReviewArtifactPath(review.cwd, params.local || params.workingTree || !review.pr ? "uncommitted" : await reviewTargetId(review));
8724
- await writeFile6(artifact, renderReviewDoc({
9469
+ await writeFile7(artifact, renderReviewDoc({
8725
9470
  title: params.title ?? review.pr?.title ?? review.vcs.branch,
8726
9471
  number: useLocalBackend ? undefined : review.pr?.number,
8727
9472
  url: useLocalBackend ? undefined : review.pr?.url,
@@ -8744,21 +9489,17 @@ ${openMessage}`, {
8744
9489
  count: findings.length
8745
9490
  });
8746
9491
  }
8747
- for (const comment of comments) {
8748
- await addComment(session.path, comment.body, {
8749
- targetFile: comment.file,
8750
- line: comment.line,
8751
- side: comment.side === "LEFT" ? "old" : "new",
8752
- username: localReviewAuthor(model)
8753
- });
8754
- }
8755
- if (body.trim())
8756
- await addComment(session.path, body, { username: localReviewAuthor(model) });
9492
+ const backend = createLocalReviewBackend({
9493
+ session: session.path,
9494
+ artifactPath: artifact,
9495
+ author: localReviewAuthor(model)
9496
+ });
9497
+ await backend.stage({ comments, body });
8757
9498
  return result3(`Local review staged in tuicr: ${artifact}`, { artifact, count: findings.length, session });
8758
9499
  }
8759
9500
  if (!review.pr)
8760
9501
  return result3(`Review written: ${artifact}. No PR/MR matches this remote target.`, { artifact });
8761
- const hasDraft = comments.length > 0 || body.trim().length > 0;
9502
+ const hasDraft = hasReviewDraft(comments, body);
8762
9503
  if (hasDraft) {
8763
9504
  await createRemoteReviewBackend(review.vcs, review.pr.number).stage({ comments, body });
8764
9505
  }
@@ -8794,12 +9535,12 @@ ${openMessage}`, {
8794
9535
  const session = await resolveTuicrSession(review, Boolean(params.local || params.workingTree));
8795
9536
  if (!session)
8796
9537
  return result3("No matching tuicr session. Open review_new or review_launch_ui first.");
8797
- await addComment(session.path, comment.body, {
8798
- targetFile: comment.file,
8799
- line: comment.line,
8800
- side: comment.side === "LEFT" ? "old" : "new",
8801
- username: localReviewAuthor(model)
9538
+ const backend = createLocalReviewBackend({
9539
+ session: session.path,
9540
+ artifactPath: "",
9541
+ author: localReviewAuthor(model)
8802
9542
  });
9543
+ await backend.stage({ comments: [comment], body: "" });
8803
9544
  return result3(`Comment added to tuicr session ${session.slug}.`, { session, comment });
8804
9545
  }
8805
9546
  if (!review.pr)
@@ -8811,70 +9552,88 @@ ${openMessage}`, {
8811
9552
  defineTool6({
8812
9553
  name: "review_comments",
8813
9554
  label: "review comments",
8814
- description: "Read remote GitHub or GitLab review threads.",
8815
- promptSnippet: "Call review_comments before addressing remote findings",
8816
- promptGuidelines: ["Use review_dump for a local tuicr review."],
9555
+ description: "Pull review threads or local tuicr comments and write a target-named artifact.",
9556
+ promptSnippet: "Call review_comments before addressing findings",
9557
+ promptGuidelines: ["Pass local=true to prepare the local reply overlay."],
8817
9558
  parameters: parameters2(localSchema),
8818
- executionMode: "parallel",
9559
+ executionMode: "sequential",
8819
9560
  async execute(_id, input) {
8820
9561
  const params = localSchema.parse(input);
8821
- if (params.local || params.workingTree)
8822
- return result3("Use review_dump for a local tuicr review.");
8823
9562
  const review = await resolveReviewContext(resolveWorkingDirectory(params), params.target);
8824
- if (!review.pr || !review.forge)
9563
+ let threads;
9564
+ let artifact;
9565
+ if (params.local || params.workingTree) {
9566
+ const session = await resolveTuicrSession(review, true);
9567
+ if (!session)
9568
+ return result3("No matching tuicr session found.");
9569
+ artifact = await localThreadArtifactPath(review.cwd, session.slug);
9570
+ threads = await syncLocalThreadArtifact(artifact, review.pr?.title ?? review.vcs.branch, session.slug, toLocalReviewThreads(await readSession(session.path)));
9571
+ } else if (review.pr && review.forge) {
9572
+ threads = await createRemoteReviewBackend(review.vcs, review.pr.number).listThreads();
9573
+ const target = await reviewTargetId(review);
9574
+ artifact = await newReviewArtifactPath(review.cwd, target);
9575
+ await writeFile7(artifact, renderThreadArtifact(review.pr.title, target, threads, { number: review.pr.number, url: review.pr.url }), "utf8");
9576
+ } else {
8825
9577
  return result3(review.forge ? "No PR/MR matches this remote review target." : unsupportedForgeMessage());
8826
- const threads = await createRemoteReviewBackend(review.vcs, review.pr.number).listThreads();
9578
+ }
8827
9579
  return result3(threads.map((thread) => `${thread.id} ${thread.file ?? "review"}:${thread.line ?? "-"} — ${thread.body}`).join(`
8828
- `) || "No comments.", { pr: review.pr, threads });
8829
- }
8830
- }),
8831
- defineTool6({
8832
- name: "review_dump",
8833
- label: "review dump",
8834
- description: "Save one immutable local tuicr review revision and remove its completed session.",
8835
- promptSnippet: "Call review_dump before applying local review feedback",
8836
- promptGuidelines: ["Each dump advances the local review revision."],
8837
- parameters: parameters2(localSchema),
8838
- executionMode: "sequential",
8839
- async execute(_id, input) {
8840
- const params = localSchema.parse(input);
8841
- const review = await resolveReviewContext(resolveWorkingDirectory(params), params.target);
8842
- const session = await resolveTuicrSession(review, true);
8843
- if (!session)
8844
- return result3("No matching local tuicr session found.");
8845
- const base = review.pr?.baseRef ?? (review.forge ? await review.forge.defaultBranch() : "HEAD");
8846
- const captured = await captureLocalReview({
8847
- cwd: review.cwd,
8848
- branch: review.vcs.branch,
8849
- base,
8850
- diff: await workingTreeDiff(review.cwd),
8851
- session
8852
- });
8853
- return result3(captured.dump.comments.map((thread) => `${thread.id} ${thread.file ?? "review"}:${thread.line ?? "-"} — ${thread.body}`).join(`
8854
- `) || "No comments.", { artifact: captured.path, review: captured.dump, threads: captured.dump.comments });
9580
+ `) || "No comments.", { artifact, threads });
8855
9581
  }
8856
9582
  }),
8857
9583
  defineTool6({
8858
9584
  name: "review_respond",
8859
9585
  label: "review respond",
8860
- description: "Reply directly to a remote GitHub or GitLab review thread.",
8861
- promptSnippet: "Call review_respond after addressing a remote comment",
8862
- promptGuidelines: ["Leave threads open unless the user explicitly requests resolution."],
9586
+ description: "Post local question replies to tuicr and record their publish overlay, or reply to remote threads.",
9587
+ promptSnippet: "Call review_respond after addressing a comment",
9588
+ promptGuidelines: ["Question replies remain unresolved."],
8863
9589
  parameters: parameters2(respondSchema),
8864
9590
  executionMode: "sequential",
8865
9591
  async execute(_id, input, _signal, _onUpdate, ctx) {
8866
9592
  const params = respondSchema.parse(input);
8867
- if (params.local)
8868
- return result3("Local reviews use immutable revision dumps, not thread replies.");
8869
9593
  const review = await resolveReviewContext(resolveWorkingDirectory(params), params.target);
9594
+ const model = modelRoute(ctx);
9595
+ if (params.local) {
9596
+ const tuicrSession = await resolveTuicrSession(review, true);
9597
+ if (!tuicrSession)
9598
+ return result3("No matching tuicr session. Open review_new or review_launch_ui first.");
9599
+ const artifact = await localThreadArtifactPath(review.cwd, tuicrSession.slug);
9600
+ if (!existsSync2(artifact))
9601
+ return result3("No local review artifact. Run review_comments with local=true first.");
9602
+ const threads = await readThreadArtifact(artifact);
9603
+ const known = threads.find((thread) => thread.id === params.threadId);
9604
+ const question = known?.question === true || params.question === true || !known && params.question === undefined;
9605
+ const awaitUserDeletion = !question && params.resolve === true;
9606
+ await addComment(tuicrSession.path, `${localResponseMarker(params.threadId)}
9607
+ ${params.body}`, {
9608
+ targetFile: known?.file,
9609
+ line: known?.line,
9610
+ side: "new",
9611
+ username: localReviewAuthor(model)
9612
+ });
9613
+ await createLocalReviewBackend({
9614
+ session: tuicrSession.path,
9615
+ artifactPath: artifact,
9616
+ author: localReviewAuthor(model)
9617
+ }).reply({
9618
+ threadId: params.threadId,
9619
+ body: params.body,
9620
+ resolve: false,
9621
+ question
9622
+ });
9623
+ return result3(`Local ${question ? "answer" : "response"} posted to tuicr and recorded in ${artifact}${awaitUserDeletion ? "; delete the source comment in tuicr to resolve it" : ""}.`, { artifact, question, awaitUserDeletion, session: tuicrSession });
9624
+ }
8870
9625
  if (!review.pr || !review.forge)
8871
9626
  return result3("No remote PR/MR for this reply.");
8872
- const resolve = params.question ? false : params.resolve ?? false;
8873
- await createRemoteReviewBackend(review.vcs, review.pr.number).reply({
9627
+ const remote = createRemoteReviewBackend(review.vcs, review.pr.number);
9628
+ const remoteThreads = await remote.listThreads();
9629
+ const known = remoteThreads.find((thread) => thread.id === params.threadId);
9630
+ const question = known?.question === true || params.question === true || !known && params.question === undefined;
9631
+ const resolve = reviewResponseResolution(question, params.resolve);
9632
+ await remote.reply({
8874
9633
  threadId: params.threadId,
8875
- body: withRemoteProvenance(params.body, modelRoute(ctx)),
9634
+ body: withRemoteProvenance(params.body, model),
8876
9635
  resolve,
8877
- question: params.question
9636
+ question
8878
9637
  });
8879
9638
  return result3(`Replied to ${params.threadId}${resolve ? " and resolved it" : " and left it open"}.`, {
8880
9639
  pr: review.pr,
@@ -8885,52 +9644,66 @@ ${openMessage}`, {
8885
9644
  defineTool6({
8886
9645
  name: "review_publish",
8887
9646
  label: "review publish",
8888
- description: "Publish pending remote review comments and status.",
9647
+ description: "Publish pending remote draft PR/MR review comments and status, or promote a local tuicr draft before publishing.",
8889
9648
  promptSnippet: "Call review_publish to make remote review work public",
8890
- promptGuidelines: ["Local reviews use revision dumps and are never published remotely."],
9649
+ promptGuidelines: ["Statuses are COMMENT, APPROVE, REQUEST_CHANGES, or CLOSE."],
8891
9650
  parameters: parameters2(publishSchema),
8892
9651
  executionMode: "sequential",
8893
- async execute(_id, input) {
9652
+ async execute(_id, input, _signal, _onUpdate, ctx) {
8894
9653
  const params = publishSchema.parse(input);
8895
- if (params.local)
8896
- return result3("Local reviews use immutable revision dumps and have no publish step.");
8897
9654
  const review = await resolveReviewContext(resolveWorkingDirectory(params), params.target);
8898
9655
  if (!review.pr || !review.forge)
8899
9656
  return result3("No remote PR/MR to publish.");
8900
- return publishResolvedReview(review, params);
9657
+ return publishResolvedReview(review, params, modelRoute(ctx));
8901
9658
  }
8902
9659
  }),
8903
9660
  defineTool6({
8904
9661
  name: "review_complete",
8905
9662
  label: "review complete",
8906
- description: "Approve, reject, or abandon a remote review.",
8907
- promptSnippet: "Call review_complete to finish a remote review without merging it.",
8908
- promptGuidelines: ["Use review_dump to finish a local review revision."],
9663
+ description: "Approve, reject, or abandon a remote review, or archive a local review artifact.",
9664
+ promptSnippet: "Call review_complete to finish a review without merging it.",
9665
+ promptGuidelines: ["A local completion archives the Diffpi artifact and deletes the matching tuicr session."],
8909
9666
  parameters: parameters2(completeSchema),
8910
9667
  executionMode: "sequential",
8911
- async execute(_id, input) {
9668
+ async execute(_id, input, _signal, _onUpdate, ctx) {
8912
9669
  const params = completeSchema.parse(input);
8913
- if (params.local)
8914
- return result3("Use review_dump to finish a local review revision.");
8915
9670
  const review = await resolveReviewContext(resolveWorkingDirectory(params), params.target);
9671
+ if (params.local) {
9672
+ const session = await resolveTuicrSession(review, true);
9673
+ if (!session)
9674
+ return result3("No matching local tuicr session to close.");
9675
+ const artifact = await localThreadArtifactPath(review.cwd, session.slug);
9676
+ if (!existsSync2(artifact))
9677
+ return result3("No local review artifact. Run review_comments with local=true first.");
9678
+ const archived = await uniqueRecordPath(await completedReviewsDir(review.cwd), reviewSlug(session.slug));
9679
+ await rename4(artifact, archived);
9680
+ await unlink2(session.path);
9681
+ return result3(`Archived ${archived} and deleted the tuicr session ${session.slug}.`, {
9682
+ artifact: archived,
9683
+ session
9684
+ });
9685
+ }
8916
9686
  if (!review.pr || !review.forge)
8917
9687
  return result3("No remote PR/MR to complete.");
8918
9688
  if (!params.action)
8919
9689
  return result3("Choose a complete action: approve, reject, or abandon.");
8920
9690
  const status = { approve: "APPROVE", reject: "REQUEST_CHANGES", abandon: "CLOSE" }[params.action];
8921
- return publishResolvedReview(review, { ...params, status });
9691
+ return publishResolvedReview(review, { ...params, status }, modelRoute(ctx));
8922
9692
  }
8923
9693
  }),
8924
9694
  defineTool6({
8925
9695
  name: "review_merge",
8926
9696
  label: "review merge",
8927
- description: "Squash-merge an open, ready GitHub PR after checking its conventional subject.",
8928
- promptSnippet: "Call review_merge after confirming the PR is open, ready, and CI is settled; approval is optional",
8929
- promptGuidelines: ["This is intentionally GitHub-only until GitLab merge support is added."],
8930
- parameters: parameters2(contextSchema.extend({ subject: z9.string().optional() })),
9697
+ description: "Squash-merge an open, ready GitHub PR through gh after checking its conventional subject.",
9698
+ promptSnippet: "Call review_merge directly; it uses gh to confirm the PR is open, ready, and CI is settled before merging",
9699
+ promptGuidelines: [
9700
+ "Do not query GitHub through MCP or duplicate readiness checks before calling review_merge.",
9701
+ "This is intentionally GitHub-only until GitLab merge support is added."
9702
+ ],
9703
+ parameters: parameters2(contextSchema.extend({ subject: z11.string().optional() })),
8931
9704
  executionMode: "sequential",
8932
9705
  async execute(_id, input) {
8933
- const params = contextSchema.extend({ subject: z9.string().optional() }).parse(input);
9706
+ const params = contextSchema.extend({ subject: z11.string().optional() }).parse(input);
8934
9707
  const review = await resolveReviewContext(resolveWorkingDirectory(params), params.target);
8935
9708
  if (review.vcs.provider !== "github" || !review.forge)
8936
9709
  return result3("review_merge currently supports GitHub only.");
@@ -8963,8 +9736,32 @@ ${openMessage}`, {
8963
9736
  })
8964
9737
  ];
8965
9738
  }
9739
+ async function syncLocalThreadArtifact(path, title, sessionSlug, threads) {
9740
+ let previous = [];
9741
+ try {
9742
+ previous = parseThreadArtifact(await readFile12(path, "utf8"));
9743
+ } catch (error) {
9744
+ if (error.code !== "ENOENT")
9745
+ throw error;
9746
+ }
9747
+ const previousById = new Map(previous.map((thread) => [thread.id, thread]));
9748
+ const currentIds = new Set(threads.map((thread) => thread.id));
9749
+ const current = threads.map((thread) => {
9750
+ const existing = previousById.get(thread.id);
9751
+ return {
9752
+ ...thread,
9753
+ resolved: false,
9754
+ addressed: existing?.addressed ?? Boolean(existing?.reply),
9755
+ reply: existing?.reply
9756
+ };
9757
+ });
9758
+ const removed = previous.filter((thread) => !currentIds.has(thread.id)).map((thread) => ({ ...thread, resolved: true }));
9759
+ const merged = [...current, ...removed];
9760
+ await writeFile7(path, renderThreadArtifact(title, sessionSlug, merged), "utf8");
9761
+ return merged;
9762
+ }
8966
9763
  function parameters2(schema) {
8967
- return z9.toJSONSchema(schema, { io: "input" });
9764
+ return z11.toJSONSchema(schema, { io: "input" });
8968
9765
  }
8969
9766
  function resolveWorkingDirectory(params) {
8970
9767
  return params.cwd ?? process.cwd();
@@ -8975,22 +9772,216 @@ function result3(text, details = {}) {
8975
9772
  function unsupportedForgeMessage() {
8976
9773
  return "No supported GitHub or GitLab remote was detected. Use local=true for an offline tuicr review.";
8977
9774
  }
9775
+ async function collectReviewStatus(review) {
9776
+ const [porcelain, branch, localSession, remoteSession] = await Promise.all([
9777
+ runChecked("git", ["-C", review.cwd, "status", "--porcelain"]),
9778
+ runChecked("git", ["-C", review.cwd, "branch", "--show-current"]),
9779
+ resolveTuicrSession(review, true).catch(() => {
9780
+ return;
9781
+ }),
9782
+ resolveTuicrSession(review, false).catch(() => {
9783
+ return;
9784
+ })
9785
+ ]);
9786
+ const entries = porcelain.stdout.split("\\n").filter(Boolean);
9787
+ const staged = entries.filter((line) => !line.startsWith("??") && line[0] !== " ").length;
9788
+ const unstaged = entries.filter((line) => !line.startsWith("??") && line[1] !== " ").length;
9789
+ const untracked = entries.filter((line) => line.startsWith("??")).length;
9790
+ const remote = review.pr ? `yes (#${review.pr.number})` : "no";
9791
+ const url = review.pr?.url ?? "none";
9792
+ const text = [
9793
+ `Branch: ${branch.stdout.trim() || review.vcs.branch}`,
9794
+ `Worktree: ${entries.length ? "dirty" : "clean"} (staged=${staged}, unstaged=${unstaged}, untracked=${untracked})`,
9795
+ `Local working-tree tuicr review: ${localSession ? `yes (${localSession.slug}, ${localSession.commentCount} comments)` : "no"}`,
9796
+ `Remote PR/MR: ${remote}`,
9797
+ `Remote URL: ${url}`,
9798
+ `Remote tuicr session: ${remoteSession ? `yes (${remoteSession.slug}, ${remoteSession.commentCount} comments)` : "no"}`
9799
+ ].join("\\n");
9800
+ return {
9801
+ text,
9802
+ details: {
9803
+ branch: branch.stdout.trim(),
9804
+ staged,
9805
+ unstaged,
9806
+ untracked,
9807
+ localSession,
9808
+ remoteSession,
9809
+ pr: review.pr,
9810
+ url
9811
+ }
9812
+ };
9813
+ }
8978
9814
  function modelRoute(ctx) {
8979
9815
  if (!ctx.model)
8980
9816
  throw new Error("Cannot record review provenance because Pi did not provide an active model route.");
8981
9817
  return `${ctx.model.provider}/${ctx.model.id}`;
8982
9818
  }
8983
- async function publishResolvedReview(review, params) {
9819
+ async function publishResolvedReview(review, params, model) {
8984
9820
  const status = params.status ?? "COMMENT";
8985
9821
  const event = status === "CLOSE" ? "COMMENT" : status;
8986
9822
  assertReviewEventSupported(review.vcs.provider, event);
9823
+ const remote = createRemoteReviewBackend(review.vcs, review.pr.number);
9824
+ const promotion = params.local ? await promoteLocalReview(review, remote, model) : undefined;
8987
9825
  if (status !== "CLOSE" && review.pr.isDraft)
8988
9826
  await review.forge.markReady(review.pr.number);
8989
- await createRemoteReviewBackend(review.vcs, review.pr.number).publish(event);
9827
+ await remote.publish(event);
9828
+ if (promotion) {
9829
+ promotion.publication.state.bodies = [
9830
+ ...new Set([...promotion.publication.state.bodies, ...promotion.bodyFingerprints])
9831
+ ];
9832
+ promotion.publication.state.comments = [
9833
+ ...new Set([...promotion.publication.state.comments, ...promotion.commentFingerprints])
9834
+ ];
9835
+ const published = new Set(promotion.commentFingerprints);
9836
+ promotion.publication.state.stagedComments = promotion.publication.state.stagedComments.filter((fingerprint) => !published.has(fingerprint));
9837
+ await saveReviewPublicationState(promotion.publication.path, promotion.publication.state);
9838
+ }
8990
9839
  if (status === "CLOSE")
8991
9840
  await review.forge.closePr(review.pr.number);
8992
9841
  const finalPr = await review.forge.viewPr(String(review.pr.number));
8993
- return result3(`Published #${review.pr.number} (${status}).`, { pr: finalPr ?? review.pr, status });
9842
+ const promotedBodies = promotion?.promotedBodies ?? 0;
9843
+ const promotedComments = promotion?.promotedComments ?? 0;
9844
+ const promotedReplies = promotion?.promotedReplies ?? 0;
9845
+ return result3(`Published #${review.pr.number} (${status}); promoted ${promotedBodies} review bodies, ${promotedComments} comments, and ${promotedReplies} replies.`, { pr: finalPr ?? review.pr, status, promotedBodies, promotedComments, promotedReplies });
9846
+ }
9847
+ async function promoteLocalReview(review, remote, model) {
9848
+ const publication = await loadReviewPublicationState(review.cwd, review.vcs, review.pr.number);
9849
+ const session = await resolvePublishSession(review.cwd, {
9850
+ branch: review.vcs.branch,
9851
+ owner: review.vcs.provider === "none" ? undefined : review.vcs.owner,
9852
+ repo: review.vcs.provider === "none" ? undefined : review.vcs.repo,
9853
+ number: review.pr?.number
9854
+ });
9855
+ if (!session)
9856
+ throw new Error("No matching tuicr session to publish.");
9857
+ const sessionIsWorkingTree = session.kind === "local";
9858
+ const local = createLocalReviewBackend({
9859
+ session: session.path,
9860
+ artifactPath: "",
9861
+ author: localReviewAuthor(model)
9862
+ });
9863
+ const draft = await local.readDraft();
9864
+ const remoteDraft = await remote.readDraft();
9865
+ const knownRootComments = new Set([
9866
+ ...publication.state.comments,
9867
+ ...publication.state.stagedComments,
9868
+ ...remoteDraft.comments.map(reviewCommentFingerprint)
9869
+ ]);
9870
+ const { checkpointed, candidates } = partitionReviewComments(draft.comments, knownRootComments, model);
9871
+ const remoteThreads = await remote.listThreads();
9872
+ const threadReplies = sessionIsWorkingTree ? [] : candidates.flatMap(({ source: comment }) => {
9873
+ const thread = resolveReviewThread(comment, remoteThreads);
9874
+ return thread ? [{ comment, thread }] : [];
9875
+ });
9876
+ const unmatchedActions = sessionIsWorkingTree ? [] : candidates.map(({ source }) => source).filter((comment) => parseReviewThreadAction(comment.body).action && !threadReplies.some((reply) => reply.comment === comment));
9877
+ if (unmatchedActions.length > 0) {
9878
+ const locations = unmatchedActions.map(({ file, line }) => `${file}:${line ?? "?"}`).join(", ");
9879
+ throw new Error(`Cannot apply review thread action: no matching remote thread at ${locations}.`);
9880
+ }
9881
+ const comments = candidates.filter(({ source }) => !threadReplies.some((reply) => reply.comment === source)).map(({ published }) => published);
9882
+ const body = draft.body.trim();
9883
+ const bodyFingerprints = body ? [reviewBodyFingerprint(body)] : [];
9884
+ const commentFingerprints = [
9885
+ ...checkpointed.map(({ fingerprint }) => fingerprint),
9886
+ ...comments.map(reviewCommentFingerprint)
9887
+ ];
9888
+ const knownBodies = new Set(publication.state.bodies);
9889
+ if (remoteDraft.body.trim())
9890
+ knownBodies.add(reviewBodyFingerprint(remoteDraft.body));
9891
+ const unpublishedBody = body && !knownBodies.has(reviewBodyFingerprint(body)) ? body : "";
9892
+ const unpublished = unpublishedReviewComments(comments, knownRootComments);
9893
+ if (unpublishedBody)
9894
+ await remote.stage({ comments: [], body: unpublishedBody });
9895
+ let promotedComments = 0;
9896
+ for (const comment of unpublished) {
9897
+ await remote.stage({ comments: [comment], body: "" });
9898
+ publication.state.stagedComments.push(reviewCommentFingerprint(comment));
9899
+ await saveReviewPublicationState(publication.path, publication.state);
9900
+ promotedComments += 1;
9901
+ }
9902
+ const promotedReplies = await promoteLocalReplies(review, remote, publication, model, sessionIsWorkingTree) + await promoteLocationReplies(remote, publication, threadReplies, model);
9903
+ return {
9904
+ publication,
9905
+ bodyFingerprints,
9906
+ commentFingerprints,
9907
+ promotedBodies: unpublishedBody ? 1 : 0,
9908
+ promotedComments,
9909
+ promotedReplies
9910
+ };
9911
+ }
9912
+ async function promoteLocationReplies(remote, publication, replies, model) {
9913
+ let count = 0;
9914
+ for (const { comment, thread } of replies) {
9915
+ const parsed = parseReviewThreadAction(comment.body);
9916
+ const body = parsed.body.trim();
9917
+ const action = parsed.action;
9918
+ const fingerprint = reviewReplyFingerprint(thread.id, `${action ?? "reply"}\x00${body}`);
9919
+ if (publication.state.replies.includes(fingerprint))
9920
+ continue;
9921
+ if (action === "delete") {
9922
+ if (!remote.deleteThread)
9923
+ throw new Error(`The review backend cannot delete thread ${thread.id}.`);
9924
+ await remote.deleteThread(thread.id);
9925
+ publication.state.replies.push(fingerprint);
9926
+ await saveReviewPublicationState(publication.path, publication.state);
9927
+ count += 1;
9928
+ continue;
9929
+ }
9930
+ const remoteBody = withCommentProvenance({ ...comment, body }, model);
9931
+ if (body && !thread.replies?.some((reply) => reply === body || reply === remoteBody)) {
9932
+ await remote.reply({
9933
+ threadId: thread.id,
9934
+ body: remoteBody,
9935
+ resolve: false
9936
+ });
9937
+ }
9938
+ if (action && remote.setResolved)
9939
+ await remote.setResolved(thread.id, action === "resolve");
9940
+ publication.state.replies.push(fingerprint);
9941
+ await saveReviewPublicationState(publication.path, publication.state);
9942
+ count += 1;
9943
+ }
9944
+ return count;
9945
+ }
9946
+ async function promoteLocalReplies(review, remote, publication, model, workingTree) {
9947
+ const target = workingTree ? "uncommitted" : await reviewTargetId(review);
9948
+ const artifact = workingTree ? await latestThreadArtifact(review.cwd, review, target) : publication.state.overlayPath ?? await latestThreadArtifact(review.cwd, review, target);
9949
+ if (!artifact)
9950
+ return 0;
9951
+ if (!workingTree)
9952
+ publication.state.overlayPath = artifact;
9953
+ let count = 0;
9954
+ for (const thread of await readThreadArtifact(artifact)) {
9955
+ if (!thread.reply)
9956
+ continue;
9957
+ const body = withRemoteProvenance(thread.reply, model);
9958
+ const fingerprint = reviewReplyFingerprint(thread.id, body);
9959
+ if (publication.state.replies.includes(fingerprint))
9960
+ continue;
9961
+ if (workingTree) {
9962
+ const draft = workingTreeReplyDraft(thread, body);
9963
+ const comment = draft.comments[0];
9964
+ if (comment) {
9965
+ const commentFingerprint = reviewCommentFingerprint(comment);
9966
+ if (!publication.state.stagedComments.includes(commentFingerprint)) {
9967
+ await remote.stage(draft);
9968
+ publication.state.stagedComments.push(commentFingerprint);
9969
+ }
9970
+ } else {
9971
+ const bodyFingerprint = reviewBodyFingerprint(draft.body);
9972
+ if (!publication.state.bodies.includes(bodyFingerprint)) {
9973
+ await remote.stage(draft);
9974
+ publication.state.bodies.push(bodyFingerprint);
9975
+ }
9976
+ }
9977
+ } else {
9978
+ await remote.reply({ threadId: thread.id, body, resolve: false, question: thread.question });
9979
+ }
9980
+ publication.state.replies.push(fingerprint);
9981
+ await saveReviewPublicationState(publication.path, publication.state);
9982
+ count += 1;
9983
+ }
9984
+ return count;
8994
9985
  }
8995
9986
  async function resolveReviewContext(cwd, target) {
8996
9987
  const vcs = await detectVcs(cwd);
@@ -9031,6 +10022,10 @@ async function assertRemoteBranchReady(cwd) {
9031
10022
  if (head.stdout.trim() !== pushed.stdout.trim())
9032
10023
  throw new Error("Push the current branch before opening a remote review.");
9033
10024
  }
10025
+ function withCommentProvenance(comment, fallbackModel) {
10026
+ const route = comment.author?.match(/^Agent:\s*(.+)$/)?.[1];
10027
+ return route ? withRemoteProvenance(comment.body, route || fallbackModel) : comment.body;
10028
+ }
9034
10029
  async function reviewTargetId(review) {
9035
10030
  if (!review.pr)
9036
10031
  return "uncommitted";
@@ -9047,41 +10042,103 @@ async function headSha(cwd) {
9047
10042
  }
9048
10043
  async function newReviewArtifactPath(cwd, target) {
9049
10044
  const dir = await reviewsDir(cwd);
9050
- await mkdir8(dir, { recursive: true });
10045
+ await mkdir7(dir, { recursive: true });
9051
10046
  return uniqueRecordPath(dir, reviewRecordName(target));
9052
10047
  }
10048
+ async function localThreadArtifactPath(cwd, sessionSlug) {
10049
+ const dir = await reviewsDir(cwd);
10050
+ return join17(dir, `${reviewSlug(sessionSlug) || "local-review"}.md`);
10051
+ }
10052
+ async function readThreadArtifact(path) {
10053
+ try {
10054
+ return parseThreadArtifact(await readFile12(path, "utf8"));
10055
+ } catch (error) {
10056
+ if (error.code === "ENOENT") {
10057
+ throw new Error(`Expected local reply overlay is missing: ${path}`);
10058
+ }
10059
+ throw error;
10060
+ }
10061
+ }
10062
+ async function latestThreadArtifact(cwd, review, target) {
10063
+ try {
10064
+ return await findLatestThreadArtifact(cwd, review, target);
10065
+ } catch (error) {
10066
+ throw new Error(`Cannot locate the latest review thread artifact for ${target}.`, { cause: error });
10067
+ }
10068
+ }
10069
+ async function findLatestThreadArtifact(cwd, review, target) {
10070
+ const dir = await reviewsDir(cwd);
10071
+ const suffix = reviewSlug(target) || "uncommitted";
10072
+ const names = await listReviewArtifactNames(dir);
10073
+ const candidates = await Promise.all(names.flatMap((name) => {
10074
+ if (!name.endsWith(".md"))
10075
+ return [];
10076
+ return [
10077
+ (async () => {
10078
+ const path = join17(dir, name);
10079
+ const info = await stat(path);
10080
+ return { path, name, content: await readFile12(path, "utf8"), modified: info.mtimeMs };
10081
+ })()
10082
+ ];
10083
+ }));
10084
+ return candidates.filter(({ name, content }) => {
10085
+ if (!content.startsWith("<!-- diffpi-threads:"))
10086
+ return false;
10087
+ if (review.pr && target !== "local" && target !== "uncommitted")
10088
+ return content.includes(`- PR/MR: #${review.pr.number}`);
10089
+ return artifactNameMatches(name, suffix);
10090
+ }).sort((a, b) => b.modified - a.modified)[0]?.path;
10091
+ }
10092
+ async function listReviewArtifactNames(dir) {
10093
+ try {
10094
+ return await readdir3(dir);
10095
+ } catch (error) {
10096
+ throw new Error(`Cannot read review artifacts in ${dir}.`, { cause: error });
10097
+ }
10098
+ }
9053
10099
  function deriveTitle(branch) {
9054
10100
  return branch.replace(/^(feature|feat|fix|bug|chore)\//, "").replace(/^eng-\d+-/i, "").replace(/[-_]+/g, " ").replace(/^\w/, (char) => char.toUpperCase());
9055
10101
  }
9056
10102
  function uniqueRecordPath(dir, base) {
9057
- let path = join16(dir, `${base}.md`);
10103
+ let path = join17(dir, `${base}.md`);
9058
10104
  let count = 2;
9059
10105
  while (existsSync2(path))
9060
- path = join16(dir, `${base}-${count++}.md`);
10106
+ path = join17(dir, `${base}-${count++}.md`);
9061
10107
  return path;
9062
10108
  }
10109
+ function artifactNameMatches(name, suffix) {
10110
+ if (!name.endsWith(".md"))
10111
+ return false;
10112
+ const stem = name.slice(0, -3);
10113
+ const marker = `-${suffix}`;
10114
+ const markerIndex = stem.lastIndexOf(marker);
10115
+ if (markerIndex < 0)
10116
+ return false;
10117
+ const tail = stem.slice(markerIndex + marker.length);
10118
+ return tail === "" || /^-\d+$/.test(tail);
10119
+ }
9063
10120
 
9064
10121
  // src/tools/setup.ts
9065
10122
  import { defineTool as defineTool7 } from "@earendil-works/pi-coding-agent";
9066
- import { z as z11 } from "zod";
10123
+ import { z as z13 } from "zod";
9067
10124
 
9068
10125
  // src/setup.ts
9069
10126
  import { parseFrontmatter as parseFrontmatter2 } from "@earendil-works/pi-coding-agent";
9070
- import { readdir as readdir4, readFile as readFile12 } from "node:fs/promises";
10127
+ import { readdir as readdir5, readFile as readFile15 } from "node:fs/promises";
9071
10128
  import { homedir as homedir8 } from "node:os";
9072
- import { basename as basename6, join as join20 } from "node:path";
10129
+ import { basename as basename6, join as join21 } from "node:path";
9073
10130
 
9074
10131
  // src/config.ts
9075
10132
  import { parseFrontmatter } from "@earendil-works/pi-coding-agent";
9076
- import { z as z10 } from "zod";
10133
+ import { z as z12 } from "zod";
9077
10134
  import { homedir as homedir5 } from "node:os";
9078
- import { join as join17 } from "node:path";
10135
+ import { join as join18 } from "node:path";
9079
10136
 
9080
10137
  // src/fsx.ts
9081
- import { readdir as readdir3, readFile as readFile10 } from "node:fs/promises";
10138
+ import { readdir as readdir4, readFile as readFile13 } from "node:fs/promises";
9082
10139
  async function readTextIfExists(path) {
9083
10140
  try {
9084
- return await readFile10(path, "utf8");
10141
+ return await readFile13(path, "utf8");
9085
10142
  } catch (error) {
9086
10143
  if (isMissingPath(error))
9087
10144
  return;
@@ -9094,17 +10151,17 @@ function isMissingPath(error) {
9094
10151
 
9095
10152
  // src/config.ts
9096
10153
  var modelReferenceSchema = zx.text;
9097
- var agentConfigSchema = z10.object({
9098
- models: z10.array(modelReferenceSchema).optional()
10154
+ var agentConfigSchema = z12.object({
10155
+ models: z12.array(modelReferenceSchema).optional()
9099
10156
  }).strict();
9100
- var diffpiConfigSchema = z10.object({
9101
- agents: z10.record(z10.string(), agentConfigSchema).optional()
10157
+ var diffpiConfigSchema = z12.object({
10158
+ agents: z12.record(z12.string(), agentConfigSchema).optional()
9102
10159
  }).strict();
9103
10160
  function diffpiConfigPaths(homeDir = homedir5()) {
9104
- const directory = join17(homeDir, ".difflab", "diffpi");
10161
+ const directory = join18(homeDir, ".difflab", "diffpi");
9105
10162
  return {
9106
- yaml: join17(directory, "config.yaml"),
9107
- json: join17(directory, "config.json")
10163
+ yaml: join18(directory, "config.yaml"),
10164
+ json: join18(directory, "config.json")
9108
10165
  };
9109
10166
  }
9110
10167
  async function loadDiffpiConfig(options = {}) {
@@ -9160,12 +10217,12 @@ function normalizeModelReference(value) {
9160
10217
  }
9161
10218
 
9162
10219
  // src/mcp.ts
9163
- import { mkdir as mkdir9, readFile as readFile11, writeFile as writeFile7 } from "node:fs/promises";
10220
+ import { mkdir as mkdir8, readFile as readFile14, writeFile as writeFile8 } from "node:fs/promises";
9164
10221
  import { homedir as homedir6 } from "node:os";
9165
- import { dirname as dirname8, join as join18 } from "node:path";
10222
+ import { dirname as dirname8, join as join19 } from "node:path";
9166
10223
  var mcp = {
9167
10224
  globalConfigPath(homeDir = homedir6()) {
9168
- return join18(homeDir, ".config", "mcp", "mcp.json");
10225
+ return join19(homeDir, ".config", "mcp", "mcp.json");
9169
10226
  },
9170
10227
  async serversEnsure(servers, options = {}) {
9171
10228
  const path = options.path ?? mcp.globalConfigPath();
@@ -9178,8 +10235,8 @@ var mcp = {
9178
10235
  const next = { ...current, mcpServers: nextServers };
9179
10236
  const changed = JSON.stringify(current) !== JSON.stringify(next);
9180
10237
  if (changed && !options.dryRun) {
9181
- await mkdir9(dirname8(path), { recursive: true });
9182
- await writeFile7(path, `${JSON.stringify(next, null, 2)}
10238
+ await mkdir8(dirname8(path), { recursive: true });
10239
+ await writeFile8(path, `${JSON.stringify(next, null, 2)}
9183
10240
  `, "utf8");
9184
10241
  }
9185
10242
  return { path, changed, existed: currentText !== undefined, planned: changed && options.dryRun === true };
@@ -9208,7 +10265,7 @@ function getParsedConfig(content, path) {
9208
10265
  }
9209
10266
  async function getOptionalFile2(path) {
9210
10267
  try {
9211
- return await readFile11(path, "utf8");
10268
+ return await readFile14(path, "utf8");
9212
10269
  } catch (error) {
9213
10270
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
9214
10271
  return;
@@ -9220,9 +10277,9 @@ function isRecord(value) {
9220
10277
  }
9221
10278
 
9222
10279
  // src/pi.ts
9223
- import { mkdir as mkdir10, writeFile as writeFile8 } from "node:fs/promises";
10280
+ import { mkdir as mkdir9, writeFile as writeFile9 } from "node:fs/promises";
9224
10281
  import { homedir as homedir7 } from "node:os";
9225
- import { dirname as dirname9, join as join19 } from "node:path";
10282
+ import { dirname as dirname9, join as join20 } from "node:path";
9226
10283
  var pi = {
9227
10284
  executableCheck: findPiExecutable,
9228
10285
  packageList: listPiPackages,
@@ -9235,19 +10292,19 @@ var pi = {
9235
10292
  configEnsure: ensurePiConfig
9236
10293
  };
9237
10294
  async function ensurePiAgent(filename, content, agentDir = resolvePiAgentDir(), dryRun = false) {
9238
- const path = join19(agentDir, "agents", filename);
10295
+ const path = join20(agentDir, "agents", filename);
9239
10296
  const currentText = await readTextIfExists(path);
9240
10297
  const changed = currentText !== content;
9241
10298
  if (changed && !dryRun) {
9242
- await mkdir10(dirname9(path), { recursive: true });
9243
- await writeFile8(path, content, "utf8");
10299
+ await mkdir9(dirname9(path), { recursive: true });
10300
+ await writeFile9(path, content, "utf8");
9244
10301
  }
9245
10302
  return { path, changed, existed: currentText !== undefined, planned: changed && dryRun };
9246
10303
  }
9247
- async function checkGlobalPiSkill(name, agentDir = resolvePiAgentDir(), sharedSkillsDir = join19(homedir7(), ".agents", "skills")) {
9248
- const roots = [join19(agentDir, "skills"), sharedSkillsDir];
10304
+ async function checkGlobalPiSkill(name, agentDir = resolvePiAgentDir(), sharedSkillsDir = join20(homedir7(), ".agents", "skills")) {
10305
+ const roots = [join20(agentDir, "skills"), sharedSkillsDir];
9249
10306
  for (const root of roots) {
9250
- if (await readTextIfExists(join19(root, name, "SKILL.md")) !== undefined)
10307
+ if (await readTextIfExists(join20(root, name, "SKILL.md")) !== undefined)
9251
10308
  return true;
9252
10309
  }
9253
10310
  return false;
@@ -9276,8 +10333,8 @@ async function ensurePiConfig(path, update, dryRun = false) {
9276
10333
  const next = update(current);
9277
10334
  const changed = JSON.stringify(current) !== JSON.stringify(next);
9278
10335
  if (changed && !dryRun) {
9279
- await mkdir10(dirname9(path), { recursive: true });
9280
- await writeFile8(path, `${JSON.stringify(next, null, 2)}
10336
+ await mkdir9(dirname9(path), { recursive: true });
10337
+ await writeFile9(path, `${JSON.stringify(next, null, 2)}
9281
10338
  `, "utf8");
9282
10339
  }
9283
10340
  return { path, changed, existed: currentText !== undefined, planned: changed && dryRun };
@@ -9297,7 +10354,7 @@ async function installPiPackage(executable, source) {
9297
10354
  await runChecked(executable, ["install", source]);
9298
10355
  }
9299
10356
  function resolvePiAgentDir(homeDir = homedir7()) {
9300
- return process.env.PI_CODING_AGENT_DIR ?? (process.env.XDG_CONFIG_HOME ? join19(process.env.XDG_CONFIG_HOME, "pi") : join19(homeDir, ".pi", "agent"));
10357
+ return process.env.PI_CODING_AGENT_DIR ?? (process.env.XDG_CONFIG_HOME ? join20(process.env.XDG_CONFIG_HOME, "pi") : join20(homeDir, ".pi", "agent"));
9301
10358
  }
9302
10359
  function parseJsonObject(content, path) {
9303
10360
  if (!content?.trim())
@@ -9349,7 +10406,7 @@ var FORGE_DEPENDENCIES = {
9349
10406
  };
9350
10407
  async function ensureMise(options = {}) {
9351
10408
  const homeDir = options.homeDir ?? homedir8();
9352
- const current = await mise.executableCheck() ?? await mise.executableCheck(join20(homeDir, ".local", "bin", "mise"));
10409
+ const current = await mise.executableCheck() ?? await mise.executableCheck(join21(homeDir, ".local", "bin", "mise"));
9353
10410
  if (current)
9354
10411
  return { executable: current, action: createSetupAction("mise", "ready", current) };
9355
10412
  reportProgress(options, "Installing mise");
@@ -9398,9 +10455,9 @@ async function ensureMiseDeps(miseExecutable, options = {}) {
9398
10455
  async function ensurePiPlugins(options = {}) {
9399
10456
  const actions = await ensurePiPackages(PI_PACKAGES, options);
9400
10457
  const agentDir = options.agentDir ?? pi.agentDir(options.homeDir);
9401
- const webSearch = await pi.configEnsure(join20(agentDir, "web-search.json"), (config) => ({ ...config, workflow: "auto-summary" }), options.dryRun);
10458
+ const webSearch = await pi.configEnsure(join21(agentDir, "web-search.json"), (config) => ({ ...config, workflow: "auto-summary" }), options.dryRun);
9402
10459
  actions.push(getConfigSetupAction("web search settings", webSearch));
9403
- const lsp = await pi.configEnsure(join20(agentDir, "pi-lsp.json"), (config) => ({
10460
+ const lsp = await pi.configEnsure(join21(agentDir, "pi-lsp.json"), (config) => ({
9404
10461
  ...config,
9405
10462
  progressive: { ...getRecord(config.progressive), enabled: true, inject: "none" }
9406
10463
  }), options.dryRun);
@@ -9411,11 +10468,11 @@ async function ensurePiAgents(options = {}) {
9411
10468
  const agentDir = options.agentDir ?? pi.agentDir(options.homeDir);
9412
10469
  const bundledAgentsDir = options.bundledAgentsDir ?? BUNDLED_AGENTS_DIR;
9413
10470
  const userConfig = await loadDiffpiConfig({ homeDir: options.homeDir });
9414
- const entries = (await readdir4(bundledAgentsDir, { withFileTypes: true })).filter((entry) => entry.isFile() && entry.name.startsWith("diffpi-") && entry.name.endsWith(".md")).sort((left, right) => left.name.localeCompare(right.name));
10471
+ const entries = (await readdir5(bundledAgentsDir, { withFileTypes: true })).filter((entry) => entry.isFile() && entry.name.startsWith("diffpi-") && entry.name.endsWith(".md")).sort((left, right) => left.name.localeCompare(right.name));
9415
10472
  const actions = [];
9416
10473
  for (const entry of entries) {
9417
10474
  const id = basename6(entry.name, ".md").replace(/^diffpi-/, "");
9418
- const source = await readFile12(join20(bundledAgentsDir, entry.name), "utf8");
10475
+ const source = await readFile15(join21(bundledAgentsDir, entry.name), "utf8");
9419
10476
  const content = materializeAgentModels(source, id, userConfig.config, options.availableModels);
9420
10477
  const result = await pi.agentEnsure(entry.name, content, agentDir, options.dryRun);
9421
10478
  actions.push(getConfigSetupAction(`pi agent ${id}`, result));
@@ -9424,7 +10481,7 @@ async function ensurePiAgents(options = {}) {
9424
10481
  }
9425
10482
  async function ensurePiSkills(miseExecutable, options = {}) {
9426
10483
  const agentDir = options.agentDir ?? pi.agentDir(options.homeDir);
9427
- const sharedSkillsDir = join20(options.homeDir ?? homedir8(), ".agents", "skills");
10484
+ const sharedSkillsDir = join21(options.homeDir ?? homedir8(), ".agents", "skills");
9428
10485
  const actions = [];
9429
10486
  for (const source of PI_SKILL_SOURCES) {
9430
10487
  const missing = [];
@@ -9620,7 +10677,7 @@ function reportProgress(options, message) {
9620
10677
  options.onProgress?.(message);
9621
10678
  }
9622
10679
  async function packageVersion2() {
9623
- const source = await readFile12(join20(resolveBundledAgentsDir(), "..", "package.json"), "utf8");
10680
+ const source = await readFile15(join21(resolveBundledAgentsDir(), "..", "package.json"), "utf8");
9624
10681
  let value;
9625
10682
  try {
9626
10683
  value = JSON.parse(source);
@@ -9636,13 +10693,13 @@ function getRecord(value) {
9636
10693
  }
9637
10694
 
9638
10695
  // src/tools/setup.ts
9639
- var setupParametersSchema = z11.object({
9640
- issueTracker: z11.enum(["none", "linear", "jira"]).default("none").describe("Issue tracker MCP server to configure. Use none unless the user explicitly selects Linear or Jira."),
9641
- forges: z11.array(z11.enum(["github", "gitlab"])).default([]).describe("Hosted VCS MCP servers to configure. Installs matching CLIs and registers each MCP server."),
9642
- forge: z11.enum(["none", "github", "gitlab"]).optional().describe("Deprecated single-host alias. Prefer forges for one or more VCS MCP servers."),
9643
- bindZedKey: z11.boolean().default(false).describe("Opt in to a Zed keybinding for the tuicr review task.")
10696
+ var setupParametersSchema = z13.object({
10697
+ issueTracker: z13.enum(["none", "linear", "jira"]).default("none").describe("Issue tracker MCP server to configure. Use none unless the user explicitly selects Linear or Jira."),
10698
+ forges: z13.array(z13.enum(["github", "gitlab"])).default([]).describe("Hosted VCS MCP servers to configure. Installs matching CLIs and registers each MCP server."),
10699
+ forge: z13.enum(["none", "github", "gitlab"]).optional().describe("Deprecated single-host alias. Prefer forges for one or more VCS MCP servers."),
10700
+ bindZedKey: z13.boolean().default(false).describe("Opt in to a Zed keybinding for the tuicr review task.")
9644
10701
  });
9645
- var setupParameters = z11.toJSONSchema(setupParametersSchema, { io: "input" });
10702
+ var setupParameters = z13.toJSONSchema(setupParametersSchema, { io: "input" });
9646
10703
  var diffpiSetupTool = defineTool7({
9647
10704
  name: "diffpi_setup",
9648
10705
  label: "diffpi setup",
@@ -9715,11 +10772,11 @@ ${lines.join(`
9715
10772
 
9716
10773
  // src/tools/templates.ts
9717
10774
  import { defineTool as defineTool8 } from "@earendil-works/pi-coding-agent";
9718
- import { z as z12 } from "zod";
9719
- var templateSchema = z12.object({
9720
- name: z12.string().min(1),
9721
- variables: z12.record(z12.string(), z12.string()).optional(),
9722
- homeDir: z12.string().optional()
10775
+ import { z as z14 } from "zod";
10776
+ var templateSchema = z14.object({
10777
+ name: z14.string().min(1),
10778
+ variables: z14.record(z14.string(), z14.string()).optional(),
10779
+ homeDir: z14.string().optional()
9723
10780
  });
9724
10781
  var diffpiTemplateTool = defineTool8({
9725
10782
  name: "diffpi_template",
@@ -9727,7 +10784,7 @@ var diffpiTemplateTool = defineTool8({
9727
10784
  description: "Load a bundled Diffpi template or a user override and render named variables.",
9728
10785
  promptSnippet: "Use diffpi_template for package workflow templates",
9729
10786
  promptGuidelines: ["User overrides live under ~/.difflab/diffpi/templates."],
9730
- parameters: z12.toJSONSchema(templateSchema, { io: "input" }),
10787
+ parameters: z14.toJSONSchema(templateSchema, { io: "input" }),
9731
10788
  executionMode: "parallel",
9732
10789
  async execute(_id, input) {
9733
10790
  const params = templateSchema.parse(input);