diacode 0.2.2 → 0.3.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,7 +5,7 @@ var __export = (target, all) => {
5
5
  __defProp(target, name2, { get: all[name2], enumerable: true });
6
6
  };
7
7
 
8
- // packages/server/bin/dcursed.js
8
+ // packages/server/bin/diacode.js
9
9
  import { existsSync as existsSync2, readFileSync as readFileSync3, statSync } from "node:fs";
10
10
  import { resolve as resolve6, relative as relative4 } from "node:path";
11
11
 
@@ -126,17 +126,23 @@ var EDGE_KINDS = (
126
126
  ["needs", "after", "approve", "ask", "input"]
127
127
  );
128
128
  var CHECKPOINTS = /* @__PURE__ */ new Set(["approve", "ask", "input"]);
129
- var SCHEMA = "dcursed.plan/1";
130
- var OLDER = ["dcursed.plan/0"];
131
- var SOURCES = ["dcursed", "cursor-plan", "claude-code-plan", "mermaid", "markdown"];
129
+ var SCHEMA = "diacode.plan/1";
130
+ var OLDER = ["diacode.plan/0", "dcursed.plan/1", "dcursed.plan/0"];
131
+ var SOURCES = ["diacode", "dcursed", "cursor-plan", "claude-code-plan", "mermaid", "markdown"];
132
132
  var STATUS_FROM = ["reported", "observed", "you"];
133
133
  var isString = (v, min = 0, max = Infinity) => typeof v === "string" && v.length >= min && v.length <= max;
134
134
  var FILES_MAX = 64;
135
135
  var FILE_MAX = 256;
136
136
  var DETAIL_MAX = 4e3;
137
+ var OPTIONS_MAX = 8;
138
+ var OPTION_MAX = 80;
139
+ var isOptionList = (v) => Array.isArray(v) && v.length >= 1 && v.length <= OPTIONS_MAX && v.every((o) => isString(o, 1, OPTION_MAX) && o.trim() === o);
140
+ var OPTIONS_PROBLEM = `options is 1-${OPTIONS_MAX} answers, each 1-${OPTION_MAX} characters with no space at either end`;
137
141
  var NOTE_MAX = 2e3;
138
142
  function upgradePlan(plan) {
139
- return isObject(plan) && OLDER.includes(plan.schema) ? { ...plan, schema: SCHEMA } : plan;
143
+ if (!isObject(plan) || !OLDER.includes(plan.schema)) return plan;
144
+ const source = isObject(plan.source) && plan.source.kind === "dcursed" ? { source: { ...plan.source, kind: "diacode" } } : {};
145
+ return { ...plan, ...source, schema: SCHEMA };
140
146
  }
141
147
  var isFileList = (v) => Array.isArray(v) && v.length <= FILES_MAX && v.every((s) => isString(s, 1, FILE_MAX));
142
148
  var FILES_PROBLEM = `files is a list of paths or globs (at most ${FILES_MAX}, each 1-${FILE_MAX} characters)`;
@@ -197,11 +203,12 @@ function validatePlan(plan) {
197
203
  problems.push(`${at}: not an object`);
198
204
  return;
199
205
  }
200
- onlyKeys(e, ["from", "to", "label", "kind", "question", "passed", "answer"], at, problems);
206
+ onlyKeys(e, ["from", "to", "label", "kind", "question", "options", "passed", "answer"], at, problems);
201
207
  if (e.label !== void 0 && !isString(e.label, 0, 120)) problems.push(`${at}: label is at most 120 characters`);
202
208
  if (e.kind !== void 0 && (e.kind === "needs" || !EDGE_KINDS.includes(e.kind))) problems.push(`${at}: kind is one of ${EDGE_KINDS.slice(1).join(", ")} (leave it out for needs)`);
203
209
  const checkpoint2 = CHECKPOINTS.has(e.kind);
204
210
  if (e.question !== void 0 && (e.kind !== "ask" || !isString(e.question, 1, NOTE_MAX))) problems.push(`${at}: only an "ask" checkpoint has a question, of 1-${NOTE_MAX} characters`);
211
+ if (e.options !== void 0 && (e.kind !== "ask" || !isOptionList(e.options))) problems.push(`${at}: only an "ask" checkpoint has options; ${OPTIONS_PROBLEM}`);
205
212
  if (e.passed !== void 0 && (!checkpoint2 || e.passed !== true)) problems.push(`${at}: only a checkpoint is passed, and passed is true`);
206
213
  if (e.answer !== void 0 && (e.passed !== true || !isString(e.answer, 0, NOTE_MAX))) problems.push(`${at}: only a passed checkpoint has an answer, of at most ${NOTE_MAX} characters`);
207
214
  if (!(e.from in plan.nodes)) problems.push(`${at}: "${e.from}" is not a step`);
@@ -237,15 +244,15 @@ var OPS = {
237
244
  "node.add": { required: ["label"], optional: ["id", "kind", "detail", "group", "files", "touches", "after"], ids: ["id"] },
238
245
  "node.set": { required: ["id"], optional: ["label", "kind", "detail", "group", "files", "touches"], ids: ["id"], oneOf: ["label", "kind", "detail", "group", "files", "touches"] },
239
246
  "node.remove": { required: ["id"], ids: ["id"] },
240
- "edge.add": { required: ["from", "to"], optional: ["label", "kind"], ids: ["from", "to"] },
247
+ "edge.add": { required: ["from", "to"], optional: ["label", "kind", "options"], ids: ["from", "to"] },
241
248
  "edge.remove": { required: ["from", "to"], ids: ["from", "to"] },
242
249
  "edge.rewire": { required: ["from", "to"], optional: ["newFrom", "newTo"], ids: ["from", "to", "newFrom", "newTo"], oneOf: ["newFrom", "newTo"] },
243
250
  "edge.reverse": { required: ["from", "to"], ids: ["from", "to"] },
244
- "edge.set": { required: ["from", "to"], optional: ["label", "kind"], ids: ["from", "to"], oneOf: ["label", "kind"] },
251
+ "edge.set": { required: ["from", "to"], optional: ["label", "kind", "options"], ids: ["from", "to"], oneOf: ["label", "kind", "options"] },
245
252
  // A checkpoint: you pass it (with your answer or input), an agent asks its question at an `ask`, and an approval
246
253
  // you withhold sends the step before it back.
247
254
  "gate.pass": { required: ["from", "to"], optional: ["answer"], ids: ["from", "to"] },
248
- "gate.ask": { required: ["from", "to", "question"], ids: ["from", "to"] },
255
+ "gate.ask": { required: ["from", "to", "question"], optional: ["options"], ids: ["from", "to"] },
249
256
  "gate.reject": { required: ["from", "to"], optional: ["reason"], ids: ["from", "to"] },
250
257
  "status.set": { required: ["id", "status"], optional: ["note"], ids: ["id"] },
251
258
  claim: { required: ["id"], ids: ["id"] },
@@ -279,6 +286,7 @@ function validateOp(op) {
279
286
  }
280
287
  if (op.question !== void 0 && !isString(op.question, 1, NOTE_MAX)) problems.push(`${op.op}: question is 1-${NOTE_MAX} characters`);
281
288
  if (op.answer !== void 0 && !isString(op.answer, 0, NOTE_MAX)) problems.push(`${op.op}: answer is at most ${NOTE_MAX} characters`);
289
+ if (op.options !== void 0 && !isOptionList(op.options)) problems.push(`${op.op}: ${OPTIONS_PROBLEM}`);
282
290
  if (op.files !== void 0 && !isFileList(op.files)) problems.push(`${op.op}: ${FILES_PROBLEM}`);
283
291
  if (op.touches !== void 0 && !isTouches(op.touches)) problems.push(`${op.op}: ${TOUCHES_PROBLEM}`);
284
292
  if (op.group !== void 0 && !(op.op === "node.set" && op.group === null) && !isString(op.group, 1, 80)) problems.push(`${op.op}: group is 1-80 characters`);
@@ -443,7 +451,7 @@ function step(p, op, ctx) {
443
451
  }
444
452
  case "edge.add":
445
453
  if (frozen(op.to)) refuse(`${op.to} is done; what it depended on is history`);
446
- addEdge(p, op.from, op.to, op.label, op.kind);
454
+ addEdge(p, op.from, op.to, op.label, op.kind, op.options);
447
455
  affectFrom(op.to, `now depends on ${op.from}`);
448
456
  return op;
449
457
  case "edge.remove": {
@@ -479,6 +487,10 @@ function step(p, op, ctx) {
479
487
  else e.kind = op.kind;
480
488
  clearCheckpoint(e);
481
489
  }
490
+ if (op.options !== void 0) {
491
+ if (e.kind !== "ask") refuse(`${op.from} \u2192 ${op.to} is not an "ask" checkpoint; only one has options`);
492
+ e.options = op.options;
493
+ }
482
494
  return op;
483
495
  }
484
496
  case "gate.pass": {
@@ -495,6 +507,7 @@ function step(p, op, ctx) {
495
507
  if (e.kind !== "ask") refuse(`${op.from} \u2192 ${op.to} is an "${e.kind}" checkpoint; only an "ask" one takes a question`);
496
508
  if (e.passed) refuse(`the checkpoint ${op.from} \u2192 ${op.to} is passed already: ${op.to} can start`);
497
509
  e.question = op.question;
510
+ if (op.options !== void 0) e.options = op.options;
498
511
  return op;
499
512
  }
500
513
  case "gate.reject": {
@@ -616,12 +629,13 @@ function checkEdge(p, from, to, ignore) {
616
629
  const without = ignore ? { ...p, edges: p.edges.filter((e) => e !== ignore) } : p;
617
630
  if (reaches(without, to, from)) refuse(`${from} \u2192 ${to} would make a loop`);
618
631
  }
619
- function addEdge(p, from, to, label, kind) {
632
+ function addEdge(p, from, to, label, kind, options) {
620
633
  checkEdge(p, from, to);
634
+ if (options && kind !== "ask") refuse('only an "ask" checkpoint has options');
621
635
  p.edges.push({ from, to, ...label ? { label } : {}, ...kind && kind !== "needs" ? { kind: (
622
636
  /** @type {Exclude<import('./types.js').EdgeKind, 'needs'>} */
623
637
  kind
624
- ) } : {} });
638
+ ) } : {}, ...options ? { options } : {} });
625
639
  }
626
640
  function checkpoint(p, from, to) {
627
641
  const e = findEdge(p, from, to);
@@ -630,6 +644,7 @@ function checkpoint(p, from, to) {
630
644
  }
631
645
  function clearCheckpoint(e) {
632
646
  delete e.question;
647
+ delete e.options;
633
648
  delete e.passed;
634
649
  delete e.answer;
635
650
  }
@@ -661,7 +676,7 @@ function derive(plan) {
661
676
  gates.push({ from: e.from, to: e.to, kind: (
662
677
  /** @type {Gate['kind']} */
663
678
  e.kind
664
- ), ...e.label ? { label: e.label } : {}, ...e.question ? { question: e.question } : {}, turn });
679
+ ), ...e.label ? { label: e.label } : {}, ...e.question ? { question: e.question } : {}, ...e.question && e.options ? { options: e.options } : {}, turn });
665
680
  }
666
681
  if (waiting.length) blocked.set(id, waiting);
667
682
  else if (at.length) held.set(id, at.map((e) => e.from));
@@ -781,7 +796,7 @@ function opposite(reason) {
781
796
  var ORDER = {
782
797
  plan: ["schema", "id", "title", "goal", "rev", "phase", "source", "nodes", "edges", "proposals"],
783
798
  node: ["label", "kind", "group", "detail", "status", "statusFrom", "statusBy", "note", "owner", "files", "touches"],
784
- edge: ["from", "to", "kind", "label", "question", "passed", "answer"],
799
+ edge: ["from", "to", "kind", "label", "question", "options", "passed", "answer"],
785
800
  proposal: ["id", "by", "at", "reason", "ops"],
786
801
  layout: ["schema", "plan", "direction", "canvas", "collapsed", "nodes"],
787
802
  place: ["x", "y", "pinned"]
@@ -927,7 +942,7 @@ function diffToOps(before, after, { bridge = false } = {}) {
927
942
  }
928
943
  }
929
944
  }
930
- for (const c of came) ops.push(pick({ op: "edge.add", from: c.from, to: c.to, label: c.label, kind: c.kind }));
945
+ for (const c of came) ops.push(pick({ op: "edge.add", from: c.from, to: c.to, label: c.label, kind: c.kind, options: c.kind === "ask" ? c.options : void 0 }));
931
946
  for (const [k, e] of afterEdges) {
932
947
  const was = beforeEdges.get(k);
933
948
  const set = was && edgeChange(was, e);
@@ -950,7 +965,8 @@ function diffToOps(before, after, { bridge = false } = {}) {
950
965
  const was = beforeEdges.get(k) ?? /** @type {import('./types.js').Edge} */
951
966
  { from: e.from, to: e.to };
952
967
  const reset = kindOf(was) !== kindOf(e);
953
- if (e.question !== void 0 && (reset || e.question !== was.question) && !e.passed) ops.push({ op: "gate.ask", from: e.from, to: e.to, question: e.question });
968
+ if (e.question !== void 0 && (reset || e.question !== was.question || JSON.stringify(e.options) !== JSON.stringify(was.options)) && !e.passed) ops.push({ op: "gate.ask", from: e.from, to: e.to, question: e.question, ...e.options ? { options: e.options } : {} });
969
+ else if (e.options !== void 0 && e.question === void 0 && kindOf(e) === "ask" && (reset || JSON.stringify(e.options) !== JSON.stringify(was.options))) ops.push({ op: "edge.set", from: e.from, to: e.to, options: e.options });
954
970
  if (e.passed && (reset || !was.passed)) ops.push(pick({ op: "gate.pass", from: e.from, to: e.to, answer: e.answer }));
955
971
  else if (!e.passed && was.passed && !reset) ignored.push(`${e.from} \u2192 ${e.to}: passed (a checkpoint is not taken back; change the arrow's kind to reset it)`);
956
972
  }
@@ -1264,7 +1280,7 @@ var STEP = { along: 230, across: 72 };
1264
1280
  var FIRST = { along: 90, across: 50 };
1265
1281
  var MARGIN = { x: 70, y: 55 };
1266
1282
  var MIN_CANVAS = { width: 640, height: 240 };
1267
- var newLayout = (planId, direction = "LR") => ({ schema: "dcursed.layout/0", plan: planId, direction, canvas: { ...MIN_CANVAS }, nodes: {} });
1283
+ var newLayout = (planId, direction = "LR") => ({ schema: "diacode.layout/0", plan: planId, direction, canvas: { ...MIN_CANVAS }, nodes: {} });
1268
1284
  function placeUnplaced(plan, layout, { paths, loops = false } = {}) {
1269
1285
  const td = layout.direction === "TD";
1270
1286
  const get = (p) => td ? { along: p.y, across: p.x } : { along: p.x, across: p.y };
@@ -1473,7 +1489,7 @@ function arrowIn(e) {
1473
1489
  if (!e.kind) return e.from;
1474
1490
  const bits = [KIND[e.kind]];
1475
1491
  if (e.kind === "input" && e.label) bits.push(quote(e.label, 80));
1476
- if (e.question) bits.push(`asked ${quote(e.question, 160)}`);
1492
+ if (e.question) bits.push(`asked ${quote(e.question, 160)}${e.options?.length ? `, offering ${e.options.map((o) => quote(o, 60)).join(" / ")}` : ""}`);
1477
1493
  if (e.passed) bits.push(e.answer ? `PASSED, the person said ${quote(e.answer, 300)}` : "PASSED");
1478
1494
  return `${e.from} (${bits.join("; ")})`;
1479
1495
  }
@@ -1510,7 +1526,7 @@ function describeOp(op) {
1510
1526
  case "gate.pass":
1511
1527
  return `the checkpoint ${op.from} \u2192 ${op.to} is passed${op.answer ? `: ${quote(op.answer, 300)}` : ""}; ${op.to} may start`;
1512
1528
  case "gate.ask":
1513
- return `asked the person before ${op.to}: ${quote(op.question, 300)}`;
1529
+ return `asked the person before ${op.to}: ${quote(op.question, 300)}${op.options?.length ? `, offering ${op.options.map((o) => quote(o, 60)).join(" / ")}` : ""}`;
1514
1530
  case "gate.reject":
1515
1531
  return `${op.from} was sent back, not approved${op.reason ? ` (${quote(op.reason, 300)})` : ""}: it is to be done again`;
1516
1532
  case "status.set":
@@ -1664,7 +1680,7 @@ function describeBrief({ plan, review }) {
1664
1680
  `DiaCode plan "${plan.title}" (${plan.id}) \xB7 rev ${plan.rev} \xB7 ${plan.phase} \xB7 ${finished}/${work.length} done.`,
1665
1681
  ...plan.phase === "paused" ? [PAUSED] : [],
1666
1682
  ...parts.length ? [parts.join(" ")] : [],
1667
- "The person edits this plan while you work. Follow it with the dcursed tools (plan_read, step_start, step_done), report as you go, and read what changed since you last looked."
1683
+ "The person edits this plan while you work. Follow it with the diacode tools (plan_read, step_start, step_done), report as you go, and read what changed since you last looked."
1668
1684
  ].join("\n");
1669
1685
  }
1670
1686
 
@@ -2058,6 +2074,7 @@ __export(arch_exports, {
2058
2074
  standIn: () => standIn,
2059
2075
  stepArrow: () => stepArrow,
2060
2076
  toFlowchart: () => toFlowchart,
2077
+ upgradeArch: () => upgradeArch,
2061
2078
  usedBy: () => usedBy,
2062
2079
  usersOf: () => usersOf,
2063
2080
  validateArch: () => validateArch,
@@ -2113,7 +2130,8 @@ function standIn(arch2, id, folded) {
2113
2130
  }
2114
2131
 
2115
2132
  // packages/core/src/arch/validate.js
2116
- var SCHEMA2 = "dcursed.arch/0";
2133
+ var SCHEMA2 = "diacode.arch/0";
2134
+ var OLDER2 = ["dcursed.arch/0"];
2117
2135
  var KINDS2 = (
2118
2136
  /** @type {const} */
2119
2137
  ["person", "service", "component", "store", "queue", "group"]
@@ -2122,7 +2140,12 @@ var PHASES2 = (
2122
2140
  /** @type {const} */
2123
2141
  ["draft", "accepted"]
2124
2142
  );
2125
- var SOURCES2 = ["dcursed", "mermaid", "c4", "markdown", "cursor-plan"];
2143
+ var SOURCES2 = ["diacode", "dcursed", "mermaid", "c4", "markdown", "cursor-plan"];
2144
+ function upgradeArch(a) {
2145
+ if (!isObject2(a) || !OLDER2.includes(a.schema)) return a;
2146
+ const source = isObject2(a.source) && a.source.kind === "dcursed" ? { source: { ...a.source, kind: "diacode" } } : {};
2147
+ return { ...a, ...source, schema: SCHEMA2 };
2148
+ }
2126
2149
  var TECH_MAX = 120;
2127
2150
  var FLOWS_MAX = 40;
2128
2151
  var FLOW_STEPS_MAX = 60;
@@ -2639,15 +2662,17 @@ function addArrow(a, op) {
2639
2662
 
2640
2663
  // packages/core/src/arch/log.js
2641
2664
  function newArch({ title, goal, phase = "accepted", source }) {
2642
- return { schema: SCHEMA2, title, ...goal ? { goal } : {}, rev: 0, phase, source: source ?? { kind: "dcursed" }, nodes: {}, edges: [], flows: [] };
2665
+ return { schema: SCHEMA2, title, ...goal ? { goal } : {}, rev: 0, phase, source: source ?? { kind: "diacode" }, nodes: {}, edges: [], flows: [] };
2643
2666
  }
2644
2667
  function replay2(start, lines) {
2645
2668
  let arch2 = start;
2646
2669
  for (const line of lines) {
2647
2670
  if (line.snapshot) {
2648
- arch2 = /** @type {Arch} */
2649
- /** @type {unknown} */
2650
- structuredClone(line.snapshot);
2671
+ arch2 = upgradeArch(
2672
+ /** @type {Arch} */
2673
+ /** @type {unknown} */
2674
+ structuredClone(line.snapshot)
2675
+ );
2651
2676
  if (arch2.rev !== line.rev) throw new Error(`log rev ${line.rev}: the snapshot is rev ${arch2.rev}`);
2652
2677
  continue;
2653
2678
  }
@@ -3288,7 +3313,7 @@ function newPlan({ id, title, goal, source }) {
3288
3313
  ...goal ? { goal } : {},
3289
3314
  rev: 0,
3290
3315
  phase: "planning",
3291
- source: source ?? { kind: "dcursed" },
3316
+ source: source ?? { kind: "diacode" },
3292
3317
  nodes: {},
3293
3318
  edges: []
3294
3319
  };
@@ -3304,12 +3329,12 @@ import { watch, mkdirSync } from "node:fs";
3304
3329
  // packages/server/src/files.js
3305
3330
  import { mkdir, readFile, writeFile, rename, appendFile, readdir } from "node:fs/promises";
3306
3331
  import { join, dirname } from "node:path";
3307
- var plansDir = (root2) => join(root2, ".dcursed", "plans");
3308
- var dcursedDir = (root2) => join(root2, ".dcursed");
3332
+ var plansDir = (root2) => join(root2, ".diacode", "plans");
3333
+ var diacodeDir = (root2) => join(root2, ".diacode");
3309
3334
  var archPathsOf = (root2) => ({
3310
- arch: join(dcursedDir(root2), "architecture.json"),
3311
- layout: join(dcursedDir(root2), "architecture.layout.json"),
3312
- log: join(dcursedDir(root2), "architecture.log.jsonl")
3335
+ arch: join(diacodeDir(root2), "architecture.json"),
3336
+ layout: join(diacodeDir(root2), "architecture.layout.json"),
3337
+ log: join(diacodeDir(root2), "architecture.log.jsonl")
3313
3338
  });
3314
3339
  var pathsOf = (root2, id) => ({
3315
3340
  plan: join(plansDir(root2), `${id}.plan.json`),
@@ -3375,12 +3400,12 @@ var HttpError = class extends Error {
3375
3400
  this.status = status;
3376
3401
  }
3377
3402
  };
3378
- var DRIFT_IGNORED = /(^|\/)(\.dcursed|\.opencode|\.git|node_modules|dist|build|coverage)\/|(^|\/)(package-lock\.json|yarn\.lock|pnpm-lock\.yaml)$/;
3403
+ var DRIFT_IGNORED = /(^|\/)(\.diacode|\.opencode|\.git|node_modules|dist|build|coverage)\/|(^|\/)(package-lock\.json|yarn\.lock|pnpm-lock\.yaml)$/;
3379
3404
  var same3 = (a, b) => JSON.stringify(canonicalPlan(a)) === JSON.stringify(canonicalPlan(b));
3380
3405
  var LIVE = /* @__PURE__ */ new Set(["planning", "approved", "executing", "paused"]);
3381
3406
  var PlanStore = class extends EventEmitter {
3382
3407
  /**
3383
- * @param {string} root the repository; plans live in <root>/.dcursed/plans/
3408
+ * @param {string} root the repository; plans live in <root>/.diacode/plans/
3384
3409
  * @param {{ now?: () => string }} [options]
3385
3410
  */
3386
3411
  constructor(root2, { now = () => (/* @__PURE__ */ new Date()).toISOString() } = {}) {
@@ -3634,6 +3659,19 @@ var PlanStore = class extends EventEmitter {
3634
3659
  );
3635
3660
  this.emit("drift", { id });
3636
3661
  }
3662
+ /**
3663
+ * You said a file outside the plan needs no step (a scratch file, say): it is not offered again, unless an agent edits it again.
3664
+ * @param {string} id @param {string} [file] none: all of them
3665
+ * @returns {number} how many were let go
3666
+ */
3667
+ ignoreOutside(id, file) {
3668
+ const files = this.outside.get(id);
3669
+ if (!files) return 0;
3670
+ const gone = file === void 0 ? files.size : Number(files.delete(file));
3671
+ if (file === void 0) files.clear();
3672
+ if (gone) this.emit("drift", { id });
3673
+ return gone;
3674
+ }
3637
3675
  /**
3638
3676
  * The files agents have edited that no step lists *now* (a step that has since come to list one
3639
3677
  * covers it), newest first: what the plan has drifted from. @param {string} id
@@ -3792,8 +3830,8 @@ function parsePlan(text2, id) {
3792
3830
  function parseLayout(text2, id) {
3793
3831
  try {
3794
3832
  const l = JSON.parse(text2);
3795
- if (l?.schema !== "dcursed.layout/0" || l.plan !== id || typeof l.nodes !== "object" || l.nodes === null) return null;
3796
- return { ...l, direction: l.direction === "TD" ? "TD" : "LR" };
3833
+ if (!["diacode.layout/0", "dcursed.layout/0"].includes(l?.schema) || l.plan !== id || typeof l.nodes !== "object" || l.nodes === null) return null;
3834
+ return { ...l, schema: "diacode.layout/0", direction: l.direction === "TD" ? "TD" : "LR" };
3797
3835
  } catch {
3798
3836
  return null;
3799
3837
  }
@@ -3810,7 +3848,7 @@ var same4 = (a, b) => JSON.stringify(arch.canonicalArch(a)) === JSON.stringify(a
3810
3848
  var newLayout2 = () => newLayout(arch.LAYOUT_OF);
3811
3849
  var ArchStore = class extends EventEmitter2 {
3812
3850
  /**
3813
- * @param {string} root the repository; the architecture lives in <root>/.dcursed/architecture.json
3851
+ * @param {string} root the repository; the architecture lives in <root>/.diacode/architecture.json
3814
3852
  * @param {{ now?: () => string }} [options]
3815
3853
  */
3816
3854
  constructor(root2, { now = () => (/* @__PURE__ */ new Date()).toISOString() } = {}) {
@@ -4005,7 +4043,7 @@ var ArchStore = class extends EventEmitter2 {
4005
4043
  return this.proposeFootprint(planId, arch.dropPlannedOps, `plan ${planId} is abandoned: drop what it planned, and keep what it was going to retire`);
4006
4044
  }
4007
4045
  /**
4008
- * @param {string} planId @param {(a: Arch, planId: string) => import('@dcursed/core/src/arch/types.js').Op[]} makeOps @param {string} reason
4046
+ * @param {string} planId @param {(a: Arch, planId: string) => import('@diacode/core/src/arch/types.js').Op[]} makeOps @param {string} reason
4009
4047
  */
4010
4048
  proposeFootprint(planId, makeOps, reason) {
4011
4049
  return this.enqueue(async () => {
@@ -4032,8 +4070,8 @@ var ArchStore = class extends EventEmitter2 {
4032
4070
  // ── hand edits ───────────────────────────────────────────────────────────
4033
4071
  /** Watch the folder; a file someone else wrote is a hand edit. */
4034
4072
  watch() {
4035
- mkdirSync2(dcursedDir(this.root), { recursive: true });
4036
- this.watcher = watch2(dcursedDir(this.root), (_event, filename) => {
4073
+ mkdirSync2(diacodeDir(this.root), { recursive: true });
4074
+ this.watcher = watch2(diacodeDir(this.root), (_event, filename) => {
4037
4075
  const m = filename && /^architecture(\.layout)?\.json$/.exec(String(filename));
4038
4076
  if (!m) return;
4039
4077
  clearTimeout(this.timers.get(m[0]));
@@ -4132,14 +4170,16 @@ function parseArch(text2) {
4132
4170
  return `architecture.json is not JSON: ${/** @type {Error} */
4133
4171
  e.message}`;
4134
4172
  }
4173
+ parsed = arch.upgradeArch(parsed);
4135
4174
  const problems = arch.validateArch(parsed);
4136
4175
  return problems.length ? `architecture.json: ${problems.join("; ")}` : parsed;
4137
4176
  }
4177
+ var LAYOUT_IDS = ["diacode.layout/0", "dcursed.layout/0"];
4138
4178
  function parseLayout2(text2) {
4139
4179
  try {
4140
4180
  const l = JSON.parse(text2);
4141
- if (l?.schema !== "dcursed.layout/0" || typeof l.nodes !== "object" || l.nodes === null) return null;
4142
- return { ...l, direction: l.direction === "TD" ? "TD" : "LR" };
4181
+ if (!LAYOUT_IDS.includes(l?.schema) || typeof l.nodes !== "object" || l.nodes === null) return null;
4182
+ return { ...l, schema: "diacode.layout/0", direction: l.direction === "TD" ? "TD" : "LR" };
4143
4183
  } catch {
4144
4184
  return null;
4145
4185
  }
@@ -4150,11 +4190,11 @@ import { randomUUID } from "node:crypto";
4150
4190
 
4151
4191
  // packages/server/src/guide.js
4152
4192
  var FLOW_HINT = "How it goes: tell your agent the task. It draws the architecture in the editor; you change what is wrong and press Approve architecture. It draws the plan; you change it and press Approve plan. It checks the architecture against the plan and asks you about any change; then you press Start. After that, a change you make on one side is told to the agent, which proposes the matching change on the other.";
4153
- var GUIDE = `DiaCode keeps this repository's architecture and plans as files in .dcursed/, and the person edits them in a diagram while you work, so they change under you.
4193
+ var GUIDE = `DiaCode keeps this repository's architecture and plans as files in .diacode/, and the person edits them in a diagram while you work, so they change under you.
4154
4194
 
4155
4195
  THE ORDER. The person approves each stage in the editor before the next; do the stage you are in, then STOP and say it is ready.
4156
4196
  1. THE TASK. When the person gives you something to build or change, your first and only job is the ARCHITECTURE: call arch_draft with the system AS IT WILL BE (who uses it, the services, the parts inside them, the stores and queues, and how they use each other). Mark every part that does not exist yet planned: true. An empty repository is no excuse: draw what you are about to build. Then stop and say in a sentence that it is ready to review. Do not call plan_create, do not write code, and do not ask the person questions in your own window: assume what you need, say so in the architecture (the goal, a box's detail), and they correct the drawing.
4157
- 2. THEY APPROVE THE ARCHITECTURE. You are sent a message that starts with [DiaCode]. Draw the PLAN on it with plan_create, then stop and say it is ready to review. A question the task told you to ask before building (or at some point in the build) is an ask checkpoint on the arrow into the first step that needs the answer: that step gets after: [{ "id": "<a step before it>", "kind": "ask", "label": "<the question>" }] (a short first step such as "Set up the project" will do as the step before). When that step is next, you call step_ask on it, the step the arrow points at, and end your turn; the person answers in the editor, so do not ask it in your window and do not make a step of its own for asking. If you did ask in your window, write their answer into the detail of the step it concerns.
4197
+ 2. THEY APPROVE THE ARCHITECTURE. You are sent a message that starts with [DiaCode]. Draw the PLAN on it with plan_create, then stop and say it is ready to review. A question the task told you to ask before building (or at some point in the build) is an ask checkpoint on the arrow into the first step that needs the answer: that step gets after: [{ "id": "<a step before it>", "kind": "ask", "label": "<the question>" }] (a short first step such as "Set up the project" will do as the step before). When that step is next, you call step_ask on it, the step the arrow points at, and end your turn; the person answers in the editor, so do not ask it in your window and do not make a step of its own for asking. If you did ask in your window, write their answer into the detail of the step it concerns. ONE question per ask: never several numbered questions in one box (the person answers "1" and you cannot tell which). Write the question in a sentence, list its answers in its text, "(1) one vote each (2) several", and give the same answers as step_ask's \`options\`, so the person presses one; if you have two questions, ask the second after the first is answered.
4158
4198
  3. THEY APPROVE THE PLAN. You are sent a [DiaCode] message: the plan is NOT started. Check the architecture against it, once: every part the plan adds is a box (planned: true while it does not exist), every part it removes is marked retiring, each step lists the boxes it changes as touches. Fix what is missing with arch_edit; your changes to an approved architecture arrive as proposals the person accepts or rejects, so give each a plain reason. Then stop and say what you changed, or that nothing needed to change. Do not start any step.
4159
4199
  4. THEY PRESS START. You are sent a [DiaCode] message: carry the plan out, below.
4160
4200
  5. WHILE IT RUNS, and while it is approved and not started, what the person changes on one side is told to you as a [DiaCode] message. Make the other side agree: a change to the plan that adds, removes or reconnects a part of the system gets the matching arch_edit; a change to the architecture that a step no longer matches gets the matching plan_edit. Both arrive as proposals; say why. If nothing needs to change, say so.
@@ -4162,7 +4202,7 @@ Each DiaCode tool's answer ends with the stage you are at. When it says to wait,
4162
4202
 
4163
4203
  How to work with a plan
4164
4204
  - plan_list, then plan_read. A plan is a graph of steps; an arrow from A to B means B depends on A. A step marked READY has nothing left to wait for.
4165
- - Some arrows say more. "order only" (after): B comes later but does not use what A makes. A CHECKPOINT is where the person comes in before B starts: they approve A's result, they give input B needs, or (ask) you ask them first with step_ask and end your turn. A step that WAITS AT A CHECKPOINT cannot be started until the person passes it; you are sent their answer when they do.
4205
+ - Some arrows say more. "order only" (after): B comes later but does not use what A makes. A CHECKPOINT is where the person comes in before B starts: they approve A's result, they give input B needs, or (ask) you ask them first with step_ask and end your turn. When the task says to show them something before going on ("show me the page before the import"), that is an approve checkpoint (kind: "approve", with a label saying what to look at) on the arrow out of the step that shows it; a file you need from them is an input checkpoint on an arrow into the step that needs it, a different arrow, not folded into the approval's label. A step that WAITS AT A CHECKPOINT cannot be started until the person passes it; you are sent their answer when they do.
4166
4206
  - Every reply ends with what the person (or another agent) changed since you last looked. Read it before your next step: their edits win over what you remember.
4167
4207
  - If a reply (or a tool result) starts with HEADS UP, something happened to a step you hold: it was cancelled, removed, finished or reopened by the person, reworded, or has a new prerequisite. Deal with that before anything else: stop on a cancelled or removed step, re-read a reworded one, and if a new prerequisite blocks you, say so with step_wait or do the prerequisite if it is ready.
4168
4208
  - To start a step call step_start (refused until the person has pressed Start). When you finish it call step_done with a note saying what is true now (the tests that pass, the files you changed). Call step_failed if it failed and step_wait if you need the person, then end your turn: their answer is sent to you. Report as you go, not at the end.
@@ -4172,17 +4212,20 @@ How to work with a plan
4172
4212
  - Once the person has approved a plan, changes to its structure (steps, arrows, labels) become proposals the person accepts; statuses and claims land at once. Finished steps are history: you cannot rewrite them.
4173
4213
  - The person can PAUSE a plan: finish the step you are on, then start nothing new and end your turn; you are told when it resumes, with what they changed meanwhile. They can also STOP it: then stop at once, without finishing your step, and end your turn (every tool you call is refused until you do). A stopped plan waits for them to press Start again.
4174
4214
  - When every step is done, say so in a sentence and stop: the person closes the plan in the editor, and is then asked whether to make the boxes it planned real.
4175
- - Do not edit the files in .dcursed/plans/ by hand. The tools check the rules and keep the log.
4215
+ - Do not edit the files in .diacode/plans/ by hand. The tools check the rules and keep the log.
4216
+
4217
+ Showing the person something
4218
+ - A step that shows the person something (a page, a running app, a file to open) leaves it RUNNING when the step ends: do not stop the server or close the window until the person has approved. Put the full address in that step's note (step_done), such as "Running at http://localhost:3000", and say there what to try. A checkpoint that asks the person to look at something (an approve checkpoint, or the label you give it) says what to look at and where, never "try npm start". The editor turns an address in a note into a link and puts an Open button on the checkpoint.
4176
4219
 
4177
4220
  Working while the person watches
4178
4221
  - Write and change files with your file tools, not with shell redirects or heredocs, and keep each shell command plain: one command, no loops, no variables. The person's tool asks them to approve every command it cannot check, and each such prompt holds the run until they come to its window.
4179
4222
 
4180
4223
  The architecture
4181
- - The repository has one ARCHITECTURE, in .dcursed/architecture.json: the system as the person has approved it, which every plan is a change to. Its boxes are person, service, component, store, queue or group (external: someone else runs it); an arrow from A to B means A USES B (not "A first"); a box sits only in a service or a group, and a box with boxes inside it is a frame that takes no arrows. Flows are the ordered steps of what a user does, over those arrows.
4224
+ - The repository has one ARCHITECTURE, in .diacode/architecture.json: the system as the person has approved it, which every plan is a change to. Its boxes are person, service, component, store, queue or group (external: someone else runs it); an arrow from A to B means A USES B (not "A first"); a box sits only in a service or a group, and a box with boxes inside it is a frame that takes no arrows. Flows are the ordered steps of what a user does, over those arrows.
4182
4225
  - Draw what runs and who uses it, and keep it small: a few boxes per service. Tests, build scripts, docs and configuration are not boxes (list them in the files of the box they belong to): a test box that uses everything draws an arrow to everything. Keep arrow labels to a few words ("Fetch poems"); say the protocol in tech, not in the label.
4183
4226
  - arch_read shows it; read it before you plan work that changes the system. arch_draft makes the first one (only when there is none; a repository that already has code is drawn from the code and the task together). A plan is refused until the person has approved an architecture.
4184
4227
  - When a plan adds or removes a part of the system, say so in the architecture: arch_edit a box with planned: true (or retiring: "<plan id>"), and give the plan's steps the boxes they change with touches. When the plan is closed the person is asked to make it real.
4185
- - Do not edit .dcursed/architecture.json by hand either.`;
4228
+ - Do not edit .diacode/architecture.json by hand either.`;
4186
4229
 
4187
4230
  // packages/server/src/calls.js
4188
4231
  import { EventEmitter as EventEmitter3 } from "node:events";
@@ -4248,7 +4291,7 @@ var Calls = class extends EventEmitter3 {
4248
4291
  }
4249
4292
  /**
4250
4293
  * A batch landed. Only yours can make a call: an agent does not wake an agent.
4251
- * @param {string} id @param {import('@dcursed/core/src/log.js').LogLine} line
4294
+ * @param {string} id @param {import('@diacode/core/src/log.js').LogLine} line
4252
4295
  */
4253
4296
  noticed(id, line) {
4254
4297
  if (line.actor !== "you" || line.proposed) return;
@@ -4279,7 +4322,7 @@ var Calls = class extends EventEmitter3 {
4279
4322
  const archToo = was === "planning" && this.arch?.arch?.phase === "draft" && to !== void 0 && this.archDrafter() === to;
4280
4323
  if (archToo) this.acceptArch().catch(() => {
4281
4324
  });
4282
- this.make({ plan: id, rev: line.rev, kind: "planApproved", to, text: planApprovedText(plan, id, { archToo, hasArch: Boolean(this.arch?.exists) }) });
4325
+ this.make({ plan: id, rev: line.rev, kind: "planApproved", to, text: planApprovedText(plan, id, { archToo, hasArch: Boolean(this.arch?.exists), bare: this.bareSteps(id).map((b) => ({ id: b, label: plan.nodes[b]?.label ?? b })) }) });
4283
4326
  } else if (op.op === "plan.set" && op.phase) {
4284
4327
  phased = true;
4285
4328
  this.dropQueued(id);
@@ -4307,7 +4350,7 @@ var Calls = class extends EventEmitter3 {
4307
4350
  * A batch landed on the architecture. Only yours can make a call. Accepting the draft an agent drew tells it that its
4308
4351
  * changes are proposals from now on; accepting or rejecting a proposal tells the agent that made it what you decided
4309
4352
  * (the server's own, for a finished plan's boxes, has no agent to tell). Several in a row are one call to each agent.
4310
- * @param {{ rev: number, line: import('@dcursed/core/src/log.js').LogLine, phaseWas?: string, quiet?: boolean }} e
4353
+ * @param {{ rev: number, line: import('@diacode/core/src/log.js').LogLine, phaseWas?: string, quiet?: boolean }} e
4311
4354
  */
4312
4355
  archNoticed({ rev, line, phaseWas, quiet }) {
4313
4356
  const arch2 = this.arch?.arch;
@@ -4380,7 +4423,8 @@ var Calls = class extends EventEmitter3 {
4380
4423
  const since = Math.min(seen ?? from - 1, from - 1);
4381
4424
  const lines = arch_exports.describeChanges(this.arch?.since(since) ?? [], since, { not: actor });
4382
4425
  if (!lines.length) return;
4383
- this.make({ plan: ARCH_SCOPE, rev, kind: "archChanged", to: actor, text: archChangedText(plan, planId, a, lines) });
4426
+ const bare = this.bareBoxes(since);
4427
+ this.make({ plan: ARCH_SCOPE, rev, kind: "archChanged", to: actor, text: archChangedText(plan, planId, a, lines, { bare: bare.map((b) => ({ id: b, label: a.nodes[b]?.label ?? b })) }), ...bare.length ? { bare } : {} });
4384
4428
  }
4385
4429
  /**
4386
4430
  * What you changed on the plan and on the architecture since this agent last looked, for the message that wakes it when a
@@ -4472,7 +4516,7 @@ var Calls = class extends EventEmitter3 {
4472
4516
  /**
4473
4517
  * You stopped a plan: an order for every agent at work on it (the ones that held the steps the stop put back, and
4474
4518
  * any agent seen working on it or asking you in its window), and a `stopped` call to each that a plugin listens for.
4475
- * @param {string} id @param {import('@dcursed/core/src/log.js').LogLine} line
4519
+ * @param {string} id @param {import('@diacode/core/src/log.js').LogLine} line
4476
4520
  */
4477
4521
  stopAll(id, line) {
4478
4522
  const plan = this.store.get(id).plan;
@@ -4607,7 +4651,82 @@ var Calls = class extends EventEmitter3 {
4607
4651
  const since = seen ?? from - 1;
4608
4652
  const changes = describeChanges(this.store.changesSince(id, since), since, { not: actor });
4609
4653
  const sync = this.store.changesSince(id, since).some((l) => l.actor === "you" && !l.proposed && (l.ops ?? []).some((o) => STRUCTURAL.has(o.op) || o.op === "plan.set" && (o.title !== void 0 || o.goal !== void 0)));
4610
- this.make({ plan: id, rev, kind: "changed", to: actor, text: changedText(plan, id, this.store.attentionFor(id, actor, since), changes, { sync }) });
4654
+ const bare = this.bareSteps(id, since);
4655
+ this.make({ plan: id, rev, kind: "changed", to: actor, text: changedText(plan, id, this.store.attentionFor(id, actor, since), changes, { sync, bare: bare.map((b) => ({ id: b, label: plan.nodes[b]?.label ?? b })) }), ...bare.length ? { bare } : {} });
4656
+ }
4657
+ /**
4658
+ * Steps you added by name only (no description, no files, no boxes): those you added since `since`, or with no `since`, every such
4659
+ * step of the plan. A step you filled in while the edit waited is not bare any more.
4660
+ * @param {string} id @param {number} [since]
4661
+ * @returns {string[]}
4662
+ */
4663
+ bareSteps(id, since) {
4664
+ const plan = this.store.get(id).plan;
4665
+ if (!plan) return [];
4666
+ const added = since === void 0 ? Object.keys(plan.nodes) : this.store.changesSince(id, since).filter((l) => l.actor === "you" && !l.proposed).flatMap((l) => (l.ops ?? []).filter((o) => o.op === "node.add").map((o) => (
4667
+ /** @type {string} */
4668
+ o.id
4669
+ )));
4670
+ return [...new Set(added)].filter((s) => {
4671
+ const n = plan.nodes[s];
4672
+ return n && n.kind !== "context" && !n.detail && !n.files?.length && !n.touches?.length && (n.status === void 0 || n.status === "not_started");
4673
+ });
4674
+ }
4675
+ /**
4676
+ * Boxes you added by name only (no description, technology or files) since `since`.
4677
+ * @param {number} since @returns {string[]}
4678
+ */
4679
+ bareBoxes(since) {
4680
+ const a = this.arch?.arch;
4681
+ if (!a) return [];
4682
+ const added = (this.arch?.since(since) ?? []).filter((l) => l.actor === "you" && !l.proposed).flatMap((l) => (l.ops ?? []).filter((o) => o.op === "box.add").map((o) => (
4683
+ /** @type {string} */
4684
+ o.id
4685
+ )));
4686
+ return [...new Set(added)].filter((b) => {
4687
+ const n = a.nodes[b];
4688
+ return n && n.kind !== "group" && !n.detail && !n.tech && !n.files?.length;
4689
+ });
4690
+ }
4691
+ /**
4692
+ * You asked your agent to look at something the plan does not cover or got wrong: files edited outside it (`drift`), steps whose
4693
+ * upstream changed (`review`), or a step that failed (`failure`). The agent is woken with what you pressed and what it is about.
4694
+ * Nobody to tell comes back as a call in the state `none`, which the editor says in words.
4695
+ * @param {string} id @param {{ kind: 'drift' | 'review' | 'failure', step?: string, steps?: string[] }} request
4696
+ * @returns {Call}
4697
+ */
4698
+ askAgent(id, { kind, step: step3, steps }) {
4699
+ const view = this.store.get(id);
4700
+ const plan = view.plan;
4701
+ if (!plan) throw new HttpError(409, `${id}.plan.json is not a valid plan yet`);
4702
+ let to;
4703
+ let text2;
4704
+ if (kind === "drift") {
4705
+ const drift = this.store.driftOf(id);
4706
+ if (!drift.length) throw new HttpError(409, "nothing is outside the plan");
4707
+ to = this.worker(id);
4708
+ text2 = driftText(plan, id, drift);
4709
+ } else if (kind === "failure") {
4710
+ const n = step3 ? plan.nodes[step3] : void 0;
4711
+ if (!step3 || !n) throw new HttpError(404, `there is no step ${step3 ?? ""} in ${id}`);
4712
+ if (n.status !== "failed") throw new HttpError(409, `${step3} has not failed`);
4713
+ const behind = Object.keys(view.derived?.atRisk ?? {}).filter((s) => (view.derived?.atRisk?.[s] ?? []).includes(step3));
4714
+ to = this.holder(id, step3) ?? this.worker(id);
4715
+ text2 = failureText(plan, id, step3, behind);
4716
+ } else {
4717
+ const waiting = (steps?.length ? steps : Object.keys(view.review ?? {})).filter((s) => plan.nodes[s]);
4718
+ if (!waiting.length) throw new HttpError(409, "nothing needs review");
4719
+ to = this.worker(id);
4720
+ text2 = reviewText(plan, id, waiting.map((s) => ({ id: s, because: view.review?.[s]?.because ?? [] })));
4721
+ }
4722
+ const call = (
4723
+ /** @type {Call} */
4724
+ this.make({ plan: id, rev: plan.rev, kind: "replan", ...kind === "failure" && step3 ? { step: step3 } : {}, ...to ? { to } : {}, text: text2 })
4725
+ );
4726
+ if (call.state === "queued" && to && !this.lastHeard.has(to) && ![...this.waiters].some((w) => w.actor === to) && !this.busy(to)) {
4727
+ this.settle(call, "none", "nothing is listening for the editor");
4728
+ }
4729
+ return { ...call };
4611
4730
  }
4612
4731
  /** The revision of a plan an agent was last shown, if it ever was. @param {string} actor @param {string} id */
4613
4732
  seen(actor, id) {
@@ -4641,7 +4760,7 @@ var Calls = class extends EventEmitter3 {
4641
4760
  if (this.calls.length > KEEP) this.calls.shift();
4642
4761
  if (call.state === "none") {
4643
4762
  this.emit("call", { ...call });
4644
- return;
4763
+ return call;
4645
4764
  }
4646
4765
  if (!this.offer(call)) {
4647
4766
  this.emit("call", { ...call });
@@ -4686,6 +4805,7 @@ var Calls = class extends EventEmitter3 {
4686
4805
  const plan = this.store.get(call.plan).plan;
4687
4806
  if (!plan) return false;
4688
4807
  if (call.kind === "started" || call.kind === "resumed") return plan.phase === "executing";
4808
+ if (call.kind === "replan") return plan.phase !== "done";
4689
4809
  if (call.kind === "planApproved") return plan.phase === "approved";
4690
4810
  if (call.kind === "stopped") return plan.phase === "approved" && call.to !== void 0 && this.stoppedFor(call.to) === call.plan;
4691
4811
  if (call.kind === "passed") {
@@ -4789,16 +4909,48 @@ var Calls = class extends EventEmitter3 {
4789
4909
  this.pending.clear();
4790
4910
  }
4791
4911
  };
4792
- function planApprovedText(plan, id, { archToo = false, hasArch = true } = {}) {
4912
+ var clipped = (s, max = 300) => s.length > max ? `${s.slice(0, max - 1)}\u2026` : s;
4913
+ function driftText(plan, id, drift) {
4914
+ return [
4915
+ `[DiaCode] The person asks whether the plan "${plan.title}" (${id}) should cover work that is outside it. These files were edited, and no step lists them:`,
4916
+ ...drift.slice(0, 20).map((d) => `- ${d.file} (edited ${d.count}\xD7 by ${d.by})`),
4917
+ "Read the plan with plan_read. Then answer with ONE of: (a) the matching change to the plan, proposed with plan_edit (propose: true and a plain reason): usually the file added to the step it belongs to (node.set with that step's whole files list plus this one), or a new step for work the plan does not have; (b) one sentence saying the plan needs no change (a scratch or generated file, say). Do not start a step, do not change the architecture, and stop when you have answered."
4918
+ ].join("\n");
4919
+ }
4920
+ function failureText(plan, id, step3, behind) {
4921
+ const n = plan.nodes[step3];
4922
+ return [
4923
+ `[DiaCode] The person asks you to re-plan from a failure. In the plan "${plan.title}" (${id}) the step ${step3}${n?.label ? ` ("${n.label}")` : ""} failed${n?.note ? `: ${clipped(n.note, 600)}` : "."}`,
4924
+ ...behind.length ? [`These wait behind it: ${behind.join(", ")}.`] : [],
4925
+ "Read the plan with plan_read. Then answer with ONE of: (a) the change the failure teaches, proposed with plan_edit (propose: true and a plain reason): typically a new step before it that removes the cause, the step reworded with what the failure showed or split, or a dependency that was never real removed; (b) one sentence saying no change is needed. Do not set a status: whether to try again is the person's call (Try again). Stop when you have answered."
4926
+ ].join("\n");
4927
+ }
4928
+ function reviewText(plan, id, steps) {
4929
+ return [
4930
+ `[DiaCode] The person asks you to review steps of the plan "${plan.title}" (${id}) that a change upstream of them may have made wrong:`,
4931
+ ...steps.slice(0, 20).map((s) => `- ${s.id}${plan.nodes[s.id]?.label ? ` ("${plan.nodes[s.id].label}")` : ""}${s.because.length ? `: ${clipped(s.because.join("; "), 240)}` : ""}`),
4932
+ "Read the plan with plan_read. For each step: if it needs a different label, detail or files, propose that with plan_edit (propose: true and a plain reason); if it is fine, say so in a sentence (and mark it reviewed with the review op). Do not start a step. Stop when you have answered."
4933
+ ].join("\n");
4934
+ }
4935
+ function planApprovedText(plan, id, { archToo = false, hasArch = true, bare = [] } = {}) {
4793
4936
  return [
4794
4937
  `[DiaCode] The person approved the plan "${plan.title}" (${id}) in the editor${archToo ? ", and with it the architecture you drew" : ""}. It is NOT started: do not start any step; they press Start when the architecture and the plan are final.`,
4795
4938
  hasArch ? 'Now check the architecture against the plan, once. arch_read it (they may have edited it). Every part the plan adds (a step that creates a service, page, store, queue or component) must be a box, marked planned: true while it does not exist yet; a part the plan removes is marked retiring: "' + id + '"; each step lists the boxes it changes as touches (plan_edit node.set). Then arch_edit whatever is missing or wrong: your changes arrive as proposals, so give each a plain reason.' : "There is no architecture yet. Draw one now with arch_draft: the system as the plan will make it, every part that does not exist yet marked planned: true.",
4939
+ ...bare.length ? [bareStepsWords(bare)] : [],
4796
4940
  "Then stop, and say in a sentence what you changed in the architecture (or that nothing needed to change). The person accepts or rejects each change, then presses Start; the Start is sent to you as another [DiaCode] message."
4797
4941
  ].join("\n");
4798
4942
  }
4943
+ function bareStepsWords(bare) {
4944
+ const list = bare.slice(0, 10).map((b) => `${b.id} ("${b.label}")`).join(", ");
4945
+ return `The person added ${bare.length === 1 ? "this step" : "these steps"} by name only, with no description, no files and no boxes: ${list}. For each, propose what is missing with plan_edit: node.set with detail (what done means, in a sentence or two), files (the paths it will touch) and touches (the ids of the architecture's boxes it changes), and \`propose: true\` with a plain reason, so it arrives as a card the person accepts. Read the steps around it and the architecture (arch_read) to say something specific. If you cannot tell what a step means, say what you need to know instead of guessing.`;
4946
+ }
4947
+ function bareBoxesWords(bare) {
4948
+ const list = bare.slice(0, 10).map((b) => `${b.id} ("${b.label}")`).join(", ");
4949
+ return `The person added ${bare.length === 1 ? "this box" : "these boxes"} by name only, with no description, technology or files: ${list}. For each, propose what is missing with arch_edit: box.set with detail (what it is for, in a sentence), tech and files (where its code is or will be), and the arrows to what it uses (arrow.add), with a plain reason: it arrives as a card the person accepts. If you cannot tell what a box is for, say what you need to know instead of guessing.`;
4950
+ }
4799
4951
  function startedText(plan, id, { archToo = false, again = false } = {}) {
4800
4952
  return [
4801
- `[DiaCode] The person pressed Start${again ? " again" : ""} on the plan "${plan.title}" (${id}) in the editor${archToo ? ", and approved the architecture you drew with it (your changes to the architecture are proposals from now on)" : ""}. Carry it out now with the dcursed tools, one step at a time:`,
4953
+ `[DiaCode] The person pressed Start${again ? " again" : ""} on the plan "${plan.title}" (${id}) in the editor${archToo ? ", and approved the architecture you drew with it (your changes to the architecture are proposals from now on)" : ""}. Carry it out now with the diacode tools, one step at a time:`,
4802
4954
  "step_start, do the work, then step_done saying what is true now. Read it with plan_read first, because the person may have changed it while reviewing.",
4803
4955
  "If a step is unclear, stop on it with step_wait and say what you need. If doing the work makes the plan and the architecture disagree, propose the matching change on the other side (plan_edit or arch_edit, with a reason) instead of letting them drift."
4804
4956
  ].join(" ");
@@ -4838,22 +4990,24 @@ function answeredText(plan, id, step3, answer) {
4838
4990
  return `[DiaCode] The person answered your question on step ${step3}${label ? ` ("${label}")` : ""} in plan ${id}: ${answer}
4839
4991
  Carry on with ${step3} using that answer.`;
4840
4992
  }
4841
- function changedText(plan, id, attention, changes, { sync = true } = {}) {
4993
+ function changedText(plan, id, attention, changes, { sync = true, bare = [] } = {}) {
4842
4994
  const clip2 = (s) => s.length > 400 ? `${s.slice(0, 399)}\u2026` : s;
4843
4995
  const waiting = plan.phase === "approved";
4844
4996
  return [
4845
4997
  `[DiaCode] While you were between turns, the person changed the plan "${plan.title}" (${id}) in the editor.`,
4846
4998
  ...attention.length ? ["HEADS UP, about your steps:", ...attention.map((a) => `- ${clip2(a)}`)] : [],
4847
4999
  ...changes.length ? ["What changed:", ...changes.slice(-20).map((c) => `- ${clip2(c)}`)] : [],
5000
+ ...bare.length ? [bareStepsWords(bare)] : [],
4848
5001
  sync ? "Read the plan with plan_read. Then make the architecture agree: if what they changed adds, removes or reconnects a part of the system (a box, an arrow, a service), propose the matching change with arch_edit, giving a plain reason; if the architecture needs nothing, say so." : "Read the plan with plan_read. If they settled a proposal of yours, adjust what depended on it.",
4849
5002
  waiting ? "The plan is not started: do not start any step, and stop when you have said what you changed or that nothing needed to." : "Then carry on with what is left for you. A finished step is the person's to reopen: if one of those changed, say whether it needs reopening. If nothing is left for you to do, say so and stop."
4850
5003
  ].join("\n");
4851
5004
  }
4852
- function archChangedText(plan, id, arch2, lines) {
5005
+ function archChangedText(plan, id, arch2, lines, { bare = [] } = {}) {
4853
5006
  const clip2 = (s) => s.length > 400 ? `${s.slice(0, 399)}\u2026` : s;
4854
5007
  return [
4855
5008
  `[DiaCode] The person changed the architecture ("${arch2.title}") in the editor:`,
4856
5009
  ...lines.slice(-20).map((l) => `- ${clip2(l)}`),
5010
+ ...bare.length ? [bareBoxesWords(bare)] : [],
4857
5011
  `Read it with arch_read, then make the plan "${plan.title}" (${id}) agree: if a step no longer matches (a box was removed that a step builds or changes, a part was added that no step builds, a step's files moved), propose the matching change with plan_edit, giving a plain reason. If the plan needs nothing, say so.`,
4858
5012
  plan.phase === "approved" ? "The plan is not started: do not start any step, and stop when you have said what you changed or that nothing needed to." : "Then carry on with what is left for you."
4859
5013
  ].join("\n");
@@ -5002,7 +5156,7 @@ var OP_EXAMPLES = {
5002
5156
  "edge.remove": '{"op":"edge.remove","from":"tests","to":"lint"}',
5003
5157
  "edge.rewire": '{"op":"edge.rewire","from":"a","to":"b","newTo":"c"} (or newFrom)',
5004
5158
  "edge.reverse": '{"op":"edge.reverse","from":"a","to":"b"}',
5005
- "edge.set": '{"op":"edge.set","from":"a","to":"b","label":"parsed rows"} (or "kind": needs, after, approve, ask or input)',
5159
+ "edge.set": '{"op":"edge.set","from":"a","to":"b","label":"parsed rows"} (or "kind": needs, after, approve, ask or input; or "options": ["one vote each", "several"] for the answers an ask checkpoint offers)',
5006
5160
  "group.rename": '{"op":"group.rename","from":"old name","to":"new name"}',
5007
5161
  "plan.set": '{"op":"plan.set","goal":"what the plan is for"} (or title)',
5008
5162
  review: '{"op":"review","ids":["tests"]}'
@@ -5030,6 +5184,13 @@ var FINISHERS = [
5030
5184
  { name: "step_failed", status: "failed", release: false, description: "Report that a step failed, and why. The person is asked to look at what depends on it." },
5031
5185
  { name: "step_wait", status: "waiting", release: false, description: "Stop on a step because you need the person (a decision, a missing fact). Say what you need, then end your turn: the answer is sent to you." }
5032
5186
  ];
5187
+ var OPTIONS = {
5188
+ type: "array",
5189
+ minItems: 1,
5190
+ maxItems: OPTIONS_MAX,
5191
+ items: { type: "string", maxLength: OPTION_MAX },
5192
+ description: `the answers you offer, each a few words (at most ${OPTIONS_MAX}): they are shown as buttons, so keep the question itself to ONE question that they answer`
5193
+ };
5033
5194
  var KIND2 = {
5034
5195
  type: "string",
5035
5196
  enum: ["needs", "after", "approve", "ask", "input"],
@@ -5086,8 +5247,8 @@ WARNING: the plan file has an edit that breaks a rule (${view.error}). Writes wa
5086
5247
  touches: { type: "array", items: { type: "string" }, description: "the ids of the architecture's boxes this step changes (see arch_read), besides the ones its files fall in" },
5087
5248
  after: {
5088
5249
  type: "array",
5089
- description: 'the steps this one depends on: an id, or { id, kind, label } for an arrow that is more than "needs" (such as a checkpoint the person asked for)',
5090
- items: { anyOf: [{ type: "string" }, { type: "object", required: ["id"], properties: { id: { type: "string" }, kind: KIND2, label: { type: "string" } } }] }
5250
+ description: 'the steps this one depends on: an id, or { id, kind, label, options } for an arrow that is more than "needs" (such as a checkpoint the person asked for; an ask checkpoint may list the answers it will offer)',
5251
+ items: { anyOf: [{ type: "string" }, { type: "object", required: ["id"], properties: { id: { type: "string" }, kind: KIND2, label: { type: "string" }, options: OPTIONS } }] }
5091
5252
  },
5092
5253
  kind: { type: "string", enum: ["task", "context"], description: "context: something that already exists, shown for reference" }
5093
5254
  }
@@ -5123,7 +5284,7 @@ ${next}`, data: { plan: made.id, rev: view.rev } };
5123
5284
  name: "plan_edit",
5124
5285
  description: [
5125
5286
  "Change a plan with a batch of operations, all or nothing. Operations:",
5126
- "node.add{label,id?,kind?,detail?,group?,files?,touches?,after?[]} \xB7 node.set{id,label?,kind?,detail?,group?,files?,touches?} \xB7 node.remove{id} \xB7 edge.add{from,to,label?,kind?} \xB7 edge.remove{from,to} \xB7 edge.rewire{from,to,newFrom?,newTo?} \xB7 edge.reverse{from,to} \xB7 edge.set{from,to,label?,kind?} \xB7 group.rename{from,to} \xB7 plan.set{title?,goal?} \xB7 review{ids[]} (these steps were looked at and need no change).",
5287
+ "node.add{label,id?,kind?,detail?,group?,files?,touches?,after?[]} \xB7 node.set{id,label?,kind?,detail?,group?,files?,touches?} \xB7 node.remove{id} \xB7 edge.add{from,to,label?,kind?,options?} \xB7 edge.remove{from,to} \xB7 edge.rewire{from,to,newFrom?,newTo?} \xB7 edge.reverse{from,to} \xB7 edge.set{from,to,label?,kind?,options?} \xB7 group.rename{from,to} \xB7 plan.set{title?,goal?} \xB7 review{ids[]} (these steps were looked at and need no change).",
5127
5288
  "An arrow from\u2192to means `to` depends on `from`. An arrow's kind: needs (the default), after (order only), or a checkpoint where the person comes in before `to` starts: approve, ask, input. Use the step_* tools for status. While the plan is being executed your structural changes become a proposal for the person to accept; pass propose:true to do that while planning too, which is the right thing for a change the person has not asked for."
5128
5289
  ].join("\n"),
5129
5290
  inputSchema: {
@@ -5168,17 +5329,18 @@ You have it, and it is in progress.` };
5168
5329
  },
5169
5330
  {
5170
5331
  name: "step_ask",
5171
- description: 'A step behind an "ask" checkpoint waits for you to ask the person something before it starts. Ask it here, then end your turn: the answer is sent to you, and the step can start.',
5172
- inputSchema: { type: "object", required: ["id", "question"], properties: { plan: PLAN, id: STEP2, question: { type: "string", description: "what you need to know before this step, in a sentence or two" } } },
5332
+ description: 'A step behind an "ask" checkpoint waits for you to ask the person something before it starts. Ask it here, then end your turn: the answer is sent to you, and the step can start. Ask ONE question per call (several questions are several asks, one after the other), and when it has a few answers, give them as `options`: the person presses one, or writes their own.',
5333
+ inputSchema: { type: "object", required: ["id", "question"], properties: { plan: PLAN, id: STEP2, question: { type: "string", description: "the one thing you need to know before this step, in a sentence or two" }, options: OPTIONS } },
5173
5334
  async run(args2, s, ctx) {
5174
5335
  const planId = planOf(ctx, args2.plan);
5175
5336
  const id = str(args2.id, "id");
5176
5337
  const question = str(args2.question, "question");
5338
+ const options = args2.options === void 0 ? void 0 : args2.options;
5177
5339
  const { plan } = viewOf(ctx, planId);
5178
5340
  if (!plan.nodes[id]) throw new HttpError(404, `there is no step ${id} in ${planId}`);
5179
5341
  const asks = plan.edges.filter((e) => e.to === id && e.kind === "ask" && !e.passed);
5180
5342
  if (!asks.length) return { error: true, text: `${id} has no "ask" checkpoint waiting. If you need the person anyway, use step_wait on the step you are on.` };
5181
- const { reply: _reply, ...outcome } = await send(ctx, s, planId, asks.map((e) => ({ op: "gate.ask", from: e.from, to: id, question })), { reason: `asked before ${id}` });
5343
+ const { reply: _reply, ...outcome } = await send(ctx, s, planId, asks.map((e) => ({ op: "gate.ask", from: e.from, to: id, question, ...options !== void 0 ? { options } : {} })), { reason: `asked before ${id}` });
5182
5344
  if (outcome.error) return outcome;
5183
5345
  return { ...outcome, text: `${outcome.text}
5184
5346
 
@@ -5460,7 +5622,7 @@ function stepsToOps(steps) {
5460
5622
  if (typeof a === "string") return { id: a };
5461
5623
  if (a && typeof a === "object" && typeof /** @type {any} */
5462
5624
  a.id === "string") return (
5463
- /** @type {{ id: string, kind?: unknown, label?: unknown }} */
5625
+ /** @type {{ id: string, kind?: unknown, label?: unknown, options?: unknown }} */
5464
5626
  a
5465
5627
  );
5466
5628
  throw new HttpError(400, 'each "after" entry is a step id, or { id, kind, label }');
@@ -5477,7 +5639,8 @@ function stepsToOps(steps) {
5477
5639
  place(a.id);
5478
5640
  const kind2 = typeof a.kind === "string" && a.kind !== "needs" ? a.kind : void 0;
5479
5641
  const label2 = typeof a.label === "string" && a.label.trim() ? a.label.trim() : void 0;
5480
- if (kind2 || label2) kinds.push({ op: "edge.set", from: a.id, to: id, ...kind2 ? { kind: kind2 } : {}, ...label2 ? { label: label2 } : {} });
5642
+ const options = Array.isArray(a.options) && a.options.length ? a.options : void 0;
5643
+ if (kind2 || label2 || options) kinds.push({ op: "edge.set", from: a.id, to: id, ...kind2 ? { kind: kind2 } : {}, ...label2 ? { label: label2 } : {}, ...options ? { options } : {} });
5481
5644
  }
5482
5645
  visiting.delete(id);
5483
5646
  placed.add(id);
@@ -5586,7 +5749,7 @@ ${changes.map((c) => `- ${clip(c)}`).join("\n")}`;
5586
5749
  ...ok2({
5587
5750
  protocolVersion: VERSIONS.includes(asked) ? asked : VERSIONS[0],
5588
5751
  capabilities: { tools: { listChanged: false } },
5589
- serverInfo: { name: "dcursed", title: "DiaCode plan server", version },
5752
+ serverInfo: { name: "diacode", title: "DiaCode plan server", version },
5590
5753
  instructions: GUIDE
5591
5754
  })
5592
5755
  };
@@ -5662,7 +5825,7 @@ var OPS_HELP = [
5662
5825
  'edge.add {"op":"edge.add","from":"a","to":"b"} (b depends on a)',
5663
5826
  'edge.remove {"op":"edge.remove","from":"a","to":"b"}'
5664
5827
  ].map((l) => ` ${l}`).join("\n");
5665
- var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", ".dcursed", ".opencode", "dist", "build", "coverage", ".next", ".venv", "__pycache__"]);
5828
+ var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", ".diacode", ".opencode", "dist", "build", "coverage", ".next", ".venv", "__pycache__"]);
5666
5829
  var LIMITS = { entries: 120, depth: 4, file: 3500, total: 14e3 };
5667
5830
  var LOCKFILE = /(^|\/)(package-lock\.json|yarn\.lock|pnpm-lock\.yaml|.*\.min\.js|.*\.map|.*\.svg|.*\.png|.*\.jpe?g|.*\.ico)$/;
5668
5831
  var PRIVATE = /(^|\/)(\.[^/]+|id_(rsa|dsa|ecdsa|ed25519)(\.pub)?|[^/]*\.(pem|key|p12|pfx|jks|keystore|tfstate)|credentials[^/]*\.json)(\/|$)/i;
@@ -5854,7 +6017,7 @@ function parseFindings(text2) {
5854
6017
  }
5855
6018
  throw new Error("the reply was not the JSON that was asked for");
5856
6019
  }
5857
- var READ_ONLY = { mcp: { dcursed: { enabled: false } }, permission: { edit: "deny", bash: "ask", webfetch: "deny", external_directory: "deny" } };
6020
+ var READ_ONLY = { mcp: { diacode: { enabled: false } }, permission: { edit: "deny", bash: "ask", webfetch: "deny", external_directory: "deny" } };
5858
6021
  var ANSI = /\u001b\[[0-9;]*m/g;
5859
6022
  function openCodeRunner(options) {
5860
6023
  return async (prompt) => {
@@ -5869,6 +6032,14 @@ Your last attempt tried "${r.refused}", which is refused here and ended the sess
5869
6032
  }
5870
6033
  };
5871
6034
  }
6035
+ function plainFailure(raw) {
6036
+ const t = raw.replace(ANSI, "");
6037
+ if (/api[ _-]?key|expired|unauthori[sz]ed|\b40[13]\b|invalid[^.]{0,30}(key|token)|credential|not configured|not (logged|signed) in|(sign|log)[ -]?in|authenticat/i.test(t)) return "OpenCode is not signed in (its key is missing or has expired, or no provider is set up). Run `opencode auth login` in a terminal, then ask again.";
6038
+ if (/could not run|ENOENT|installed/i.test(t)) return "OpenCode is not installed, or is not on the PATH.";
6039
+ if (/did not answer within/i.test(t)) return "OpenCode did not answer in time. A rate-limited model keeps trying in silence: ask again in a minute.";
6040
+ if (/rate.?limit|\b429\b|quota|overloaded/i.test(t)) return "OpenCode's model is busy or rate-limited right now. Ask again in a minute.";
6041
+ return "OpenCode could not answer. Run `opencode run hello` in a terminal to see why.";
6042
+ }
5872
6043
  function once({ root: root2, model, agent = "plan", bin = "opencode", timeoutMs = 24e4 }, prompt) {
5873
6044
  return new Promise((resolve7, reject) => {
5874
6045
  const args2 = ["run", "--dir", root2, "--format", "json", "--agent", agent, ...model ? ["--model", model] : [], prompt];
@@ -5878,7 +6049,7 @@ function once({ root: root2, model, agent = "plan", bin = "opencode", timeoutMs
5878
6049
  let err = "";
5879
6050
  const timer = setTimeout(() => {
5880
6051
  child.kill("SIGKILL");
5881
- reject(new Error(`OpenCode did not answer within ${Math.round(timeoutMs / 1e3)} seconds (a rate-limited model retries in silence)`));
6052
+ reject(new Error(plainFailure(`OpenCode did not answer within ${Math.round(timeoutMs / 1e3)} seconds`)));
5882
6053
  }, timeoutMs);
5883
6054
  child.stdout.on("data", (d) => {
5884
6055
  out += d;
@@ -5888,10 +6059,10 @@ function once({ root: root2, model, agent = "plan", bin = "opencode", timeoutMs
5888
6059
  });
5889
6060
  child.on("error", (e) => {
5890
6061
  clearTimeout(timer);
5891
- reject(new Error(
6062
+ reject(new Error(plainFailure(
5892
6063
  /** @type {any} */
5893
6064
  e.code === "ENOENT" ? `could not run "${bin}": is OpenCode installed?` : e.message
5894
- ));
6065
+ )));
5895
6066
  });
5896
6067
  child.on("close", () => {
5897
6068
  clearTimeout(timer);
@@ -5899,14 +6070,14 @@ function once({ root: root2, model, agent = "plan", bin = "opencode", timeoutMs
5899
6070
  for (const line of out.split("\n")) {
5900
6071
  try {
5901
6072
  const e = JSON.parse(line);
5902
- if (e.type === "error") return reject(new Error(String(e.error?.data?.message ?? e.error?.name ?? "OpenCode reported an error")));
6073
+ if (e.type === "error") return reject(new Error(plainFailure(String(e.error?.data?.message ?? e.error?.name ?? "OpenCode reported an error"))));
5903
6074
  if (e.type === "text" && typeof e.part?.text === "string") texts.push(e.part.text);
5904
6075
  } catch {
5905
6076
  }
5906
6077
  }
5907
6078
  if (texts.length) return resolve7({ text: texts.join("\n") });
5908
6079
  const refused2 = /permission requested: (.+?); auto-rejecting/.exec(err.replace(ANSI, ""));
5909
- return refused2 ? resolve7({ refused: refused2[1] }) : reject(new Error(err.replace(ANSI, "").trim().split("\n").pop() || "OpenCode said nothing"));
6080
+ return refused2 ? resolve7({ refused: refused2[1] }) : reject(new Error(plainFailure(err.replace(ANSI, "").trim().split("\n").pop() || "OpenCode said nothing")));
5910
6081
  });
5911
6082
  });
5912
6083
  }
@@ -6322,7 +6493,7 @@ var Presence = class extends EventEmitter5 {
6322
6493
  * The steps in progress whose owner has stopped. An owner we know nothing about is not flagged:
6323
6494
  * with no plugin there is nothing to be silent. Nor is one asking the person: it has not stopped, it is
6324
6495
  * waiting on them, and the editor says that instead.
6325
- * @param {import('@dcursed/core/src/types.js').Plan | null | undefined} plan
6496
+ * @param {import('@diacode/core/src/types.js').Plan | null | undefined} plan
6326
6497
  * @returns {Record<string, Stalled>}
6327
6498
  */
6328
6499
  stalled(plan) {
@@ -6346,7 +6517,7 @@ var Presence = class extends EventEmitter5 {
6346
6517
  * What a plan's viewers should see now, and a key that changes only when it is news: `seen`
6347
6518
  * moves with every heartbeat, so only a state, a plan or a stall changes the key. Each listener
6348
6519
  * keeps the last key it was sent; two editors on one plan must both hear every change.
6349
- * @param {string | undefined} planId @param {import('@dcursed/core/src/types.js').Plan | null | undefined} plan
6520
+ * @param {string | undefined} planId @param {import('@diacode/core/src/types.js').Plan | null | undefined} plan
6350
6521
  * @param {any[]} [drift] files edited that no step lists (the store's; shown with who is working because it is just as live)
6351
6522
  * @returns {{ view: { presence: Agent[], stalled: Record<string, Stalled>, drift: any[], reads: Read[] }, key: string }}
6352
6523
  */
@@ -6394,7 +6565,7 @@ var TYPES = (
6394
6565
  );
6395
6566
  function findEditor() {
6396
6567
  const candidates = [
6397
- process.env.DCURSED_EDITOR,
6568
+ process.env.DIACODE_EDITOR,
6398
6569
  fileURLToPath(new URL("../editor", import.meta.url)),
6399
6570
  fileURLToPath(new URL("../../../dist", import.meta.url))
6400
6571
  ];
@@ -6419,7 +6590,7 @@ async function serveEditor(root2, pathname) {
6419
6590
 
6420
6591
  // packages/server/src/agents.js
6421
6592
  var SILENT_MS = 15 * 6e4;
6422
- var OURS = /(^|[^a-z])(plan_list|plan_read|plan_create|plan_edit|step_start|step_done|step_failed|step_wait|step_ask)$|^dcursed_/;
6593
+ var OURS = /(^|[^a-z])(plan_list|plan_read|plan_create|plan_edit|step_start|step_done|step_failed|step_wait|step_ask)$|^diacode_/;
6423
6594
  var Agents = class {
6424
6595
  /**
6425
6596
  * @param {{ store: import('./store.js').PlanStore, presence: import('./presence.js').Presence, now?: () => number, stage?: () => string }} options
@@ -6719,7 +6890,7 @@ var MESSAGE_MAX = 300;
6719
6890
  var EventRing = class {
6720
6891
  /**
6721
6892
  * @param {number} [max] how many are kept
6722
- * @param {{ now?: () => string, log?: (line: string) => void }} [options] `log` gets each one as it happens (DCURSED_DEBUG)
6893
+ * @param {{ now?: () => string, log?: (line: string) => void }} [options] `log` gets each one as it happens (DIACODE_DEBUG)
6723
6894
  */
6724
6895
  constructor(max = 100, { now = () => (/* @__PURE__ */ new Date()).toISOString(), log } = {}) {
6725
6896
  this.max = max;
@@ -6732,7 +6903,7 @@ var EventRing = class {
6732
6903
  const event = { at: this.now(), kind, message: message.replace(/\s+/g, " ").trim().slice(0, MESSAGE_MAX) };
6733
6904
  this.events.push(event);
6734
6905
  if (this.events.length > this.max) this.events.shift();
6735
- this.log?.(`[dcursed] ${kind}: ${event.message}`);
6906
+ this.log?.(`[diacode] ${kind}: ${event.message}`);
6736
6907
  }
6737
6908
  /** Oldest first. @returns {ServerEvent[]} */
6738
6909
  list() {
@@ -6743,6 +6914,50 @@ var EventRing = class {
6743
6914
  // packages/server/src/permissions.js
6744
6915
  import { EventEmitter as EventEmitter6 } from "node:events";
6745
6916
  import { randomBytes } from "node:crypto";
6917
+ function runsAnything(r) {
6918
+ if (r.toolName !== "Bash") return false;
6919
+ const c = (r.ruleContent ?? "").trim();
6920
+ if (!c || /^[*:\s]+$/.test(c)) return true;
6921
+ return /^(sudo|su|doas|eval|exec|xargs|env|ssh|nohup|watch|time|command)(\s|:|$)/.test(c) || /^(node|nodejs|deno|bun|python3?|ruby|perl|php|lua|bash|sh|zsh|fish|osascript|npx|pnpm dlx|yarn dlx|bunx|uvx)\s+(-e|-c|-r|-p|--eval|--print|--command|-i|exec|run|dlx|-x)\b/.test(c) || /^(npx|bunx|uvx|pnpx)(\s|:|$)/.test(c);
6922
+ }
6923
+ function alwaysFrom(suggestions) {
6924
+ if (!Array.isArray(suggestions)) return void 0;
6925
+ for (const s of suggestions) {
6926
+ if (!s || typeof s !== "object") continue;
6927
+ if (s.type === "setMode" && s.mode === "acceptEdits") return { label: "file edits", update: { type: "setMode", mode: "acceptEdits", destination: "session" } };
6928
+ if (s.type !== "addRules" || s.behavior !== "allow" || !Array.isArray(s.rules) || !s.rules.length || s.rules.length > 8) continue;
6929
+ if (s.rules.some((r) => r && typeof r.toolName === "string" && runsAnything({ toolName: r.toolName, ruleContent: typeof r.ruleContent === "string" ? r.ruleContent : void 0 }))) continue;
6930
+ if (s.rules.some((r) => r && r.toolName === "Bash" && typeof r.ruleContent === "string" && !/(:|\s)\*$/.test(r.ruleContent))) continue;
6931
+ const rules = [];
6932
+ for (const r of s.rules) {
6933
+ if (!r || typeof r.toolName !== "string" || !r.toolName || r.toolName.length > 200) break;
6934
+ if (r.ruleContent !== void 0 && (typeof r.ruleContent !== "string" || r.ruleContent.length > 500)) break;
6935
+ rules.push({ toolName: r.toolName, ...r.ruleContent !== void 0 ? { ruleContent: r.ruleContent } : {} });
6936
+ }
6937
+ if (rules.length !== s.rules.length) continue;
6938
+ const clip2 = (t) => {
6939
+ const one = t.replace(/\s+/g, " ").trim();
6940
+ return one.length > 50 ? `${one.slice(0, 49)}\u2026` : one;
6941
+ };
6942
+ const where = (r) => {
6943
+ const verb = { Read: "reading anything", Edit: "editing anything", Write: "writing anything", MultiEdit: "editing anything", Glob: "listing anything", Grep: "searching anything" }[
6944
+ /** @type {'Read'} */
6945
+ r.toolName
6946
+ ];
6947
+ const path = r.ruleContent?.match(/^(\/\/?[^*]*?)\/?\*\*$/)?.[1];
6948
+ return verb && path ? `${verb} under ${clip2(path.replace(/^\/\//, "/"))}` : void 0;
6949
+ };
6950
+ const words = [...new Set(rules.map((r) => where(r) ?? (r.toolName === "Bash" && r.ruleContent ? `${clip2(r.ruleContent.replace(/(:|\s)\*$/, ""))} commands` : r.ruleContent ? `${r.toolName}(${clip2(r.ruleContent)})` : /^mcp__/.test(r.toolName) ? `${r.toolName.replace(/^mcp__/, "").replace(/__/g, ": ")}` : `${r.toolName} calls`)))];
6951
+ return { label: words.join(", ").slice(0, 140), update: { type: "addRules", rules, behavior: "allow", destination: "session" } };
6952
+ }
6953
+ return void 0;
6954
+ }
6955
+ var FULL_MAX = 2e4;
6956
+ function wholeCommand(tool, input2) {
6957
+ const c = typeof input2.command === "string" ? input2.command : "";
6958
+ if (!c || c.length <= 300 && !/\n/.test(c)) return {};
6959
+ return c.length > FULL_MAX ? { full: c.slice(0, FULL_MAX), partial: true } : { full: c };
6960
+ }
6746
6961
  function describeRequest(tool, input2) {
6747
6962
  const clip2 = (s) => {
6748
6963
  const t = String(s ?? "").replace(/\s+/g, " ").trim();
@@ -6764,10 +6979,10 @@ var Permissions = class extends EventEmitter6 {
6764
6979
  /**
6765
6980
  * An agent asks. Resolves with your decision, or with nothing when it is answered elsewhere, `holdMs` passes, or the
6766
6981
  * request is cancelled (the hook went away). A newer prompt from the same session replaces an older one.
6767
- * @param {{ actor: string, session?: string, tool: string, input: Record<string, any>, holdMs: number }} ask
6982
+ * @param {{ actor: string, session?: string, tool: string, input: Record<string, any>, holdMs: number, suggestions?: unknown }} ask
6768
6983
  * @returns {{ permission: Permission, result: Promise<Decision | null>, cancel: () => void }}
6769
6984
  */
6770
- ask({ actor, session, tool, input: input2, holdMs }) {
6985
+ ask({ actor, session, tool, input: input2, holdMs, suggestions }) {
6771
6986
  this.heard(actor, session);
6772
6987
  const id = randomBytes(9).toString("base64url");
6773
6988
  let done = () => {
@@ -6776,14 +6991,15 @@ var Permissions = class extends EventEmitter6 {
6776
6991
  done = resolve7;
6777
6992
  });
6778
6993
  let timer;
6779
- const permission = { id, actor, ...session ? { session } : {}, tool, what: describeRequest(tool, input2), at: new Date(this.now()).toISOString() };
6994
+ const always = alwaysFrom(suggestions);
6995
+ const permission = { id, actor, ...session ? { session } : {}, tool, what: describeRequest(tool, input2), ...wholeCommand(tool, input2), at: new Date(this.now()).toISOString(), ...always ? { always: { label: always.label } } : {} };
6780
6996
  const settle = (d) => {
6781
6997
  clearTimeout(timer);
6782
6998
  if (!this.pending.delete(id)) return;
6783
6999
  done(d);
6784
7000
  this.emit("change", { id, settled: d?.behavior ?? "released" });
6785
7001
  };
6786
- this.pending.set(id, { ...permission, settle });
7002
+ this.pending.set(id, { ...permission, settle, ...always ? { offer: always } : {} });
6787
7003
  timer = setTimeout(() => settle(null), holdMs);
6788
7004
  timer.unref?.();
6789
7005
  this.emit("change", { id, asked: true });
@@ -6791,16 +7007,20 @@ var Permissions = class extends EventEmitter6 {
6791
7007
  }
6792
7008
  /** The prompts waiting, oldest first, for one agent or all. @param {string} [actor] @returns {Permission[]} */
6793
7009
  list(actor) {
6794
- return [...this.pending.values()].filter((p) => !actor || p.actor === actor).map(({ settle: _s, ...p }) => p);
7010
+ return [...this.pending.values()].filter((p) => !actor || p.actor === actor).map(({ settle: _s, offer: _o, ...p }) => p);
6795
7011
  }
6796
7012
  /**
6797
7013
  * Your answer. @param {string} id @param {'allow' | 'deny'} decision @param {string} [reason] for a deny: the agent is told it
6798
- * @returns {boolean} whether it was still waiting
7014
+ * @param {boolean} [always] for an allow: and do not ask again for what Claude Code offered (this session only)
7015
+ * @returns {boolean | 'no-always' | 'too-long'} whether it was still waiting; `no-always`: it was, but offered no such choice; `too-long`: an Allow
7016
+ * for a command too long to have been shown whole (nothing was answered in either case)
6799
7017
  */
6800
- decide(id, decision, reason) {
7018
+ decide(id, decision, reason, always = false) {
6801
7019
  const p = this.pending.get(id);
6802
7020
  if (!p) return false;
6803
- p.settle(decision === "allow" ? { behavior: "allow" } : { behavior: "deny", message: reason?.trim() ? `The person denied this in the DiaCode editor: ${reason.trim().slice(0, 500)}` : "The person denied this in the DiaCode editor." });
7021
+ if (decision === "allow" && p.partial) return "too-long";
7022
+ if (always && (decision !== "allow" || !p.offer)) return "no-always";
7023
+ p.settle(decision === "allow" ? { behavior: "allow", ...always && p.offer ? { updatedPermissions: [p.offer.update] } : {} } : { behavior: "deny", message: reason?.trim() ? `The person denied this in the DiaCode editor: ${reason.trim().slice(0, 500)}` : "The person denied this in the DiaCode editor." });
6804
7024
  return true;
6805
7025
  }
6806
7026
  /**
@@ -6831,11 +7051,12 @@ var CLOSE_GRACE_MS = 1e3;
6831
7051
  var AGENT_EVENTS = /* @__PURE__ */ new Set(["session-start", "prompt", "tool-after", "turn-end", "asking", "error", "session-end"]);
6832
7052
  var HOLD = { plugin: { default: 5e4, max: 12e4 }, hook: { default: 6e5, max: 864e5 } };
6833
7053
  var REPORT_MS = 3e4;
6834
- function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", allowedOrigins = [], now, reconciler: rc = {}, presence: presenceOptions, editor = findEditor(), debug = Boolean(process.env.DCURSED_DEBUG), calls: callOptions = {} }) {
7054
+ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", allowedOrigins = [], now, reconciler: rc = {}, presence: presenceOptions, editor = findEditor(), debug = Boolean(process.env.DIACODE_DEBUG), calls: callOptions = {} }) {
6835
7055
  const startedAt = Date.now();
6836
7056
  const ring = new EventRing(100, { log: debug ? (line) => console.error(line) : void 0 });
6837
7057
  const store = new PlanStore(root2, { now });
6838
7058
  const archStore = new ArchStore(root2, { now });
7059
+ const opencodeReplans = rc.enabled ?? Boolean(rc.run || rc.auto || rc.model || rc.bin);
6839
7060
  const reconciler = new Reconciler(store, { run: rc.run ?? openCodeRunner({ root: root2, model: rc.model, bin: rc.bin }) });
6840
7061
  const presence = new Presence(presenceOptions);
6841
7062
  const repoFiles = new RepoFiles(root2);
@@ -6868,7 +7089,7 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
6868
7089
  return agents2.map((a) => {
6869
7090
  const b = a.state === "gone" && on.has(a.actor) ? { ...a, state: "idle" } : a;
6870
7091
  const p = permissions.list(a.actor)[0];
6871
- return p ? { ...b, state: "asking", detail: `wants to ${p.what}`, permission: { id: p.id, what: p.what, tool: p.tool } } : b;
7092
+ return p ? { ...b, state: "asking", detail: `wants to ${p.what}`, permission: { id: p.id, what: p.what, tool: p.tool, ...p.full ? { full: p.full } : {}, ...p.partial ? { partial: true } : {}, ...p.always ? { always: p.always } : {} } } : b;
6872
7093
  });
6873
7094
  };
6874
7095
  const mcp = createMcp({ store, arch: archStore, presence, stopped: (actor) => calls.stoppedFor(actor), version: VERSION });
@@ -6890,7 +7111,7 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
6890
7111
  (phase === "done" ? archStore.proposeLive(e.id) : archStore.proposeDrop(e.id)).catch((err) => ring.add("error", `architecture: the proposal for plan ${e.id} being ${phase}: ${err?.message ?? err}`));
6891
7112
  });
6892
7113
  const pending = /* @__PURE__ */ new Map();
6893
- if (rc.auto) {
7114
+ if (rc.auto && opencodeReplans) {
6894
7115
  store.on("change", (e) => {
6895
7116
  const failed = e.line?.actor !== "opencode:reconciler" && (e.line?.ops ?? []).find((o) => o.op === "status.set" && o.status === "failed");
6896
7117
  if (failed) {
@@ -6957,7 +7178,7 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
6957
7178
  }
6958
7179
  const url = new URL(req.url ?? "/", "http://localhost");
6959
7180
  const parts = url.pathname.split("/").filter(Boolean).map(decodeURIComponent);
6960
- if (req.method === "GET" && url.pathname === "/api/health") return send2(res, 200, { ok: true, root: root2, version: VERSION, api: API_VERSION, schemas: [SCHEMA, "dcursed.plan/0", arch_exports.SCHEMA] });
7181
+ if (req.method === "GET" && url.pathname === "/api/health") return send2(res, 200, { ok: true, root: root2, version: VERSION, api: API_VERSION, schemas: [SCHEMA, "diacode.plan/0", arch_exports.SCHEMA], replanner: opencodeReplans ? "opencode" : "agent" });
6961
7182
  if (req.method === "GET" && url.pathname === "/api/flow") {
6962
7183
  const f = flowNow({ store, arch: archStore, presence });
6963
7184
  const p2 = (
@@ -7019,7 +7240,7 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
7019
7240
  }
7020
7241
  if (parts[0] === "api" && parts[1] === "agent" && parts[2] === "events" && parts.length === 3 && req.method === "POST") {
7021
7242
  const who = whoOf(req);
7022
- if (who.actor === "you") throw new HttpError(400, "agent events are for a harness: send x-dcursed-agent: <harness>:<agent>");
7243
+ if (who.actor === "you") throw new HttpError(400, "agent events are for a harness: send x-diacode-agent: <harness>:<agent>");
7023
7244
  const ev = (
7024
7245
  /** @type {any} */
7025
7246
  await body(req)
@@ -7029,7 +7250,7 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
7029
7250
  }
7030
7251
  if (parts[0] === "api" && parts[1] === "agent" && parts[2] === "wait" && parts.length === 3 && req.method === "POST") {
7031
7252
  const who = whoOf(req);
7032
- if (who.actor === "you") throw new HttpError(400, "waiting for calls is for a harness plugin: send x-dcursed-agent: <harness>:<agent>");
7253
+ if (who.actor === "you") throw new HttpError(400, "waiting for calls is for a harness plugin: send x-diacode-agent: <harness>:<agent>");
7033
7254
  const { plans } = (
7034
7255
  /** @type {{ plans?: unknown }} */
7035
7256
  await body(req)
@@ -7047,12 +7268,14 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
7047
7268
  if (parts.length === 2 && req.method === "GET") return send2(res, 200, { permissions: permissions.list() });
7048
7269
  if (parts.length === 3 && req.method === "POST") {
7049
7270
  if (whoOf(req).actor !== "you") throw new HttpError(403, "only you answer a permission prompt");
7050
- const { decision, reason } = (
7051
- /** @type {{ decision?: unknown, reason?: unknown }} */
7271
+ const { decision, reason, always } = (
7272
+ /** @type {{ decision?: unknown, reason?: unknown, always?: unknown }} */
7052
7273
  await body(req)
7053
7274
  );
7054
7275
  if (decision !== "allow" && decision !== "deny") throw new HttpError(400, "decision is allow or deny");
7055
- const ok2 = permissions.decide(parts[2], decision, typeof reason === "string" ? reason : void 0);
7276
+ const ok2 = permissions.decide(parts[2], decision, typeof reason === "string" ? reason : void 0, always === true);
7277
+ if (ok2 === "too-long") return send2(res, 409, { error: "that command is too long to show whole here, so it cannot be allowed from here: read it in the agent's window, and answer it there" });
7278
+ if (ok2 === "no-always") return send2(res, 409, { error: `Claude Code offered no "don't ask again" for this one: allow it once, or deny it` });
7056
7279
  return send2(res, ok2 ? 200 : 404, ok2 ? { ok: true } : { error: "that prompt is no longer waiting: it was answered in the agent's window, or it went away" });
7057
7280
  }
7058
7281
  }
@@ -7071,7 +7294,7 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
7071
7294
  if (req.method === "GET") return send2(res, 200, { agents: heard(presence.list()) });
7072
7295
  if (req.method === "POST") {
7073
7296
  const who = whoOf(req);
7074
- if (who.actor === "you") throw new HttpError(400, "presence is for a harness plugin: send x-dcursed-agent: <harness>:<agent>");
7297
+ if (who.actor === "you") throw new HttpError(400, "presence is for a harness plugin: send x-diacode-agent: <harness>:<agent>");
7075
7298
  const { state, plan: planId, detail, pid } = (
7076
7299
  /** @type {{ state?: any, plan?: unknown, detail?: unknown, pid?: unknown }} */
7077
7300
  await body(req)
@@ -7087,14 +7310,14 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
7087
7310
  }
7088
7311
  }
7089
7312
  if (req.method === "GET" && parts[0] === "api" && parts[1] === "brief" && parts.length === 2) {
7090
- const asked = req.headers["x-dcursed-agent"] === void 0 ? void 0 : whoOf(req).actor;
7313
+ const asked = req.headers["x-diacode-agent"] === void 0 ? void 0 : whoOf(req).actor;
7091
7314
  const { text: planText, plan: plan2, rev } = store.brief(url.searchParams.get("plan") ?? void 0, asked);
7092
7315
  const text2 = [agents.stage(), planText].filter(Boolean).join("\n\n");
7093
- return sendText(res, 200, text2, plan2 === void 0 ? {} : { "x-dcursed-plan": plan2, "x-dcursed-rev": String(rev) });
7316
+ return sendText(res, 200, text2, plan2 === void 0 ? {} : { "x-diacode-plan": plan2, "x-diacode-rev": String(rev) });
7094
7317
  }
7095
7318
  if (req.method === "GET" && parts[0] === "api" && parts[1] === "events" && parts.length === 2) return listEvents(req, res);
7096
7319
  if (parts[0] === "api" && parts[1] === "architecture") {
7097
- if (parts.length === 2 && req.method === "GET") return send2(res, 200, archStore.exists ? { ...archStore.get(), listening: calls.listening(), calls: calls.list(ARCH_SCOPE).slice(0, 5) } : archStore.get());
7320
+ if (parts.length === 2 && req.method === "GET") return send2(res, 200, archStore.exists ? { ...archStore.get(), listening: calls.listening(), calls: calls.list(ARCH_SCOPE).slice(0, 8) } : archStore.get());
7098
7321
  if (parts.length === 2 && req.method === "POST") return send2(res, 201, await archStore.create(
7099
7322
  /** @type {any} */
7100
7323
  await body(req),
@@ -7155,6 +7378,12 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
7155
7378
  /** @type {{ steps?: unknown, kind?: unknown, step?: unknown }} */
7156
7379
  await body(req)
7157
7380
  );
7381
+ if (!opencodeReplans) {
7382
+ if (kind !== void 0 && kind !== "review" && kind !== "failure" && kind !== "drift") throw new HttpError(400, "kind is review, failure or drift");
7383
+ if (kind === "failure" && typeof step3 !== "string") throw new HttpError(400, 'a failure re-plan names the step that failed: { kind: "failure", step }');
7384
+ if (steps !== void 0 && !(Array.isArray(steps) && steps.every((s) => typeof s === "string"))) throw new HttpError(400, "steps is a list of step ids");
7385
+ return send2(res, 202, { call: calls.askAgent(id, { kind: kind === "failure" || kind === "drift" ? kind : "review", ...typeof step3 === "string" ? { step: step3 } : {}, ...Array.isArray(steps) ? { steps } : {} }) });
7386
+ }
7158
7387
  if (kind === "failure") {
7159
7388
  if (typeof step3 !== "string") throw new HttpError(400, 'a failure re-plan names the step that failed: { kind: "failure", step }');
7160
7389
  return send2(res, 202, { job: reconciler.startFailure(id, step3) });
@@ -7164,9 +7393,19 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
7164
7393
  if (steps !== void 0 && !(Array.isArray(steps) && steps.every((s) => typeof s === "string"))) throw new HttpError(400, "steps is a list of step ids");
7165
7394
  return send2(res, 202, { job: reconciler.start(id, steps) });
7166
7395
  }
7396
+ if (parts.length === 4 && parts[3] === "drift" && req.method === "POST") {
7397
+ if (whoOf(req).actor !== "you") throw new HttpError(403, "only you decide that a file outside the plan needs no step");
7398
+ const { ignore } = (
7399
+ /** @type {{ ignore?: unknown }} */
7400
+ await body(req)
7401
+ );
7402
+ if (ignore !== true && typeof ignore !== "string") throw new HttpError(400, "ignore is a file path, or true for all of them");
7403
+ store.get(id);
7404
+ return send2(res, 200, { ignored: store.ignoreOutside(id, ignore === true ? void 0 : ignore) });
7405
+ }
7167
7406
  if (parts.length === 4 && parts[3] === "observe" && req.method === "POST") {
7168
7407
  const who = whoOf(req);
7169
- if (who.actor === "you") throw new HttpError(400, "observe is for a harness plugin: send x-dcursed-agent: <harness>:<agent>");
7408
+ if (who.actor === "you") throw new HttpError(400, "observe is for a harness plugin: send x-diacode-agent: <harness>:<agent>");
7170
7409
  const { file } = (
7171
7410
  /** @type {{ file?: unknown }} */
7172
7411
  await body(req)
@@ -7199,7 +7438,7 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
7199
7438
  function plan(id) {
7200
7439
  const view = store.get(id);
7201
7440
  const stalled = presence.stalled(view.plan);
7202
- return { ...view, reconcile: reconciler.job(id), presence: heard(presence.list(id)), reads: receipts(id), listening: calls.listening(), stopping: stoppingOn(id), calls: calls.list(id).slice(0, 5), drift: store.driftOf(id), ...view.derived ? { derived: { ...view.derived, stalled } } : {} };
7441
+ return { ...view, replanner: opencodeReplans ? "opencode" : "agent", ...opencodeReplans ? {} : { replanAgent: calls.worker(id) }, reconcile: reconciler.job(id), presence: heard(presence.list(id)), reads: receipts(id), listening: calls.listening(), stopping: stoppingOn(id), calls: calls.list(id).slice(0, 8), drift: store.driftOf(id), ...view.derived ? { derived: { ...view.derived, stalled } } : {} };
7203
7442
  }
7204
7443
  function stoppingOn(id) {
7205
7444
  return [...calls.stops.keys()].filter((actor) => calls.stoppedFor(actor) === id).sort();
@@ -7341,7 +7580,8 @@ data: ${JSON.stringify(data)}
7341
7580
  }
7342
7581
  const session = typeof payload.session_id === "string" ? payload.session_id : void 0;
7343
7582
  const input2 = payload.tool_input && typeof payload.tool_input === "object" ? payload.tool_input : {};
7344
- const asked = permissions.ask({ actor, session, tool, input: input2, holdMs: holdOf(url, HOLD.hook) });
7583
+ if (debug) ring.add("hook", `permission ${tool}: suggestions ${JSON.stringify(payload.permission_suggestions ?? null).slice(0, 600)}`);
7584
+ const asked = permissions.ask({ actor, session, tool, input: input2, holdMs: holdOf(url, HOLD.hook), suggestions: payload.permission_suggestions });
7345
7585
  const pid = Number(url.searchParams.get("pid"));
7346
7586
  agents.handle(actor, { event: "asking", session, detail: `wants to ${asked.permission.what}`, ...Number.isInteger(pid) && pid > 1 ? { pid } : {} }).catch(() => {
7347
7587
  });
@@ -7417,10 +7657,10 @@ function holdOf(url, bounds) {
7417
7657
  return Number.isFinite(asked) && asked > 0 ? Math.min(Math.max(asked, 1e3), bounds.max) : bounds.default;
7418
7658
  }
7419
7659
  function whoOf(req) {
7420
- const agent = req.headers["x-dcursed-agent"];
7660
+ const agent = req.headers["x-diacode-agent"];
7421
7661
  if (agent === void 0) return { actor: "you", via: "editor" };
7422
7662
  if (typeof agent !== "string" || agent === "you" || !isActor(agent)) {
7423
- throw new HttpError(400, "x-dcursed-agent names an agent as <harness>:<agent>, such as opencode:build");
7663
+ throw new HttpError(400, "x-diacode-agent names an agent as <harness>:<agent>, such as opencode:build");
7424
7664
  }
7425
7665
  return { actor: agent, via: "plugin" };
7426
7666
  }
@@ -7467,12 +7707,12 @@ import { spawnSync } from "node:child_process";
7467
7707
 
7468
7708
  // packages/server/src/invoke.js
7469
7709
  function invocation(env = process.env) {
7470
- if (env.npm_command === "exec" || env.DCURSED_EDITOR === "1") return "npx diacode";
7471
- if (env.npm_lifecycle_event === "dcursed") return "npm run dcursed --";
7710
+ if (env.npm_command === "exec" || env.DIACODE_EDITOR === "1") return "npx diacode";
7711
+ if (env.npm_lifecycle_event === "diacode") return "npm run diacode --";
7472
7712
  return "diacode";
7473
7713
  }
7474
7714
  function serveHint(port2, env = process.env) {
7475
- return env.DCURSED_EDITOR === "1" ? `The DiaCode extension runs the plan server for this folder, on port ${port2}.` : `Start the plan server with: ${invocation(env)} serve --root . --port ${port2}`;
7715
+ return env.DIACODE_EDITOR === "1" ? `The DiaCode extension runs the plan server for this folder, on port ${port2}.` : `Start the plan server with: ${invocation(env)} serve --root . --port ${port2}`;
7476
7716
  }
7477
7717
  function nodeWarning(version = process.versions.node) {
7478
7718
  const major = Number(version.split(".")[0]);
@@ -7480,8 +7720,8 @@ function nodeWarning(version = process.versions.node) {
7480
7720
  }
7481
7721
 
7482
7722
  // packages/server/src/init.js
7483
- var BEGIN = "<!-- dcursed:begin (written by `diacode init`; edit outside these markers) -->";
7484
- var END = "<!-- dcursed:end -->";
7723
+ var BEGIN = "<!-- diacode:begin (written by `diacode init`; edit outside these markers) -->";
7724
+ var END = "<!-- diacode:end -->";
7485
7725
  async function read(path) {
7486
7726
  try {
7487
7727
  return await readFile4(path, "utf8");
@@ -7503,7 +7743,7 @@ async function put(path, text2, what) {
7503
7743
  async function pluginSource() {
7504
7744
  const published = new URL("../opencode-plugin.js", import.meta.url);
7505
7745
  const found = await read(fileURLToPath2(published));
7506
- return found ?? readFile4(new URL(import.meta.resolve("@dcursed/opencode-plugin")), "utf8");
7746
+ return found ?? readFile4(new URL(import.meta.resolve("@diacode/opencode-plugin")), "utf8");
7507
7747
  }
7508
7748
  async function initOpenCode({ root: root2, port: port2 = 7300, agent = "build" }) {
7509
7749
  const server = `http://127.0.0.1:${port2}`;
@@ -7522,21 +7762,21 @@ async function initOpenCode({ root: root2, port: port2 = 7300, agent = "build" }
7522
7762
  }
7523
7763
  }
7524
7764
  if (mergeable) {
7525
- config.mcp = { ...config.mcp ?? {}, dcursed: entry };
7765
+ config.mcp = { ...config.mcp ?? {}, diacode: entry };
7526
7766
  said.push(await put(configPath, `${JSON.stringify(config, null, 2)}
7527
- `, "opencode.json (the dcursed MCP server)"));
7767
+ `, "opencode.json (the diacode MCP server)"));
7528
7768
  } else {
7529
7769
  said.push(`NOT DONE opencode.json: it has comments or is not plain JSON, so add this yourself under "mcp":
7530
- "dcursed": ${JSON.stringify(entry)}`);
7770
+ "diacode": ${JSON.stringify(entry)}`);
7531
7771
  }
7532
- said.push(await put(join4(root2, ".dcursed", "opencode-plugin.js"), await pluginSource(), ".dcursed/opencode-plugin.js (the plugin)"));
7533
- said.push(await put(join4(root2, ".opencode", "plugins", "dcursed.js"), [
7772
+ said.push(await put(join4(root2, ".diacode", "opencode-plugin.js"), await pluginSource(), ".diacode/opencode-plugin.js (the plugin)"));
7773
+ said.push(await put(join4(root2, ".opencode", "plugins", "diacode.js"), [
7534
7774
  "// Written by `diacode init opencode`: gives the DiaCode plugin its options.",
7535
- "import { DiaCode } from '../../.dcursed/opencode-plugin.js';",
7775
+ "import { DiaCode } from '../../.diacode/opencode-plugin.js';",
7536
7776
  "",
7537
7777
  `export const DiaCodePlugin = (/** @type {any} */ ctx) => DiaCode(ctx, ${JSON.stringify({ server, agent })});`,
7538
7778
  ""
7539
- ].join("\n"), ".opencode/plugins/dcursed.js (loads it)"));
7779
+ ].join("\n"), ".opencode/plugins/diacode.js (loads it)"));
7540
7780
  const rulesPath = join4(root2, "AGENTS.md");
7541
7781
  const rules = await read(rulesPath);
7542
7782
  const block = `${BEGIN}
@@ -7574,9 +7814,28 @@ async function mergeJson(root2, rel, change, what, snippet) {
7574
7814
  }
7575
7815
  var curlHook = (port2, harness, hook, agent, fallback = "{}") => `curl -s --max-time 2 -X POST -H 'content-type: application/json' --data-binary @- 'http://127.0.0.1:${port2}/hooks/${harness}/${hook}?agent=${agent}' || echo '${fallback}'`;
7576
7816
  var askHook = (port2, harness, hook, agent) => `curl -s --max-time 2 -X POST -H 'content-type: application/json' --data-binary @- 'http://127.0.0.1:${port2}/hooks/${harness}/${hook}?agent=${agent}&pid='"$PPID" || echo '{}'`;
7577
- var ALLOW_TOOLS = "mcp__dcursed";
7817
+ var ALLOW_TOOLS = "mcp__diacode";
7578
7818
  var WAKE_SECONDS = 86400;
7579
7819
  var wakeHook = (port2, harness, agent) => `out=$(curl -sf --max-time ${WAKE_SECONDS - 30} -X POST -H 'content-type: application/json' --data-binary @- 'http://127.0.0.1:${port2}/hooks/${harness}/wake?agent=${agent}&hold=${(WAKE_SECONDS - 40) * 1e3}') && [ -n "$out" ] && { printf '%s' "$out" >&2; exit 2; }; exit 0`;
7820
+ var ACCEPT_EDITS_WORDS = [
7821
+ "Accept edits is on for this folder (you asked for it with --accept-edits): Claude Code now edits and writes files in it, and runs",
7822
+ "mkdir, touch, rm, rmdir, mv, cp and sed on files in it, without asking. Everything else (npm, node, git, curl\u2026) still asks, and so",
7823
+ "does anything outside this folder. It is in .claude/settings.local.json, which is not committed. `init claude-code --remove` takes it out again.",
7824
+ "Claude Code's folder-trust dialog lists the allow rule (mcp__diacode) but does not mention this mode, so this message, `doctor` and that file are where it is written down."
7825
+ ];
7826
+ async function setAcceptEdits(root2) {
7827
+ const rel = ".claude/settings.local.json";
7828
+ const path = join4(root2, rel);
7829
+ const { data, ok: ok2 } = await readJson(path);
7830
+ if (!ok2) return [`NOT DONE ${rel}: it has comments or is not plain JSON, so add this yourself:
7831
+ "permissions": { "defaultMode": "acceptEdits" }`];
7832
+ const was = data?.permissions?.defaultMode;
7833
+ if (was !== void 0 && was !== "acceptEdits" && was !== "default") return [`NOT DONE ${rel}: "permissions.defaultMode" is "${was}" there, so it was left as it is. Set it to "acceptEdits" yourself if you want accept edits.`];
7834
+ data.permissions = data.permissions ?? {};
7835
+ data.permissions.defaultMode = "acceptEdits";
7836
+ return [await put(path, `${JSON.stringify(data, null, 2)}
7837
+ `, `${rel} (Claude Code's mode: accept edits)`), ...ACCEPT_EDITS_WORDS];
7838
+ }
7580
7839
  var PERMISSION_SECONDS = 600;
7581
7840
  var permissionHook = (port2, harness, agent) => `out=$(curl -sf --max-time ${PERMISSION_SECONDS - 10} -X POST -H 'content-type: application/json' --data-binary @- 'http://127.0.0.1:${port2}/hooks/${harness}/permission?agent=${agent}&hold=${(PERMISSION_SECONDS - 20) * 1e3}&pid='"$PPID") && printf '%s' "$out"; exit 0`;
7582
7841
  var ownRules = (root2, rel, text2, what) => put(join4(root2, rel), text2, `${rel} (${what})`);
@@ -7615,14 +7874,14 @@ async function letGitSeeAgain(root2, rel) {
7615
7874
  await writeFile2(file, rest);
7616
7875
  return `updated ${file.startsWith(`${root2}/`) ? file.slice(root2.length + 1) : file} (our line for ${rel} removed)`;
7617
7876
  }
7618
- async function initClaudeCode({ root: root2, port: port2 = 7300, agent = "main", shared = false }) {
7877
+ async function initClaudeCode({ root: root2, port: port2 = 7300, agent = "main", shared = false, acceptEdits = false }) {
7619
7878
  const p = String(port2);
7620
7879
  const said = [];
7621
7880
  const url = `http://127.0.0.1:${p}/mcp/claude-code?agent=${encodeURIComponent(agent)}`;
7622
7881
  const entry = { type: "http", url, alwaysLoad: true };
7623
7882
  said.push(await mergeJson(root2, ".mcp.json", (d) => {
7624
- d.mcpServers = { ...d.mcpServers ?? {}, dcursed: entry };
7625
- }, "the dcursed MCP server", `"mcpServers": { "dcursed": ${JSON.stringify(entry)} }`));
7883
+ d.mcpServers = { ...d.mcpServers ?? {}, diacode: entry };
7884
+ }, "the diacode MCP server", `"mcpServers": { "diacode": ${JSON.stringify(entry)} }`));
7626
7885
  const http2 = (hook, timeout = 3) => ({ type: "http", url: `http://127.0.0.1:${p}/hooks/claude-code/${hook}?agent=${encodeURIComponent(agent)}`, timeout });
7627
7886
  const ours = (
7628
7887
  /** @type {Record<string, any>} */
@@ -7656,8 +7915,15 @@ async function initClaudeCode({ root: root2, port: port2 = 7300, agent = "main",
7656
7915
  const kept = await keepOutOfGit(root2, ".claude/settings.local.json");
7657
7916
  if (kept) said.push(kept);
7658
7917
  }
7659
- said.push(await ownRules(root2, ".claude/rules/dcursed.md", `${RULES_BODY}`, "how to work with the plan"));
7660
- said.push("", FLOW_HINT, "", serveHint(port2), "Then start a new Claude Code session in this folder (approve the dcursed MCP server when asked).");
7918
+ if (acceptEdits) {
7919
+ said.push(...await setAcceptEdits(root2));
7920
+ if (shared) {
7921
+ const kept = await keepOutOfGit(root2, ".claude/settings.local.json");
7922
+ if (kept) said.push(kept);
7923
+ }
7924
+ }
7925
+ said.push(await ownRules(root2, ".claude/rules/diacode.md", `${RULES_BODY}`, "how to work with the plan"));
7926
+ said.push("", FLOW_HINT, "", serveHint(port2), "Then start a new Claude Code session in this folder (approve the diacode MCP server when asked).");
7661
7927
  return said;
7662
7928
  }
7663
7929
  async function initCursor({ root: root2, port: port2 = 7300, agent = "agent" }) {
@@ -7666,8 +7932,8 @@ async function initCursor({ root: root2, port: port2 = 7300, agent = "agent" })
7666
7932
  const said = [];
7667
7933
  const entry = { url: `http://127.0.0.1:${p}/mcp/cursor?agent=${a}` };
7668
7934
  said.push(await mergeJson(root2, ".cursor/mcp.json", (d) => {
7669
- d.mcpServers = { ...d.mcpServers ?? {}, dcursed: entry };
7670
- }, "the dcursed MCP server", `"mcpServers": { "dcursed": ${JSON.stringify(entry)} }`));
7935
+ d.mcpServers = { ...d.mcpServers ?? {}, diacode: entry };
7936
+ }, "the diacode MCP server", `"mcpServers": { "diacode": ${JSON.stringify(entry)} }`));
7671
7937
  const hook = (name2, fallback = "{}") => ({ command: curlHook(p, "cursor", name2, a, fallback), timeout: 3 });
7672
7938
  const ours = (
7673
7939
  /** @type {Record<string, any[]>} */
@@ -7686,13 +7952,13 @@ async function initCursor({ root: root2, port: port2 = 7300, agent = "agent" })
7686
7952
  d.hooks = d.hooks ?? {};
7687
7953
  for (const [event, list] of Object.entries(ours)) d.hooks[event] = [...(d.hooks[event] ?? []).filter((h) => !mine(h)), ...list];
7688
7954
  }, "the hooks that tell the plan server what the agent does, and tell the agent what changed", `"hooks": ${JSON.stringify(ours)}`));
7689
- said.push(await ownRules(root2, ".cursor/rules/dcursed.mdc", `---
7955
+ said.push(await ownRules(root2, ".cursor/rules/diacode.mdc", `---
7690
7956
  description: How to work with this repository's DiaCode plans
7691
7957
  alwaysApply: true
7692
7958
  ---
7693
7959
 
7694
7960
  ${RULES_BODY}`, "how to work with the plan"));
7695
- said.push("", FLOW_HINT, "", serveHint(port2), "Then enable the dcursed server in Cursor Settings \u2192 MCP, and start a new chat.");
7961
+ said.push("", FLOW_HINT, "", serveHint(port2), "Then enable the diacode server in Cursor Settings \u2192 MCP, and start a new chat.");
7696
7962
  return said;
7697
7963
  }
7698
7964
  async function initAntigravity({ root: root2, port: port2 = 7300, agent = "agent" }) {
@@ -7701,8 +7967,8 @@ async function initAntigravity({ root: root2, port: port2 = 7300, agent = "agent
7701
7967
  const said = [];
7702
7968
  const entry = { serverUrl: `http://127.0.0.1:${p}/mcp/antigravity?agent=${a}` };
7703
7969
  said.push(await mergeJson(root2, ".agents/mcp_config.json", (d) => {
7704
- d.mcpServers = { ...d.mcpServers ?? {}, dcursed: entry };
7705
- }, "the dcursed MCP server", `"mcpServers": { "dcursed": ${JSON.stringify(entry)} }`));
7970
+ d.mcpServers = { ...d.mcpServers ?? {}, diacode: entry };
7971
+ }, "the diacode MCP server", `"mcpServers": { "diacode": ${JSON.stringify(entry)} }`));
7706
7972
  const command = (name2) => ({ type: "command", command: curlHook(p, "antigravity", name2, a), timeout: 4 });
7707
7973
  const ours = {
7708
7974
  enabled: true,
@@ -7713,9 +7979,9 @@ async function initAntigravity({ root: root2, port: port2 = 7300, agent = "agent
7713
7979
  Stop: [command("Stop")]
7714
7980
  };
7715
7981
  said.push(await mergeJson(root2, ".agents/hooks.json", (d) => {
7716
- d.dcursed = ours;
7717
- }, "the hooks that tell the plan server what the agent does, and tell the agent what changed", `"dcursed": ${JSON.stringify(ours)}`));
7718
- said.push(await ownRules(root2, ".agents/rules/dcursed.md", `---
7982
+ d.diacode = ours;
7983
+ }, "the hooks that tell the plan server what the agent does, and tell the agent what changed", `"diacode": ${JSON.stringify(ours)}`));
7984
+ said.push(await ownRules(root2, ".agents/rules/diacode.md", `---
7719
7985
  trigger: always_on
7720
7986
  description: How to work with this repository's DiaCode plans
7721
7987
  ---
@@ -7725,7 +7991,7 @@ ${RULES_BODY}`, "how to work with the plan"));
7725
7991
  return said;
7726
7992
  }
7727
7993
  var HARNESS_INIT = (
7728
- /** @type {Record<string, (o: { root: string, port?: number, agent?: string, shared?: boolean }) => Promise<string[]>>} */
7994
+ /** @type {Record<string, (o: { root: string, port?: number, agent?: string, shared?: boolean, acceptEdits?: boolean }) => Promise<string[]>>} */
7729
7995
  {
7730
7996
  opencode: initOpenCode,
7731
7997
  "claude-code": initClaudeCode,
@@ -7768,14 +8034,14 @@ async function removeOpenCode({ root: root2 }) {
7768
8034
  const said = [];
7769
8035
  said.push(await unmergeJson(root2, "opencode.json", (d) => {
7770
8036
  if (d.mcp) {
7771
- delete d.mcp.dcursed;
8037
+ delete d.mcp.diacode;
7772
8038
  pruneEmpty(d, "mcp");
7773
8039
  }
7774
- }, (d) => onlyOurs(d, ["$schema"]), /dcursed/, 'the "dcursed" entry under "mcp"'));
8040
+ }, (d) => onlyOurs(d, ["$schema"]), /diacode/, 'the "diacode" entry under "mcp"'));
7775
8041
  const jsonc = await read(join4(root2, "opencode.jsonc"));
7776
- if (jsonc !== null && /dcursed/.test(jsonc)) said.push('NOT DONE opencode.jsonc: it has comments, so remove the "dcursed" entry under "mcp" yourself');
7777
- said.push(await drop(root2, ".opencode/plugins/dcursed.js", "the plugin's loader"));
7778
- said.push(await drop(root2, ".dcursed/opencode-plugin.js", "the plugin"));
8042
+ if (jsonc !== null && /diacode/.test(jsonc)) said.push('NOT DONE opencode.jsonc: it has comments, so remove the "diacode" entry under "mcp" yourself');
8043
+ said.push(await drop(root2, ".opencode/plugins/diacode.js", "the plugin's loader"));
8044
+ said.push(await drop(root2, ".diacode/opencode-plugin.js", "the plugin"));
7779
8045
  const agents = await read(join4(root2, "AGENTS.md"));
7780
8046
  if (agents === null || !agents.includes(BEGIN)) {
7781
8047
  said.push(`absent AGENTS.md (no DiaCode block)`);
@@ -7794,10 +8060,10 @@ async function removeClaudeCode({ root: root2 }) {
7794
8060
  const said = [];
7795
8061
  said.push(await unmergeJson(root2, ".mcp.json", (d) => {
7796
8062
  if (d.mcpServers) {
7797
- delete d.mcpServers.dcursed;
8063
+ delete d.mcpServers.diacode;
7798
8064
  pruneEmpty(d, "mcpServers");
7799
8065
  }
7800
- }, (d) => onlyOurs(d), /dcursed/, 'the "dcursed" entry under "mcpServers"'));
8066
+ }, (d) => onlyOurs(d), /diacode/, 'the "diacode" entry under "mcpServers"'));
7801
8067
  for (const rel of [".claude/settings.local.json", ".claude/settings.json"]) {
7802
8068
  said.push(await unmergeJson(root2, rel, (d) => {
7803
8069
  const ours = isOurs("/hooks/claude-code/");
@@ -7825,9 +8091,13 @@ async function removeClaudeCode({ root: root2 }) {
7825
8091
  pruneEmpty(d.permissions, "allow");
7826
8092
  pruneEmpty(d, "permissions");
7827
8093
  }
7828
- }, (d) => onlyOurs(d), /\/hooks\/claude-code\/|mcp__dcursed/, 'the hooks whose address contains /hooks/claude-code/, and the "mcp__dcursed" allow rule'));
8094
+ if (rel === ".claude/settings.local.json" && d.permissions?.defaultMode === "acceptEdits") {
8095
+ delete d.permissions.defaultMode;
8096
+ pruneEmpty(d, "permissions");
8097
+ }
8098
+ }, (d) => onlyOurs(d), /\/hooks\/claude-code\/|mcp__diacode|"defaultMode":\s*"acceptEdits"/, 'the hooks whose address contains /hooks/claude-code/, the "mcp__diacode" allow rule, and "defaultMode": "acceptEdits" in settings.local.json'));
7829
8099
  }
7830
- said.push(await drop(root2, ".claude/rules/dcursed.md", "the rules"));
8100
+ said.push(await drop(root2, ".claude/rules/diacode.md", "the rules"));
7831
8101
  const unhidden = await letGitSeeAgain(root2, ".claude/settings.local.json");
7832
8102
  if (unhidden) said.push(unhidden);
7833
8103
  return said;
@@ -7836,10 +8106,10 @@ async function removeCursor({ root: root2 }) {
7836
8106
  const said = [];
7837
8107
  said.push(await unmergeJson(root2, ".cursor/mcp.json", (d) => {
7838
8108
  if (d.mcpServers) {
7839
- delete d.mcpServers.dcursed;
8109
+ delete d.mcpServers.diacode;
7840
8110
  pruneEmpty(d, "mcpServers");
7841
8111
  }
7842
- }, (d) => onlyOurs(d), /dcursed/, 'the "dcursed" entry under "mcpServers"'));
8112
+ }, (d) => onlyOurs(d), /diacode/, 'the "diacode" entry under "mcpServers"'));
7843
8113
  said.push(await unmergeJson(root2, ".cursor/hooks.json", (d) => {
7844
8114
  for (const [event, list] of Object.entries(d.hooks ?? {})) {
7845
8115
  d.hooks[event] = /** @type {any[]} */
@@ -7848,21 +8118,21 @@ async function removeCursor({ root: root2 }) {
7848
8118
  }
7849
8119
  pruneEmpty(d, "hooks");
7850
8120
  }, (d) => onlyOurs(d, ["version"]), /\/hooks\/cursor\//, "the hooks whose command contains /hooks/cursor/"));
7851
- said.push(await drop(root2, ".cursor/rules/dcursed.mdc", "the rules"));
8121
+ said.push(await drop(root2, ".cursor/rules/diacode.mdc", "the rules"));
7852
8122
  return said;
7853
8123
  }
7854
8124
  async function removeAntigravity({ root: root2 }) {
7855
8125
  const said = [];
7856
8126
  said.push(await unmergeJson(root2, ".agents/mcp_config.json", (d) => {
7857
8127
  if (d.mcpServers) {
7858
- delete d.mcpServers.dcursed;
8128
+ delete d.mcpServers.diacode;
7859
8129
  pruneEmpty(d, "mcpServers");
7860
8130
  }
7861
- }, (d) => onlyOurs(d), /dcursed/, 'the "dcursed" entry under "mcpServers"'));
8131
+ }, (d) => onlyOurs(d), /diacode/, 'the "diacode" entry under "mcpServers"'));
7862
8132
  said.push(await unmergeJson(root2, ".agents/hooks.json", (d) => {
7863
- delete d.dcursed;
7864
- }, (d) => onlyOurs(d), /dcursed|\/hooks\/antigravity\//, 'the "dcursed" key'));
7865
- said.push(await drop(root2, ".agents/rules/dcursed.md", "the rules"));
8133
+ delete d.diacode;
8134
+ }, (d) => onlyOurs(d), /diacode|\/hooks\/antigravity\//, 'the "diacode" key'));
8135
+ said.push(await drop(root2, ".agents/rules/diacode.md", "the rules"));
7866
8136
  return said;
7867
8137
  }
7868
8138
  var HARNESS_REMOVE = (
@@ -7875,17 +8145,161 @@ var HARNESS_REMOVE = (
7875
8145
  }
7876
8146
  );
7877
8147
 
8148
+ // packages/server/src/migrate.js
8149
+ import { readdir as readdir3, rename as rename2, rm as rm2, rmdir as rmdir2, writeFile as writeFile3, readFile as readFile5, mkdir as mkdir3, stat as stat3 } from "node:fs/promises";
8150
+ import { join as join5 } from "node:path";
8151
+ var OLD_DIR = ".dcursed";
8152
+ var NEW_DIR = ".diacode";
8153
+ var OLD_SERVER = "dcursed";
8154
+ var OLD_RULE = "mcp__dcursed";
8155
+ var OLD_BEGIN = /<!-- dcursed:begin[^>]*-->/;
8156
+ var OLD_END = "<!-- dcursed:end -->";
8157
+ var MCP_FILES = (
8158
+ /** @type {const} */
8159
+ [[".mcp.json", "mcpServers"], [".cursor/mcp.json", "mcpServers"], [".agents/mcp_config.json", "mcpServers"], ["opencode.json", "mcp"]]
8160
+ );
8161
+ var OLD_FILES = [".claude/rules/dcursed.md", ".cursor/rules/dcursed.mdc", ".agents/rules/dcursed.md", ".opencode/plugins/dcursed.js"];
8162
+ var SETTINGS = [".claude/settings.local.json", ".claude/settings.json"];
8163
+ var exists = async (path) => {
8164
+ try {
8165
+ await stat3(path);
8166
+ return true;
8167
+ } catch {
8168
+ return false;
8169
+ }
8170
+ };
8171
+ async function legacyFound(root2) {
8172
+ const found = [];
8173
+ if (await exists(join5(root2, OLD_DIR))) found.push(`the ${OLD_DIR}/ folder`);
8174
+ for (const [rel, key2] of MCP_FILES) {
8175
+ const { data } = await readJson(join5(root2, rel));
8176
+ if (data?.[key2]?.[OLD_SERVER] !== void 0) found.push(`the "${OLD_SERVER}" entry in ${rel}`);
8177
+ }
8178
+ const hooks = await readJson(join5(root2, ".agents/hooks.json"));
8179
+ if (hooks.data?.[OLD_SERVER] !== void 0) found.push(`the "${OLD_SERVER}" key in .agents/hooks.json`);
8180
+ for (const rel of SETTINGS) {
8181
+ const { data } = await readJson(join5(root2, rel));
8182
+ if (Array.isArray(data?.permissions?.allow) && data.permissions.allow.includes(OLD_RULE)) found.push(`the ${OLD_RULE} allow rule in ${rel}`);
8183
+ }
8184
+ for (const rel of OLD_FILES) if (await exists(join5(root2, rel))) found.push(rel);
8185
+ const agents = await read(join5(root2, "AGENTS.md"));
8186
+ if (agents && OLD_BEGIN.test(agents)) found.push("the old block in AGENTS.md");
8187
+ return found;
8188
+ }
8189
+ async function moveInto(from, to, label, said) {
8190
+ let complete = true;
8191
+ const info = await stat3(from);
8192
+ if (info.isDirectory()) {
8193
+ await mkdir3(to, { recursive: true });
8194
+ for (const name2 of await readdir3(from)) complete = await moveInto(join5(from, name2), join5(to, name2), `${label}/${name2}`, said) && complete;
8195
+ if (complete) await rmdir2(from);
8196
+ return complete;
8197
+ }
8198
+ if (await exists(to)) {
8199
+ said.push(`NOT DONE ${label}: it is in both folders, so the old one was left; keep the one you want and delete the other`);
8200
+ return false;
8201
+ }
8202
+ await mkdir3(join5(to, ".."), { recursive: true });
8203
+ await rename2(from, to);
8204
+ return true;
8205
+ }
8206
+ var renameFormats = (text2) => text2.replace(/("schema"\s*:\s*")dcursed\.(plan|arch|layout)\//g, "$1diacode.$2/").replace(/("kind"\s*:\s*)"dcursed"/g, '$1"diacode"');
8207
+ async function migrate(root2) {
8208
+ const said = [];
8209
+ const oldDir = join5(root2, OLD_DIR);
8210
+ if (await exists(oldDir)) {
8211
+ const newDir = join5(root2, NEW_DIR);
8212
+ await rm2(join5(oldDir, "opencode-plugin.js"), { force: true });
8213
+ const moved = await moveInto(oldDir, newDir, OLD_DIR, said);
8214
+ const files = [];
8215
+ for (const sub of ["", "plans"]) {
8216
+ try {
8217
+ for (const f of await readdir3(join5(newDir, sub))) if (/\.(plan|arch|layout)\.json$|^architecture(\.layout)?\.json$/.test(f)) files.push(join5(newDir, sub, f));
8218
+ } catch {
8219
+ }
8220
+ }
8221
+ let renamed = 0;
8222
+ for (const file of files) {
8223
+ const text2 = await readFile5(file, "utf8");
8224
+ const next = renameFormats(text2);
8225
+ if (next !== text2) {
8226
+ await writeFile3(file, next);
8227
+ renamed += 1;
8228
+ }
8229
+ }
8230
+ said.push(moved ? `moved ${OLD_DIR}/ to ${NEW_DIR}/ (${renamed} file${renamed === 1 ? "" : "s"} now say diacode.*; the plan logs are as they were)` : `partly moved ${OLD_DIR}/ to ${NEW_DIR}/ (see above)`);
8231
+ }
8232
+ for (const [rel, key2] of MCP_FILES) {
8233
+ const path = join5(root2, rel);
8234
+ const { data, text: text2, ok: ok2 } = await readJson(path);
8235
+ if (text2 === null) continue;
8236
+ if (!ok2) {
8237
+ if (text2.includes(`"${OLD_SERVER}"`)) said.push(`NOT DONE ${rel}: it has comments or is not plain JSON, so remove the "${OLD_SERVER}" entry under "${key2}" yourself`);
8238
+ continue;
8239
+ }
8240
+ if (data?.[key2]?.[OLD_SERVER] === void 0) continue;
8241
+ delete data[key2][OLD_SERVER];
8242
+ pruneEmpty(data, key2);
8243
+ if (Object.keys(data).every((k) => k === "$schema")) said.push(await drop(root2, rel, "it held only the old DcurseD entry"));
8244
+ else {
8245
+ await writeFile3(path, `${JSON.stringify(data, null, 2)}
8246
+ `);
8247
+ said.push(`updated ${rel} (the "${OLD_SERVER}" entry removed)`);
8248
+ }
8249
+ }
8250
+ {
8251
+ const path = join5(root2, ".agents/hooks.json");
8252
+ const { data, ok: ok2 } = await readJson(path);
8253
+ if (ok2 && data?.[OLD_SERVER] !== void 0) {
8254
+ delete data[OLD_SERVER];
8255
+ if (Object.keys(data).length === 0) said.push(await drop(root2, ".agents/hooks.json", "it held only the old DcurseD hooks"));
8256
+ else {
8257
+ await writeFile3(path, `${JSON.stringify(data, null, 2)}
8258
+ `);
8259
+ said.push(`updated .agents/hooks.json (the "${OLD_SERVER}" key removed)`);
8260
+ }
8261
+ }
8262
+ }
8263
+ for (const rel of SETTINGS) {
8264
+ const path = join5(root2, rel);
8265
+ const { data, ok: ok2 } = await readJson(path);
8266
+ if (!ok2 || !Array.isArray(data?.permissions?.allow) || !data.permissions.allow.includes(OLD_RULE)) continue;
8267
+ data.permissions.allow = data.permissions.allow.filter((r) => r !== OLD_RULE);
8268
+ pruneEmpty(data.permissions, "allow");
8269
+ pruneEmpty(data, "permissions");
8270
+ await writeFile3(path, `${JSON.stringify(data, null, 2)}
8271
+ `);
8272
+ said.push(`updated ${rel} (the ${OLD_RULE} allow rule removed; init adds mcp__diacode)`);
8273
+ }
8274
+ for (const rel of OLD_FILES) if (await exists(join5(root2, rel))) said.push(await drop(root2, rel, "written by the old init"));
8275
+ const agentsPath = join5(root2, "AGENTS.md");
8276
+ const agents = await read(agentsPath);
8277
+ if (agents !== null && OLD_BEGIN.test(agents) && agents.includes(OLD_END)) {
8278
+ const rest = agents.replace(new RegExp(`\\n*${OLD_BEGIN.source}[\\s\\S]*?${escape(OLD_END)}\\n*`), "\n\n").replace(/^\n+/, "").replace(/\n{3,}/g, "\n\n");
8279
+ if (!rest.trim()) said.push(await drop(root2, "AGENTS.md", "it held only the old DcurseD block"));
8280
+ else {
8281
+ await writeFile3(agentsPath, rest.replace(/\n*$/, "\n"));
8282
+ said.push("updated AGENTS.md (the old DcurseD block removed)");
8283
+ }
8284
+ }
8285
+ try {
8286
+ await rmdir2(oldDir);
8287
+ } catch {
8288
+ }
8289
+ return said;
8290
+ }
8291
+
7878
8292
  // packages/server/src/doctor.js
7879
- import { readFile as readFile5, readdir as readdir3 } from "node:fs/promises";
8293
+ import { readFile as readFile6, readdir as readdir4 } from "node:fs/promises";
7880
8294
  import { accessSync, constants } from "node:fs";
7881
- import { join as join5, resolve as resolve4, delimiter } from "node:path";
8295
+ import { join as join6, resolve as resolve4, delimiter } from "node:path";
7882
8296
  import { homedir } from "node:os";
7883
8297
  var ok = (text2) => ({ level: "ok", text: text2 });
7884
8298
  var problem = (text2, fix) => ({ level: "problem", text: text2, ...fix ? { fix } : {} });
7885
8299
  var note = (text2) => ({ level: "note", text: text2 });
7886
8300
  async function text(root2, rel) {
7887
8301
  try {
7888
- return await readFile5(join5(root2, rel), "utf8");
8302
+ return await readFile6(join6(root2, rel), "utf8");
7889
8303
  } catch {
7890
8304
  return null;
7891
8305
  }
@@ -7905,7 +8319,7 @@ function portsIn(s, after = "") {
7905
8319
  function onPath(cmd2) {
7906
8320
  for (const dir of (process.env.PATH ?? "").split(delimiter)) {
7907
8321
  try {
7908
- accessSync(join5(dir, cmd2), constants.X_OK);
8322
+ accessSync(join6(dir, cmd2), constants.X_OK);
7909
8323
  return true;
7910
8324
  } catch {
7911
8325
  }
@@ -7917,11 +8331,11 @@ async function mcpEntry(root2, rel, harness, pick3) {
7917
8331
  if (t === null) return { finding: problem(`${rel} is missing, so the agent has no plan tools`, "{init}"), ports: [] };
7918
8332
  const data = json(t);
7919
8333
  if (data === null) {
7920
- return t.includes(`/mcp/${harness}`) ? { finding: ok(`${rel} names the dcursed MCP server (it has comments, so read as text)`), ports: portsIn(t, `/mcp/${harness}`) } : { finding: problem(`${rel} has comments and no dcursed MCP entry`, `add the entry \`${invocation()} init\` printed, by hand`), ports: [] };
8334
+ return t.includes(`/mcp/${harness}`) ? { finding: ok(`${rel} names the diacode MCP server (it has comments, so read as text)`), ports: portsIn(t, `/mcp/${harness}`) } : { finding: problem(`${rel} has comments and no diacode MCP entry`, `add the entry \`${invocation()} init\` printed, by hand`), ports: [] };
7921
8335
  }
7922
8336
  const url = pick3(data);
7923
- if (!url) return { finding: problem(`${rel} has no dcursed entry`, "{init}"), ports: [] };
7924
- return { finding: ok(`${rel}: the dcursed MCP server at ${url}`), ports: portsIn(url) };
8337
+ if (!url) return { finding: problem(`${rel} has no diacode entry`, "{init}"), ports: [] };
8338
+ return { finding: ok(`${rel}: the diacode MCP server at ${url}`), ports: portsIn(url) };
7925
8339
  }
7926
8340
  async function hooksEntry(root2, files, harness, events, hooksOf) {
7927
8341
  const marker = `/hooks/${harness}/`;
@@ -7953,36 +8367,36 @@ async function rulesFile(root2, rel, what) {
7953
8367
  async function openCode(root2) {
7954
8368
  const configFile = await text(root2, "opencode.json") !== null ? "opencode.json" : await text(root2, "opencode.jsonc") !== null ? "opencode.jsonc" : "opencode.json";
7955
8369
  const config = await text(root2, configFile);
7956
- const loader = await text(root2, ".opencode/plugins/dcursed.js");
8370
+ const loader = await text(root2, ".opencode/plugins/diacode.js");
7957
8371
  if (config === null && loader === null) return null;
7958
8372
  const findings = [];
7959
8373
  const ports = [];
7960
- const mcp = await mcpEntry(root2, configFile, "opencode", (d) => d?.mcp?.dcursed?.url);
8374
+ const mcp = await mcpEntry(root2, configFile, "opencode", (d) => d?.mcp?.diacode?.url);
7961
8375
  findings.push(mcp.finding);
7962
8376
  ports.push(...mcp.ports);
7963
- if (loader === null) findings.push(problem(".opencode/plugins/dcursed.js is missing, so OpenCode does not load the plugin", "{init}"));
8377
+ if (loader === null) findings.push(problem(".opencode/plugins/diacode.js is missing, so OpenCode does not load the plugin", "{init}"));
7964
8378
  else {
7965
- findings.push(ok(".opencode/plugins/dcursed.js (loads the plugin)"));
8379
+ findings.push(ok(".opencode/plugins/diacode.js (loads the plugin)"));
7966
8380
  ports.push(...portsIn(loader));
7967
8381
  }
7968
- const installed = await text(root2, ".dcursed/opencode-plugin.js");
7969
- if (installed === null) findings.push(problem(".dcursed/opencode-plugin.js is missing: the plugin itself", "{init}"));
7970
- else if (installed !== await pluginSource()) findings.push(problem(".dcursed/opencode-plugin.js is not the plugin that ships with this dcursed (an older one, or edited)", "{init}"));
7971
- else findings.push(ok(".dcursed/opencode-plugin.js is this version's plugin"));
8382
+ const installed = await text(root2, ".diacode/opencode-plugin.js");
8383
+ if (installed === null) findings.push(problem(".diacode/opencode-plugin.js is missing: the plugin itself", "{init}"));
8384
+ else if (installed !== await pluginSource()) findings.push(problem(".diacode/opencode-plugin.js is not the plugin that ships with this diacode (an older one, or edited)", "{init}"));
8385
+ else findings.push(ok(".diacode/opencode-plugin.js is this version's plugin"));
7972
8386
  const agents = await text(root2, "AGENTS.md");
7973
8387
  findings.push(!agents?.includes(BEGIN) ? problem("AGENTS.md has no DiaCode block: the agent is not told how to work with the plan", "{init}") : agents.includes("THE ORDER") ? ok("AGENTS.md (how to work with the plan)") : problem("AGENTS.md has the DiaCode block of an older version: it does not tell the agent the order (architecture, then plan, then Start)", "{init}"));
7974
8388
  return { harness: "opencode", label: "OpenCode", ports, findings };
7975
8389
  }
7976
8390
  async function claudeCode(root2) {
7977
- const files = [".mcp.json", ".claude/settings.local.json", ".claude/settings.json", ".claude/rules/dcursed.md"];
8391
+ const files = [".mcp.json", ".claude/settings.local.json", ".claude/settings.json", ".claude/rules/diacode.md"];
7978
8392
  const present = await Promise.all(files.map((f) => text(root2, f)));
7979
8393
  const mcpText = present[0];
7980
8394
  const hasOurs = (mcpText ?? "").includes("/mcp/claude-code") || present.slice(1, 3).some((t) => (t ?? "").includes("/hooks/claude-code/")) || present[3] !== null;
7981
8395
  if (!hasOurs) return null;
7982
8396
  const findings = [];
7983
- const mcp = await mcpEntry(root2, ".mcp.json", "claude-code", (d) => d?.mcpServers?.dcursed?.url);
8397
+ const mcp = await mcpEntry(root2, ".mcp.json", "claude-code", (d) => d?.mcpServers?.diacode?.url);
7984
8398
  const hooks = await hooksEntry(root2, [".claude/settings.local.json", ".claude/settings.json"], "claude-code", ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop", "SessionEnd"], (d) => d?.hooks);
7985
- findings.push(mcp.finding, hooks.finding, await rulesFile(root2, ".claude/rules/dcursed.md", "the agent is not told how to work with the plan"));
8399
+ findings.push(mcp.finding, hooks.finding, await rulesFile(root2, ".claude/rules/diacode.md", "the agent is not told how to work with the plan"));
7986
8400
  const hookText = present.slice(1, 3).map((t) => t ?? "").join("\n");
7987
8401
  if (hookText.includes("/hooks/claude-code/Stop") && !hookText.includes("/hooks/claude-code/wake")) {
7988
8402
  findings.push(problem("no wake hook: approving the plan in the editor, or answering a question, cannot start this agent (it is told at its next step)", "{init}"));
@@ -7996,17 +8410,19 @@ async function claudeCode(root2) {
7996
8410
  findings.push(problem("no PermissionRequest hook: when the agent asks your permission, the editor says so but cannot answer it (only its own window can)", "{init}"));
7997
8411
  }
7998
8412
  if (hookText.includes("/hooks/claude-code/Stop") && !hookText.includes("/hooks/claude-code/PreToolUse")) {
7999
- findings.push(problem("no PreToolUse hook: Stop in the editor cannot halt the agent mid-turn (it hears it at its next dcursed tool)", "{init}"));
8413
+ findings.push(problem("no PreToolUse hook: Stop in the editor cannot halt the agent mid-turn (it hears it at its next diacode tool)", "{init}"));
8000
8414
  }
8001
8415
  if (hookText.includes("/hooks/claude-code/Stop") && !hookText.includes(ALLOW_TOOLS)) {
8002
8416
  findings.push(note(`Claude Code asks permission before each plan call; init adds one rule, "${ALLOW_TOOLS}", that covers only the plan tools (run init again to add it, or skip it if you want the prompts)`));
8003
8417
  }
8418
+ const local = present[1] ?? "";
8419
+ if (/"defaultMode":\s*"acceptEdits"/.test(local)) findings.push(note("Claude Code is in accept-edits mode for this folder (.claude/settings.local.json): it edits files in the folder, and runs mkdir, touch, rm, rmdir, mv, cp and sed there, without asking. Everything else still asks. `init claude-code --remove` takes it out."));
8004
8420
  return { harness: "claude-code", label: "Claude Code", ports: [...mcp.ports, ...hooks.ports], findings };
8005
8421
  }
8006
8422
  async function cursor(root2) {
8007
- const t = [await text(root2, ".cursor/mcp.json"), await text(root2, ".cursor/hooks.json"), await text(root2, ".cursor/rules/dcursed.mdc")];
8423
+ const t = [await text(root2, ".cursor/mcp.json"), await text(root2, ".cursor/hooks.json"), await text(root2, ".cursor/rules/diacode.mdc")];
8008
8424
  if (!((t[0] ?? "").includes("/mcp/cursor") || (t[1] ?? "").includes("/hooks/cursor/") || t[2] !== null)) return null;
8009
- const mcp = await mcpEntry(root2, ".cursor/mcp.json", "cursor", (d) => d?.mcpServers?.dcursed?.url);
8425
+ const mcp = await mcpEntry(root2, ".cursor/mcp.json", "cursor", (d) => d?.mcpServers?.diacode?.url);
8010
8426
  const hooks = await hooksEntry(root2, [".cursor/hooks.json"], "cursor", ["sessionStart", "beforeSubmitPrompt", "afterFileEdit", "postToolUse", "stop", "sessionEnd"], (d) => d?.hooks);
8011
8427
  return {
8012
8428
  harness: "cursor",
@@ -8015,17 +8431,17 @@ async function cursor(root2) {
8015
8431
  findings: [
8016
8432
  mcp.finding,
8017
8433
  hooks.finding,
8018
- await rulesFile(root2, ".cursor/rules/dcursed.mdc", "the agent is not told how to work with the plan"),
8019
- note("Cursor asks you to enable the dcursed server in Settings \u2192 MCP; that switch is inside Cursor, so this cannot see it.")
8434
+ await rulesFile(root2, ".cursor/rules/diacode.mdc", "the agent is not told how to work with the plan"),
8435
+ note("Cursor asks you to enable the diacode server in Settings \u2192 MCP; that switch is inside Cursor, so this cannot see it.")
8020
8436
  ]
8021
8437
  };
8022
8438
  }
8023
8439
  async function antigravity(root2) {
8024
- const t = [await text(root2, ".agents/mcp_config.json"), await text(root2, ".agents/hooks.json"), await text(root2, ".agents/rules/dcursed.md")];
8440
+ const t = [await text(root2, ".agents/mcp_config.json"), await text(root2, ".agents/hooks.json"), await text(root2, ".agents/rules/diacode.md")];
8025
8441
  if (!((t[0] ?? "").includes("/mcp/antigravity") || (t[1] ?? "").includes("/hooks/antigravity/") || t[2] !== null)) return null;
8026
- const mcp = await mcpEntry(root2, ".agents/mcp_config.json", "antigravity", (d) => d?.mcpServers?.dcursed?.serverUrl);
8027
- const hooks = await hooksEntry(root2, [".agents/hooks.json"], "antigravity", ["SessionStart", "PreInvocation", "PostToolUse", "Stop"], (d) => d?.dcursed);
8028
- const enabled = json(t[1])?.dcursed?.enabled;
8442
+ const mcp = await mcpEntry(root2, ".agents/mcp_config.json", "antigravity", (d) => d?.mcpServers?.diacode?.serverUrl);
8443
+ const hooks = await hooksEntry(root2, [".agents/hooks.json"], "antigravity", ["SessionStart", "PreInvocation", "PostToolUse", "Stop"], (d) => d?.diacode);
8444
+ const enabled = json(t[1])?.diacode?.enabled;
8029
8445
  return {
8030
8446
  harness: "antigravity",
8031
8447
  label: "Antigravity",
@@ -8034,7 +8450,7 @@ async function antigravity(root2) {
8034
8450
  mcp.finding,
8035
8451
  hooks.finding,
8036
8452
  ...enabled === false ? [problem("the DiaCode hooks are switched off (`enabled: false` in .agents/hooks.json)", "{init}")] : [],
8037
- await rulesFile(root2, ".agents/rules/dcursed.md", "the agent is not told how to work with the plan"),
8453
+ await rulesFile(root2, ".agents/rules/diacode.md", "the agent is not told how to work with the plan"),
8038
8454
  note("Workspace hooks load only for a trusted folder; trusting it is inside Antigravity, so this cannot see it.")
8039
8455
  ]
8040
8456
  };
@@ -8061,7 +8477,7 @@ async function liveChecks(port2, root2, connections) {
8061
8477
  }
8062
8478
  out.push(ok(`the plan server for this folder is running on port ${port2}`));
8063
8479
  if (typeof health.version === "string" && health.version !== VERSION) {
8064
- out.push(note(`the running server is dcursed ${health.version} and this is ${VERSION}: stop the server and start it again to match, and run \`init\` again if an agent misbehaves`));
8480
+ out.push(note(`the running server is diacode ${health.version} and this is ${VERSION}: stop the server and start it again to match, and run \`init\` again if an agent misbehaves`));
8065
8481
  }
8066
8482
  try {
8067
8483
  const res = await fetch(`${base}/app/`, { signal: AbortSignal.timeout(1500) });
@@ -8085,13 +8501,32 @@ async function liveChecks(port2, root2, connections) {
8085
8501
  if (session) await fetch(door, { method: "DELETE", headers: { "mcp-session-id": session }, signal: AbortSignal.timeout(1e3) }).catch(() => {
8086
8502
  });
8087
8503
  const n = tools.body?.result?.tools?.length ?? 0;
8088
- out.push(init.body?.result?.serverInfo?.name === "dcursed" && n > 0 ? ok(`${c.label}: the MCP door /mcp/${c.harness} opens and offers ${n} tools`) : problem(`${c.label}: the MCP door /mcp/${c.harness} did not answer like a DiaCode server`));
8504
+ out.push(init.body?.result?.serverInfo?.name === "diacode" && n > 0 ? ok(`${c.label}: the MCP door /mcp/${c.harness} opens and offers ${n} tools`) : problem(`${c.label}: the MCP door /mcp/${c.harness} did not answer like a DiaCode server`));
8089
8505
  } catch (e) {
8090
8506
  out.push(problem(`${c.label}: the MCP door /mcp/${c.harness} failed (${e instanceof Error ? e.message : e})`));
8091
8507
  }
8092
8508
  }
8093
8509
  return out;
8094
8510
  }
8511
+ async function replannerFindings(port2, connections) {
8512
+ let health = null;
8513
+ try {
8514
+ health = await (await fetch(`http://127.0.0.1:${port2}/api/health`, { signal: AbortSignal.timeout(1500) })).json();
8515
+ } catch {
8516
+ }
8517
+ if (health?.replanner === "opencode") {
8518
+ return [
8519
+ note("the re-plan buttons run a separate OpenCode session (the plan server was started with --reconcile or --reconciler-model); each ask is a model call"),
8520
+ onPath("opencode") ? note("opencode is on the PATH. Whether it is signed in is not checked here: if a button says it is not, run `opencode auth login`") : problem("opencode is not on the PATH, so the re-plan buttons cannot run it", "install OpenCode, or start the plan server without --reconcile and --reconciler-model so the buttons ask your agent")
8521
+ ];
8522
+ }
8523
+ const wakes = connections.filter((c) => c.harness === "claude-code" || c.harness === "opencode").map((c) => c.label);
8524
+ const others = connections.filter((c) => c.harness === "cursor" || c.harness === "antigravity").map((c) => c.label);
8525
+ return [
8526
+ wakes.length ? ok(`the re-plan buttons ask ${wakes.join(" or ")} (the agent you connected): it is woken and proposes the change, or says none is needed`) : note("the re-plan buttons ask the agent you connected, but none here can be woken by the editor: the editor then says so, and offers to add the file to a step or ignore it"),
8527
+ ...others.length ? [note(`${others.join(" and ")} cannot be woken by the editor, so a re-plan button there only says so; ask it yourself in its window`)] : []
8528
+ ];
8529
+ }
8095
8530
  async function diagnose({ root: root2, port: port2 }) {
8096
8531
  root2 = resolve4(root2);
8097
8532
  const sections = [];
@@ -8099,10 +8534,12 @@ async function diagnose({ root: root2, port: port2 }) {
8099
8534
  const basics = [major >= 22 ? ok(`Node ${process.versions.node}`) : problem(`Node ${process.versions.node}: DiaCode needs Node 22 or newer`, "install a current Node from nodejs.org")];
8100
8535
  let plans = 0;
8101
8536
  try {
8102
- plans = (await readdir3(join5(root2, ".dcursed", "plans"))).filter((f) => f.endsWith(".plan.json")).length;
8537
+ plans = (await readdir4(join6(root2, ".diacode", "plans"))).filter((f) => f.endsWith(".plan.json")).length;
8103
8538
  } catch {
8104
8539
  }
8105
- basics.push(plans ? ok(`${plans} plan${plans === 1 ? "" : "s"} in .dcursed/plans`) : note("no plans yet: ask an agent to draft one, or use New plan or Import\u2026 in the editor"));
8540
+ basics.push(plans ? ok(`${plans} plan${plans === 1 ? "" : "s"} in .diacode/plans`) : note("no plans yet: ask an agent to draft one, or use New plan or Import\u2026 in the editor"));
8541
+ const legacy = await legacyFound(root2);
8542
+ if (legacy.length) basics.push(problem(`this repository still has what DiaCode 0.2 (then called DcurseD) wrote: ${legacy.join("; ")}`, `${invocation()} migrate, then ${invocation()} init <agent> again`));
8106
8543
  sections.push({ title: root2, findings: basics });
8107
8544
  const connections = (
8108
8545
  /** @type {Connection[]} */
@@ -8121,7 +8558,7 @@ async function diagnose({ root: root2, port: port2 }) {
8121
8558
  }
8122
8559
  sections.push({ title: "The plan server", findings: await liveChecks(chosen, root2, connections) });
8123
8560
  for (const c of connections) sections.push({ title: c.label, findings: c.findings });
8124
- sections.push({ title: "The reconciler", findings: [onPath("opencode") ? ok('opencode is on the PATH, so "Ask the reconciler" can run (each ask is a model call)') : note(`opencode is not on the PATH: the Review panel's "Ask the reconciler" and "Re-plan from this" need it. Agents and the editor work without it.`)] });
8561
+ sections.push({ title: "The re-planner", findings: await replannerFindings(chosen, connections) });
8125
8562
  const flags = `${resolve4(root2) === process.cwd() ? "" : ` --root ${root2}`} --port ${chosen}`;
8126
8563
  for (const s of sections) {
8127
8564
  const harness = connections.find((c) => c.label === s.title)?.harness;
@@ -8162,7 +8599,7 @@ async function issueReport({ root: root2, port: port2 }) {
8162
8599
  "",
8163
8600
  "What the server has noticed",
8164
8601
  ...seen ? [
8165
- ` dcursed ${seen.version}, API ${seen.api}, up ${seen.uptimeSeconds} s, ${seen.plans} plan${seen.plans === 1 ? "" : "s"}`,
8602
+ ` diacode ${seen.version}, API ${seen.api}, up ${seen.uptimeSeconds} s, ${seen.plans} plan${seen.plans === 1 ? "" : "s"}`,
8166
8603
  ...seen.events?.length ? seen.events.map((e) => ` ${e.at} ${e.kind}: ${e.message}`) : [" nothing since it started"]
8167
8604
  ] : [" (no server answered on this port, or it is too old to say)"]
8168
8605
  ];
@@ -8176,11 +8613,11 @@ async function issueReport({ root: root2, port: port2 }) {
8176
8613
 
8177
8614
  // packages/server/src/lock.js
8178
8615
  import { createHash } from "node:crypto";
8179
- import { readFile as readFile6, unlink, writeFile as writeFile3 } from "node:fs/promises";
8616
+ import { readFile as readFile7, unlink, writeFile as writeFile4 } from "node:fs/promises";
8180
8617
  import { readFileSync as readFileSync2, unlinkSync } from "node:fs";
8181
8618
  import { tmpdir } from "node:os";
8182
- import { join as join6, resolve as resolve5 } from "node:path";
8183
- var lockPath = (root2) => join6(tmpdir(), `dcursed-${createHash("sha256").update(resolve5(root2)).digest("hex").slice(0, 16)}.lock`);
8619
+ import { join as join7, resolve as resolve5 } from "node:path";
8620
+ var lockPath = (root2) => join7(tmpdir(), `diacode-${createHash("sha256").update(resolve5(root2)).digest("hex").slice(0, 16)}.lock`);
8184
8621
  function alive(pid) {
8185
8622
  try {
8186
8623
  process.kill(pid, 0);
@@ -8195,7 +8632,7 @@ function alive(pid) {
8195
8632
  async function holder(root2) {
8196
8633
  let info;
8197
8634
  try {
8198
- info = JSON.parse(await readFile6(lockPath(root2), "utf8"));
8635
+ info = JSON.parse(await readFile7(lockPath(root2), "utf8"));
8199
8636
  } catch {
8200
8637
  return null;
8201
8638
  }
@@ -8215,7 +8652,7 @@ async function takeLock(root2, about) {
8215
8652
  const info = { pid: process.pid, port: about.port, version: about.version, root: resolve5(root2), startedAt: (/* @__PURE__ */ new Date()).toISOString() };
8216
8653
  for (let attempt = 0; attempt < 3; attempt++) {
8217
8654
  try {
8218
- await writeFile3(path, JSON.stringify(info), { flag: "wx" });
8655
+ await writeFile4(path, JSON.stringify(info), { flag: "wx" });
8219
8656
  const sweep = () => {
8220
8657
  try {
8221
8658
  if (JSON.parse(readFileSync2(path, "utf8")).pid === process.pid) unlinkSync(path);
@@ -8227,7 +8664,7 @@ async function takeLock(root2, about) {
8227
8664
  release: async () => {
8228
8665
  process.off("exit", sweep);
8229
8666
  try {
8230
- if (JSON.parse(await readFile6(path, "utf8")).pid === process.pid) await unlink(path);
8667
+ if (JSON.parse(await readFile7(path, "utf8")).pid === process.pid) await unlink(path);
8231
8668
  } catch {
8232
8669
  }
8233
8670
  }
@@ -8248,23 +8685,30 @@ async function takeLock(root2, about) {
8248
8685
  throw new Error(`could not take the lock ${path}`);
8249
8686
  }
8250
8687
 
8251
- // packages/server/bin/dcursed.js
8688
+ // packages/server/bin/diacode.js
8252
8689
  var args = process.argv.slice(2);
8253
8690
  var cmd = invocation();
8254
8691
  var usage = [
8255
8692
  `diacode ${VERSION}: a plan you and your coding agents share`,
8256
8693
  "",
8257
- `usage: ${cmd} init <opencode|claude-code|cursor|antigravity|all> [--root <repo>] [--port 7300] [--agent <name>] [--shared] [--remove]`,
8694
+ `usage: ${cmd} init <opencode|claude-code|cursor|antigravity|all> [--root <repo>] [--port 7300] [--agent <name>] [--shared] [--accept-edits] [--remove]`,
8258
8695
  " connect a repository to an agent (its MCP entry, hooks or plugin, and rules);",
8259
- " --shared puts Claude Code's hooks in the committed .claude/settings.json, not your own settings.local.json",
8696
+ " --shared puts Claude Code's hooks in the committed .claude/settings.json, not your own settings.local.json;",
8697
+ " --accept-edits (Claude Code only, off unless you ask) sets its mode to accept edits in settings.local.json: it then edits files in",
8698
+ " the folder, and runs mkdir, touch, rm, rmdir, mv, cp and sed there, without asking; --remove takes it out again",
8260
8699
  " --remove takes out again only what init wrote, and leaves your plans and your own settings",
8261
8700
  ` ${cmd} serve [--root <repo>] [--port 7300] [--reconcile auto|manual] [--reconciler-model <provider/model>]`,
8262
- " the plan server, and the editor at http://127.0.0.1:<port>/",
8701
+ " the plan server, and the editor at http://127.0.0.1:<port>/;",
8702
+ ' "Should the plan cover this?" and the other re-plan buttons ask the agent you connected; --reconcile or --reconciler-model',
8703
+ " make them run a separate OpenCode session instead (OpenCode must be installed and signed in)",
8263
8704
  ` ${cmd} doctor [--root <repo>] [--port <n>] [--report]`,
8264
8705
  " check that the repository, the agents and the server fit together;",
8265
8706
  " --report prints the findings with what the server has noticed, paths replaced, to paste into an issue",
8266
8707
  ` ${cmd} import <file.plan.md | file.md | file.mmd> [--root <repo>] [--id <plan-id>] [--title <title>]`,
8267
8708
  " bring in a Cursor plan, markdown with a Mermaid block, or a bare Mermaid file",
8709
+ ` ${cmd} migrate [--root <repo>]`,
8710
+ " a repository set up by DiaCode 0.2 (then called DcurseD): move its plans from .dcursed/ to .diacode/ and take the old",
8711
+ " entries out of the agents' settings; then run init again. (init does this too, first.)",
8268
8712
  ` ${cmd} --version`
8269
8713
  ].join("\n");
8270
8714
  var option = (name2, fallback) => {
@@ -8293,7 +8737,22 @@ if (args[0] === "--version" || args[0] === "-v" || args[0] === "version") {
8293
8737
  const report = await diagnose({ root, ...option("port") ? { port } : {} });
8294
8738
  console.log(formatReport(report));
8295
8739
  process.exitCode = report.problems ? 1 : 0;
8740
+ } else if (args[0] === "migrate") {
8741
+ const found = await legacyFound(root);
8742
+ if (!found.length) console.log(`Nothing to migrate: ${root} has nothing under the old DcurseD name.`);
8743
+ else {
8744
+ for (const line of await migrate(root)) console.log(line);
8745
+ console.log(`
8746
+ Now connect your agent again, so that it uses the new name: ${cmd} init <opencode|claude-code|cursor|antigravity|all>
8747
+ and restart its session.`);
8748
+ }
8296
8749
  } else if (args[0] === "serve") {
8750
+ if (await legacyFound(root).then((f) => f.some((l) => l.startsWith("the .dcursed/")))) {
8751
+ console.error(`This folder still keeps its plans in .dcursed/, where DiaCode 0.2 (then called DcurseD) put them.
8752
+ Move them first: ${cmd} migrate${root === resolve6(".") ? "" : ` --root ${root}`}
8753
+ then connect your agent again: ${cmd} init <agent>`);
8754
+ process.exit(1);
8755
+ }
8297
8756
  const origins = args.flatMap((a, i) => a === "--allow-origin" && args[i + 1] ? [args[i + 1]] : []);
8298
8757
  const server = createServer({
8299
8758
  root,
@@ -8301,7 +8760,8 @@ if (args[0] === "--version" || args[0] === "-v" || args[0] === "version") {
8301
8760
  // Itself and nothing else, unless told: any page on a port such as :8080 is some other program's.
8302
8761
  // (`npm run dev` needs no flag: Vite's proxy presents the server's own origin for the dev page.)
8303
8762
  allowedOrigins: origins,
8304
- reconciler: { auto: option("reconcile", "manual") === "auto", model: option("reconciler-model"), bin: option("opencode") },
8763
+ // The re-planner buttons ask the agent you connected. OpenCode does that job only when you set it up for it, here.
8764
+ reconciler: { enabled: args.includes("--reconcile") || args.includes("--reconciler-model") || args.includes("--opencode"), auto: option("reconcile", "manual") === "auto", model: option("reconciler-model"), bin: option("opencode") },
8305
8765
  ...option("editor") ? { editor: resolve6(
8306
8766
  /** @type {string} */
8307
8767
  option("editor")
@@ -8334,7 +8794,7 @@ Pick another one: ${cmd} serve --port ${port + 1} (and ${cmd} init <harness>
8334
8794
  const lock = await takeLock(root, { port: actual, version: VERSION });
8335
8795
  if ("held" in lock) {
8336
8796
  await server.close();
8337
- console.error(`The plan server for this folder is already running: http://127.0.0.1:${lock.held.port}/ (pid ${lock.held.pid}, dcursed ${lock.held.version}).
8797
+ console.error(`The plan server for this folder is already running: http://127.0.0.1:${lock.held.port}/ (pid ${lock.held.pid}, diacode ${lock.held.version}).
8338
8798
  Two servers on one folder would overwrite each other, so this one did not start.
8339
8799
  Use that one, or stop it first (Ctrl-C in its terminal, or kill ${lock.held.pid}) and run this again.`);
8340
8800
  process.exit(1);
@@ -8355,13 +8815,25 @@ Use that one, or stop it first (Ctrl-C in its terminal, or kill ${lock.held.pid}
8355
8815
  } else if (args[0] === "init" && args[1] && (args[1] === "all" || args[1] in HARNESS_INIT)) {
8356
8816
  const which = args[1] === "all" ? Object.keys(HARNESS_INIT) : [args[1]];
8357
8817
  const remove = args.includes("--remove");
8818
+ if (args.includes("--accept-edits") && !which.includes("claude-code")) {
8819
+ console.error("--accept-edits is for Claude Code: use it with `init claude-code` (or `init all`).");
8820
+ process.exit(1);
8821
+ }
8822
+ if (args.includes("--accept-edits") && remove) {
8823
+ console.error("--accept-edits is for adding it; `init claude-code --remove` takes it out again.");
8824
+ process.exit(1);
8825
+ }
8826
+ if (!remove && (await legacyFound(root)).length) {
8827
+ console.log("\u2500\u2500 moving from DcurseD (DiaCode 0.2)");
8828
+ for (const line of await migrate(root)) console.log(line);
8829
+ }
8358
8830
  for (const h of which) {
8359
8831
  console.log(`\u2500\u2500 ${h}`);
8360
8832
  if (remove) {
8361
8833
  for (const line of await HARNESS_REMOVE[h]({ root })) console.log(line);
8362
8834
  continue;
8363
8835
  }
8364
- for (const line of await HARNESS_INIT[h]({ root, port, ...option("agent") ? { agent: option("agent") } : {}, shared: args.includes("--shared") })) console.log(line);
8836
+ for (const line of await HARNESS_INIT[h]({ root, port, ...option("agent") ? { agent: option("agent") } : {}, shared: args.includes("--shared"), ...h === "claude-code" && args.includes("--accept-edits") ? { acceptEdits: true } : {} })) console.log(line);
8365
8837
  }
8366
8838
  if (remove) console.log(`
8367
8839
  Plans stay where they are: ${plansDir(root)}`);