diacode 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/dcursed.js CHANGED
@@ -118,7 +118,7 @@ var STATUSES = (
118
118
  );
119
119
  var PHASES = (
120
120
  /** @type {const} */
121
- ["planning", "executing", "paused", "done", "abandoned"]
121
+ ["planning", "approved", "executing", "paused", "done", "abandoned"]
122
122
  );
123
123
  var KINDS = ["task", "context"];
124
124
  var EDGE_KINDS = (
@@ -134,6 +134,10 @@ var isString = (v, min = 0, max = Infinity) => typeof v === "string" && v.length
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
143
  return isObject(plan) && OLDER.includes(plan.schema) ? { ...plan, schema: SCHEMA } : plan;
@@ -197,11 +201,12 @@ function validatePlan(plan) {
197
201
  problems.push(`${at}: not an object`);
198
202
  return;
199
203
  }
200
- onlyKeys(e, ["from", "to", "label", "kind", "question", "passed", "answer"], at, problems);
204
+ onlyKeys(e, ["from", "to", "label", "kind", "question", "options", "passed", "answer"], at, problems);
201
205
  if (e.label !== void 0 && !isString(e.label, 0, 120)) problems.push(`${at}: label is at most 120 characters`);
202
206
  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
207
  const checkpoint2 = CHECKPOINTS.has(e.kind);
204
208
  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`);
209
+ if (e.options !== void 0 && (e.kind !== "ask" || !isOptionList(e.options))) problems.push(`${at}: only an "ask" checkpoint has options; ${OPTIONS_PROBLEM}`);
205
210
  if (e.passed !== void 0 && (!checkpoint2 || e.passed !== true)) problems.push(`${at}: only a checkpoint is passed, and passed is true`);
206
211
  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
212
  if (!(e.from in plan.nodes)) problems.push(`${at}: "${e.from}" is not a step`);
@@ -237,15 +242,15 @@ var OPS = {
237
242
  "node.add": { required: ["label"], optional: ["id", "kind", "detail", "group", "files", "touches", "after"], ids: ["id"] },
238
243
  "node.set": { required: ["id"], optional: ["label", "kind", "detail", "group", "files", "touches"], ids: ["id"], oneOf: ["label", "kind", "detail", "group", "files", "touches"] },
239
244
  "node.remove": { required: ["id"], ids: ["id"] },
240
- "edge.add": { required: ["from", "to"], optional: ["label", "kind"], ids: ["from", "to"] },
245
+ "edge.add": { required: ["from", "to"], optional: ["label", "kind", "options"], ids: ["from", "to"] },
241
246
  "edge.remove": { required: ["from", "to"], ids: ["from", "to"] },
242
247
  "edge.rewire": { required: ["from", "to"], optional: ["newFrom", "newTo"], ids: ["from", "to", "newFrom", "newTo"], oneOf: ["newFrom", "newTo"] },
243
248
  "edge.reverse": { required: ["from", "to"], ids: ["from", "to"] },
244
- "edge.set": { required: ["from", "to"], optional: ["label", "kind"], ids: ["from", "to"], oneOf: ["label", "kind"] },
249
+ "edge.set": { required: ["from", "to"], optional: ["label", "kind", "options"], ids: ["from", "to"], oneOf: ["label", "kind", "options"] },
245
250
  // A checkpoint: you pass it (with your answer or input), an agent asks its question at an `ask`, and an approval
246
251
  // you withhold sends the step before it back.
247
252
  "gate.pass": { required: ["from", "to"], optional: ["answer"], ids: ["from", "to"] },
248
- "gate.ask": { required: ["from", "to", "question"], ids: ["from", "to"] },
253
+ "gate.ask": { required: ["from", "to", "question"], optional: ["options"], ids: ["from", "to"] },
249
254
  "gate.reject": { required: ["from", "to"], optional: ["reason"], ids: ["from", "to"] },
250
255
  "status.set": { required: ["id", "status"], optional: ["note"], ids: ["id"] },
251
256
  claim: { required: ["id"], ids: ["id"] },
@@ -279,6 +284,7 @@ function validateOp(op) {
279
284
  }
280
285
  if (op.question !== void 0 && !isString(op.question, 1, NOTE_MAX)) problems.push(`${op.op}: question is 1-${NOTE_MAX} characters`);
281
286
  if (op.answer !== void 0 && !isString(op.answer, 0, NOTE_MAX)) problems.push(`${op.op}: answer is at most ${NOTE_MAX} characters`);
287
+ if (op.options !== void 0 && !isOptionList(op.options)) problems.push(`${op.op}: ${OPTIONS_PROBLEM}`);
282
288
  if (op.files !== void 0 && !isFileList(op.files)) problems.push(`${op.op}: ${FILES_PROBLEM}`);
283
289
  if (op.touches !== void 0 && !isTouches(op.touches)) problems.push(`${op.op}: ${TOUCHES_PROBLEM}`);
284
290
  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`);
@@ -312,12 +318,14 @@ function validateBatch(batch) {
312
318
  var isFinished = (n) => n.kind === "context" || n.status === "done" || n.status === "cancelled";
313
319
  var checkpointsBefore = (plan, id) => plan.edges.filter((e) => e.to === id && CHECKPOINTS.has(e.kind ?? "needs") && !e.passed);
314
320
  var isRunning = (plan) => plan.phase === "executing" || plan.phase === "paused";
321
+ var isApproved = (plan) => plan.phase === "approved" || isRunning(plan);
315
322
  function checkpointWords(e) {
316
323
  if (e.kind === "approve") return `the person to approve ${e.from}'s result`;
317
324
  if (e.kind === "ask") return e.question ? `the person's answer to the question asked before ${e.to}` : `you to ask the person before ${e.to} (step_ask)`;
318
325
  return `input from the person${e.label ? ` (${e.label})` : ""}`;
319
326
  }
320
327
  var isStructural = (op) => STRUCTURAL.has(op.op) || op.op === "plan.set" && (op.title !== void 0 || op.goal !== void 0);
328
+ var notStarted = (p) => p.phase === "approved" ? "the person has approved the plan but has not started it: check the architecture against it and end your turn; they press Start when it is settled" : "the plan is still a draft: the person approves it, then starts it. End your turn and say it is ready for review";
321
329
  var Refusal = class extends Error {
322
330
  };
323
331
  var refuse = (why) => {
@@ -328,7 +336,7 @@ function applyBatch(plan, ops, who) {
328
336
  const problems = validateOp(ops[i]);
329
337
  if (problems.length) return { kind: "rejected", index: i, op: ops[i], why: problems.join("; ") };
330
338
  }
331
- if ((isRunning(plan) || who.propose) && who.actor !== "you" && ops.some(isStructural)) {
339
+ if ((isApproved(plan) || who.propose) && who.actor !== "you" && ops.some(isStructural)) {
332
340
  const structural = ops.filter(isStructural);
333
341
  const rest = ops.filter((op) => !isStructural(op));
334
342
  const dry = run(plan, structural, { ...who, actor: "you" });
@@ -441,7 +449,7 @@ function step(p, op, ctx) {
441
449
  }
442
450
  case "edge.add":
443
451
  if (frozen(op.to)) refuse(`${op.to} is done; what it depended on is history`);
444
- addEdge(p, op.from, op.to, op.label, op.kind);
452
+ addEdge(p, op.from, op.to, op.label, op.kind, op.options);
445
453
  affectFrom(op.to, `now depends on ${op.from}`);
446
454
  return op;
447
455
  case "edge.remove": {
@@ -477,6 +485,10 @@ function step(p, op, ctx) {
477
485
  else e.kind = op.kind;
478
486
  clearCheckpoint(e);
479
487
  }
488
+ if (op.options !== void 0) {
489
+ if (e.kind !== "ask") refuse(`${op.from} \u2192 ${op.to} is not an "ask" checkpoint; only one has options`);
490
+ e.options = op.options;
491
+ }
480
492
  return op;
481
493
  }
482
494
  case "gate.pass": {
@@ -493,6 +505,7 @@ function step(p, op, ctx) {
493
505
  if (e.kind !== "ask") refuse(`${op.from} \u2192 ${op.to} is an "${e.kind}" checkpoint; only an "ask" one takes a question`);
494
506
  if (e.passed) refuse(`the checkpoint ${op.from} \u2192 ${op.to} is passed already: ${op.to} can start`);
495
507
  e.question = op.question;
508
+ if (op.options !== void 0) e.options = op.options;
496
509
  return op;
497
510
  }
498
511
  case "gate.reject": {
@@ -510,6 +523,7 @@ function step(p, op, ctx) {
510
523
  if (frozen(op.id)) refuse(`${op.id} is done; only you can reopen it`);
511
524
  if (!you && n.owner && n.owner !== who.actor) refuse(`${op.id} is ${n.owner}'s`);
512
525
  if (op.status === "cancelled" && !you) refuse("only you cancel a step; an agent proposes removing it");
526
+ if (op.status === "in_progress" && !you && (p.phase === "planning" || p.phase === "approved")) refuse(notStarted(p));
513
527
  if (op.status === "in_progress" && !you && p.phase === "paused" && n.status !== "in_progress") refuse(`the person paused the plan: start nothing new until they resume it. Finish the step you are on, if any, then end your turn`);
514
528
  if ((op.status === "in_progress" || op.status === "done") && !you) {
515
529
  const waiting = prerequisitesOf(p, op.id).filter((f) => !isFinished(p.nodes[f]));
@@ -535,6 +549,7 @@ function step(p, op, ctx) {
535
549
  if (n.kind === "context") refuse(`${op.id} is context; nobody works on it`);
536
550
  if (!you && n.owner && n.owner !== who.actor) refuse(`${op.id} is ${n.owner}'s`);
537
551
  if (!you && p.phase === "paused" && n.owner !== who.actor) refuse("the person paused the plan: start nothing new until they resume it");
552
+ if (!you && (p.phase === "planning" || p.phase === "approved")) refuse(notStarted(p));
538
553
  n.owner = who.actor;
539
554
  return op;
540
555
  }
@@ -563,7 +578,7 @@ function step(p, op, ctx) {
563
578
  case "plan.stop":
564
579
  if (!you) refuse("only the person stops the plan");
565
580
  if (!isRunning(p)) refuse(`the plan is ${p.phase}, not running: there is nothing to stop`);
566
- p.phase = "planning";
581
+ p.phase = "approved";
567
582
  for (const [id, n] of Object.entries(p.nodes)) {
568
583
  if (n.status === "in_progress" || n.status === "waiting") reopen(p, id, { status: "not_started", note: "stopped by you", who });
569
584
  else if (n.owner) delete n.owner;
@@ -612,12 +627,13 @@ function checkEdge(p, from, to, ignore) {
612
627
  const without = ignore ? { ...p, edges: p.edges.filter((e) => e !== ignore) } : p;
613
628
  if (reaches(without, to, from)) refuse(`${from} \u2192 ${to} would make a loop`);
614
629
  }
615
- function addEdge(p, from, to, label, kind) {
630
+ function addEdge(p, from, to, label, kind, options) {
616
631
  checkEdge(p, from, to);
632
+ if (options && kind !== "ask") refuse('only an "ask" checkpoint has options');
617
633
  p.edges.push({ from, to, ...label ? { label } : {}, ...kind && kind !== "needs" ? { kind: (
618
634
  /** @type {Exclude<import('./types.js').EdgeKind, 'needs'>} */
619
635
  kind
620
- ) } : {} });
636
+ ) } : {}, ...options ? { options } : {} });
621
637
  }
622
638
  function checkpoint(p, from, to) {
623
639
  const e = findEdge(p, from, to);
@@ -626,6 +642,7 @@ function checkpoint(p, from, to) {
626
642
  }
627
643
  function clearCheckpoint(e) {
628
644
  delete e.question;
645
+ delete e.options;
629
646
  delete e.passed;
630
647
  delete e.answer;
631
648
  }
@@ -657,7 +674,7 @@ function derive(plan) {
657
674
  gates.push({ from: e.from, to: e.to, kind: (
658
675
  /** @type {Gate['kind']} */
659
676
  e.kind
660
- ), ...e.label ? { label: e.label } : {}, ...e.question ? { question: e.question } : {}, turn });
677
+ ), ...e.label ? { label: e.label } : {}, ...e.question ? { question: e.question } : {}, ...e.question && e.options ? { options: e.options } : {}, turn });
661
678
  }
662
679
  if (waiting.length) blocked.set(id, waiting);
663
680
  else if (at.length) held.set(id, at.map((e) => e.from));
@@ -777,7 +794,7 @@ function opposite(reason) {
777
794
  var ORDER = {
778
795
  plan: ["schema", "id", "title", "goal", "rev", "phase", "source", "nodes", "edges", "proposals"],
779
796
  node: ["label", "kind", "group", "detail", "status", "statusFrom", "statusBy", "note", "owner", "files", "touches"],
780
- edge: ["from", "to", "kind", "label", "question", "passed", "answer"],
797
+ edge: ["from", "to", "kind", "label", "question", "options", "passed", "answer"],
781
798
  proposal: ["id", "by", "at", "reason", "ops"],
782
799
  layout: ["schema", "plan", "direction", "canvas", "collapsed", "nodes"],
783
800
  place: ["x", "y", "pinned"]
@@ -923,7 +940,7 @@ function diffToOps(before, after, { bridge = false } = {}) {
923
940
  }
924
941
  }
925
942
  }
926
- for (const c of came) ops.push(pick({ op: "edge.add", from: c.from, to: c.to, label: c.label, kind: c.kind }));
943
+ 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 }));
927
944
  for (const [k, e] of afterEdges) {
928
945
  const was = beforeEdges.get(k);
929
946
  const set = was && edgeChange(was, e);
@@ -946,7 +963,8 @@ function diffToOps(before, after, { bridge = false } = {}) {
946
963
  const was = beforeEdges.get(k) ?? /** @type {import('./types.js').Edge} */
947
964
  { from: e.from, to: e.to };
948
965
  const reset = kindOf(was) !== kindOf(e);
949
- 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 });
966
+ 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 } : {} });
967
+ 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 });
950
968
  if (e.passed && (reset || !was.passed)) ops.push(pick({ op: "gate.pass", from: e.from, to: e.to, answer: e.answer }));
951
969
  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)`);
952
970
  }
@@ -1146,7 +1164,7 @@ function arrange(items, depends, direction, lanes = false) {
1146
1164
  /** @type {Item} */
1147
1165
  all.find((i) => i.id === id)
1148
1166
  );
1149
- const flowOf = (b) => direction === "LR" ? b.w : b.h;
1167
+ const flowOf2 = (b) => direction === "LR" ? b.w : b.h;
1150
1168
  const crossOf = (b) => direction === "LR" ? b.h : b.w;
1151
1169
  const slot = Math.max(...items.map(crossOf)) + g.cross;
1152
1170
  const members = (k) => (
@@ -1162,7 +1180,7 @@ function arrange(items, depends, direction, lanes = false) {
1162
1180
  let cursor2 = 0;
1163
1181
  let lastGap = 0;
1164
1182
  for (const k of ranks) {
1165
- const thick = Math.max(...members(k).map((id) => flowOf(sizeOf(id))));
1183
+ const thick = Math.max(...members(k).map((id) => flowOf2(sizeOf(id))));
1166
1184
  flowAt.set(k, cursor2 + thick / 2);
1167
1185
  lastGap = direction === "LR" ? Math.max(g.gap, labelAfter(k)) : g.gap;
1168
1186
  cursor2 += thick + lastGap;
@@ -1417,13 +1435,14 @@ function describeAttention({ lines, plan, actor, since }) {
1417
1435
  if (op.phase !== void 0 && op.phase !== phase) {
1418
1436
  if (news && op.phase === "paused") say(`${who} paused the plan. ${held.size ? `Finish the step you are on (${[...held].join(", ")}), then` : "Start"} nothing new, and end your turn. You are told when it resumes.`);
1419
1437
  else if (news && op.phase === "executing" && phase === "paused") say(`${who} resumed the plan. Read it with plan_read and carry on.`);
1438
+ else if (news && op.phase === "executing" && phase === "approved") say(`${who} started the plan. Read it with plan_read and carry it out, one step at a time.`);
1420
1439
  phase = op.phase;
1421
1440
  }
1422
1441
  break;
1423
1442
  case "plan.stop":
1424
- if (news) say(`${who} STOPPED the plan. Stop now: do not finish the step you are on, and end your turn. The plan is back in planning; what was in progress was put back.`);
1443
+ if (news) say(`${who} STOPPED the plan. Stop now: do not finish the step you are on, and end your turn. The plan is back to approved, waiting for them to press Start; what was in progress was put back.`);
1425
1444
  held.clear();
1426
- phase = "planning";
1445
+ phase = "approved";
1427
1446
  break;
1428
1447
  case "gate.pass":
1429
1448
  if (news && (asked.has(`${op.from}\0${op.to}`) || finished.has(op.from))) {
@@ -1468,7 +1487,7 @@ function arrowIn(e) {
1468
1487
  if (!e.kind) return e.from;
1469
1488
  const bits = [KIND[e.kind]];
1470
1489
  if (e.kind === "input" && e.label) bits.push(quote(e.label, 80));
1471
- if (e.question) bits.push(`asked ${quote(e.question, 160)}`);
1490
+ if (e.question) bits.push(`asked ${quote(e.question, 160)}${e.options?.length ? `, offering ${e.options.map((o) => quote(o, 60)).join(" / ")}` : ""}`);
1472
1491
  if (e.passed) bits.push(e.answer ? `PASSED, the person said ${quote(e.answer, 300)}` : "PASSED");
1473
1492
  return `${e.from} (${bits.join("; ")})`;
1474
1493
  }
@@ -1505,7 +1524,7 @@ function describeOp(op) {
1505
1524
  case "gate.pass":
1506
1525
  return `the checkpoint ${op.from} \u2192 ${op.to} is passed${op.answer ? `: ${quote(op.answer, 300)}` : ""}; ${op.to} may start`;
1507
1526
  case "gate.ask":
1508
- return `asked the person before ${op.to}: ${quote(op.question, 300)}`;
1527
+ return `asked the person before ${op.to}: ${quote(op.question, 300)}${op.options?.length ? `, offering ${op.options.map((o) => quote(o, 60)).join(" / ")}` : ""}`;
1509
1528
  case "gate.reject":
1510
1529
  return `${op.from} was sent back, not approved${op.reason ? ` (${quote(op.reason, 300)})` : ""}: it is to be done again`;
1511
1530
  case "status.set":
@@ -1960,6 +1979,54 @@ function importDiagram(text2, filename = "") {
1960
1979
  };
1961
1980
  }
1962
1981
 
1982
+ // packages/core/src/flow.js
1983
+ var AT = { task: 0, architecture: 1, "plan-wait": 2, plan: 2, start: 3, running: 4, done: 5 };
1984
+ function activePlan(plans) {
1985
+ for (const group of [["executing", "paused"], ["approved"], ["planning"]]) {
1986
+ const found = plans.filter((p) => group.includes(p.phase));
1987
+ if (found.length) return found[found.length - 1];
1988
+ }
1989
+ return void 0;
1990
+ }
1991
+ function flowOf({ arch: arch2, plan, waiting = 0, busy = false, finished = false }) {
1992
+ const live = plan && plan.phase !== "done" && plan.phase !== "abandoned" ? plan : void 0;
1993
+ const at = (stage, next, label, line, why) => ({ stage, at: AT[stage], next, label, why, line });
1994
+ if (live && (live.phase === "executing" || live.phase === "paused")) {
1995
+ return at("running", null, "", live.phase === "paused" ? "Paused. Edit the plan or the architecture, then Resume: your agent is told what changed on both sides." : "Running. What you change on the plan or the architecture is told to your agent, which proposes the matching change on the other side.");
1996
+ }
1997
+ if (arch2?.phase === "draft") {
1998
+ return at(
1999
+ "architecture",
2000
+ "approveArchitecture",
2001
+ "Approve architecture",
2002
+ live ? "Look the architecture over and change what is wrong, then approve it. The plan your agent drafted waits for this: it is checked against what you approve." : "Look the architecture over and change what is wrong, then approve it. Your agent draws the plan on what you approve."
2003
+ );
2004
+ }
2005
+ if (live?.phase === "approved") {
2006
+ const why = busy ? "your agent is still at work" : waiting ? `${waiting} change${waiting === 1 ? "" : "s"} your agent proposed ${waiting === 1 ? "waits" : "wait"} for you: accept or reject ${waiting === 1 ? "it" : "them"} first` : void 0;
2007
+ return at(
2008
+ "start",
2009
+ "start",
2010
+ "Start",
2011
+ busy ? "Your agent is still at work: checking the architecture against the plan (and proposing what it needs to change), or stopping. Start is free once it has stopped." : waiting ? `Look at the ${waiting} change${waiting === 1 ? "" : "s"} your agent proposed: accept or reject ${waiting === 1 ? "it" : "each"}, then Start.` : "The architecture and the plan agree. Press Start when you are happy with both; your agent carries the plan out.",
2012
+ why
2013
+ );
2014
+ }
2015
+ if (live) {
2016
+ return at(
2017
+ "plan",
2018
+ "approvePlan",
2019
+ "Approve plan",
2020
+ "Look the plan over and change what is wrong, then approve it. Your agent then checks the architecture against it and proposes what needs to change."
2021
+ );
2022
+ }
2023
+ if (arch2?.phase === "accepted") {
2024
+ if (waiting && !busy) return at("plan-wait", null, "", `Your agent proposed ${waiting} change${waiting === 1 ? "" : "s"} to the architecture: accept or reject ${waiting === 1 ? "it" : "each"}, then it draws the plan.`);
2025
+ return at("plan-wait", null, "", busy ? "Your agent is drawing the plan on the architecture you approved." : finished ? "The last plan is done. Give your agent the next task: it draws the plan on this architecture, and you approve it." : "The architecture is approved. Your agent draws the plan on it; if nothing happens, ask it for the plan.");
2026
+ }
2027
+ return at("task", null, "", busy ? "Your agent is drawing the architecture." : "Give your agent the task. It draws the architecture here first, and you approve it.");
2028
+ }
2029
+
1963
2030
  // packages/core/src/arch/index.js
1964
2031
  var arch_exports = {};
1965
2032
  __export(arch_exports, {
@@ -2318,7 +2385,8 @@ function applyBatch2(arch2, ops, who) {
2318
2385
  const problems = validateOp2(ops[i]);
2319
2386
  if (problems.length) return { kind: "rejected", index: i, op: ops[i], why: problems.join("; ") };
2320
2387
  }
2321
- if ((arch2.phase === "accepted" || who.propose) && who.actor !== "you" && ops.some(isStructural2)) {
2388
+ const bookkeeping = who.actor.startsWith("server:") && !who.propose;
2389
+ if ((arch2.phase === "accepted" || who.propose) && who.actor !== "you" && !bookkeeping && ops.some(isStructural2)) {
2322
2390
  const structural = ops.filter(isStructural2);
2323
2391
  const rest = ops.filter((op) => !isStructural2(op));
2324
2392
  const dry = run2(arch2, structural, { ...who, actor: "you" });
@@ -3323,6 +3391,7 @@ var HttpError = class extends Error {
3323
3391
  };
3324
3392
  var DRIFT_IGNORED = /(^|\/)(\.dcursed|\.opencode|\.git|node_modules|dist|build|coverage)\/|(^|\/)(package-lock\.json|yarn\.lock|pnpm-lock\.yaml)$/;
3325
3393
  var same3 = (a, b) => JSON.stringify(canonicalPlan(a)) === JSON.stringify(canonicalPlan(b));
3394
+ var LIVE = /* @__PURE__ */ new Set(["planning", "approved", "executing", "paused"]);
3326
3395
  var PlanStore = class extends EventEmitter {
3327
3396
  /**
3328
3397
  * @param {string} root the repository; plans live in <root>/.dcursed/plans/
@@ -3521,7 +3590,7 @@ var PlanStore = class extends EventEmitter {
3521
3590
  * @param {string} actor @returns {string | undefined}
3522
3591
  */
3523
3592
  planFor(actor) {
3524
- const live = [...this.entries].filter(([, e]) => e.plan && (e.plan.phase === "planning" || e.plan.phase === "executing"));
3593
+ const live = [...this.entries].filter(([, e]) => e.plan && LIVE.has(e.plan.phase));
3525
3594
  if (live.length === 1) return live[0][0];
3526
3595
  const latest = ([, e]) => e.log.filter((l) => l.actor === actor).at(-1)?.at ?? "";
3527
3596
  const newest = (list) => [...list].sort((a, b) => latest(b).localeCompare(latest(a)))[0]?.[0];
@@ -3543,7 +3612,10 @@ var PlanStore = class extends EventEmitter {
3543
3612
  return view.plan ? { text: describeBrief(view), plan: id, rev: view.rev } : { text: "" };
3544
3613
  };
3545
3614
  if (planId) return one(planId);
3546
- const live = this.list().filter((p) => p.title !== void 0 && (p.phase === "planning" || p.phase === "executing"));
3615
+ const live = this.list().filter((p) => p.title !== void 0 && LIVE.has(
3616
+ /** @type {string} */
3617
+ p.phase
3618
+ ));
3547
3619
  if (!live.length) return { text: "" };
3548
3620
  if (live.length === 1) return one(live[0].id);
3549
3621
  const mine = actor ? this.planFor(actor) : void 0;
@@ -3576,6 +3648,19 @@ var PlanStore = class extends EventEmitter {
3576
3648
  );
3577
3649
  this.emit("drift", { id });
3578
3650
  }
3651
+ /**
3652
+ * 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.
3653
+ * @param {string} id @param {string} [file] none: all of them
3654
+ * @returns {number} how many were let go
3655
+ */
3656
+ ignoreOutside(id, file) {
3657
+ const files = this.outside.get(id);
3658
+ if (!files) return 0;
3659
+ const gone = file === void 0 ? files.size : Number(files.delete(file));
3660
+ if (file === void 0) files.clear();
3661
+ if (gone) this.emit("drift", { id });
3662
+ return gone;
3663
+ }
3579
3664
  /**
3580
3665
  * The files agents have edited that no step lists *now* (a step that has since come to list one
3581
3666
  * covers it), newest first: what the plan has drifted from. @param {string} id
@@ -3746,6 +3831,8 @@ import { EventEmitter as EventEmitter2 } from "node:events";
3746
3831
  import { watch as watch2, mkdirSync as mkdirSync2 } from "node:fs";
3747
3832
  var arch = arch_exports;
3748
3833
  var FOOTPRINT_ACTOR = "server:footprint";
3834
+ var PLAN_ACTOR = "server:plan";
3835
+ var PLAN_TO_COME = "next";
3749
3836
  var same4 = (a, b) => JSON.stringify(arch.canonicalArch(a)) === JSON.stringify(arch.canonicalArch(b));
3750
3837
  var newLayout2 = () => newLayout(arch.LAYOUT_OF);
3751
3838
  var ArchStore = class extends EventEmitter2 {
@@ -3911,6 +3998,22 @@ var ArchStore = class extends EventEmitter2 {
3911
3998
  since(baseRev) {
3912
3999
  return this.log.filter((l) => l.rev > baseRev && !l.snapshot);
3913
4000
  }
4001
+ /**
4002
+ * A plan was drawn on this architecture: whatever an agent marked `planned: true` (stored as the plan to come, `next`) is that plan's,
4003
+ * so that when it is done the person is asked to make it real. Bookkeeping, so it lands at once.
4004
+ * @param {string} planId
4005
+ */
4006
+ adoptPlanned(planId) {
4007
+ return this.enqueue(async () => {
4008
+ const a = this.arch;
4009
+ if (!a || this.error) return null;
4010
+ const ops = [];
4011
+ for (const [id, b] of Object.entries(a.nodes)) if (b.planned === PLAN_TO_COME) ops.push({ op: "box.set", id, planned: planId });
4012
+ for (const e of a.edges) if (e.planned === PLAN_TO_COME) ops.push({ op: "arrow.set", from: e.from, to: e.to, planned: planId });
4013
+ if (!ops.length) return null;
4014
+ return this.applyNow({ baseRev: a.rev, reason: `these belong to the plan ${planId}`, ops }, { actor: PLAN_ACTOR, via: "server" });
4015
+ });
4016
+ }
3914
4017
  /**
3915
4018
  * A finished plan's boxes are ready to be made real: the planned ones live, the retiring ones gone. That is a change to the
3916
4019
  * architecture, so it waits for you as a proposal; nothing happens if the plan changed nothing in it, or the proposal is
@@ -4073,37 +4176,48 @@ function parseLayout2(text2) {
4073
4176
  import { randomUUID } from "node:crypto";
4074
4177
 
4075
4178
  // packages/server/src/guide.js
4076
- var GUIDE = `DiaCode keeps this repository's plans as files in .dcursed/plans/, and the person edits the same plan in a diagram while you work, so it changes under you.
4179
+ 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.";
4180
+ 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.
4077
4181
 
4078
- How to work with it
4182
+ 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.
4183
+ 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.
4184
+ 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.
4185
+ 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.
4186
+ 4. THEY PRESS START. You are sent a [DiaCode] message: carry the plan out, below.
4187
+ 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.
4188
+ Each DiaCode tool's answer ends with the stage you are at. When it says to wait, wait.
4189
+
4190
+ How to work with a plan
4079
4191
  - 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.
4080
- - 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.
4192
+ - 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.
4081
4193
  - 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.
4082
4194
  - 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.
4083
- - To start a step call step_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.
4195
+ - 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.
4084
4196
  - To draft a plan call plan_create with every step, what each one depends on ("after") and the files it touches. To change a plan call plan_edit, and give a reason.
4085
4197
  - Give steps a group only where several share an area (two to four groups in a whole plan, often none): each group is drawn as a frame, and a step alone in a frame is noise.
4086
- - After drafting a plan, stop: tell the person it is ready to review in the editor, and do not start its steps until they approve it. Their approval is sent to you as a message that starts with [DiaCode], and plan_read then shows the plan executing (or they tell you themselves); then carry it out.
4087
- - What the person changes after your turn has ended (a step cancelled, reworded or added, a question answered) is sent to you the same way, as a [DiaCode] message: read the plan and carry on with what is left for you.
4088
- - While a plan is being executed, 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.
4089
- - 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. 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 is back in planning until they approve it again.
4198
+ - What the person changes after your turn has ended (a step cancelled, reworded or added, a question answered) is sent to you as a [DiaCode] message: read the plan and carry on with what is left for you.
4199
+ - 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.
4200
+ - 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.
4090
4201
  - 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.
4091
4202
  - Do not edit the files in .dcursed/plans/ by hand. The tools check the rules and keep the log.
4092
4203
 
4204
+ Showing the person something
4205
+ - 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.
4206
+
4093
4207
  Working while the person watches
4094
4208
  - 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.
4095
4209
 
4096
4210
  The architecture
4097
- - The repository also has one ARCHITECTURE, in .dcursed/architecture.json: the system as it is, 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.
4211
+ - 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.
4098
4212
  - 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.
4099
- - arch_read shows it; read it before you plan work that changes the system. If there is none and you are asked to draw it, arch_draft makes one from the code (boxes, arrows, flows, the files each box owns). If you were asked for a plan too, draft the plan on it at once, then stop: the person reviews the two together, and approving the plan accepts the architecture with it. Otherwise stop after arch_draft: the person reviews it and accepts it. After that, arch_edit changes become proposals they accept.
4100
- - When a plan adds or removes a part of the system, say so in the architecture: arch_edit a box with planned: "<plan id>" (or retiring), 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.
4213
+ - 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.
4214
+ - 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.
4101
4215
  - Do not edit .dcursed/architecture.json by hand either.`;
4102
4216
 
4103
4217
  // packages/server/src/calls.js
4104
4218
  import { EventEmitter as EventEmitter3 } from "node:events";
4105
4219
  var ARCH_SCOPE = "@architecture";
4106
- var HELD_WHILE_BUSY = /* @__PURE__ */ new Set(["changed", "archAccepted", "archSettled"]);
4220
+ var HELD_WHILE_BUSY = /* @__PURE__ */ new Set(["changed", "archAccepted", "archSettled", "archChanged"]);
4107
4221
  var KEEP = 50;
4108
4222
  var GAP_MS = 5e3;
4109
4223
  var WORTH_TELLING = /* @__PURE__ */ new Set(["node.add", "node.set", "node.remove", "edge.add", "edge.remove", "edge.rewire", "edge.reverse", "edge.set", "status.set", "release", "proposal.accept", "proposal.reject"]);
@@ -4177,7 +4291,9 @@ var Calls = class extends EventEmitter3 {
4177
4291
  for (const op of line.ops ?? []) {
4178
4292
  if (op.op === "plan.set" && op.phase === "executing" && was === "paused") {
4179
4293
  phased = true;
4180
- for (const to of this.resumers(id)) this.make({ plan: id, rev: line.rev, kind: "resumed", to, text: resumedText(plan, id) });
4294
+ for (const to of this.resumers(id)) {
4295
+ this.make({ plan: id, rev: line.rev, kind: "resumed", to, text: resumedText(plan, id, this.bothSides(id, to, line.rev)) });
4296
+ }
4181
4297
  } else if (op.op === "plan.set" && op.phase === "executing") {
4182
4298
  phased = true;
4183
4299
  for (const [actor, o] of this.stops) if (o.plan === id) this.stops.delete(actor);
@@ -4185,7 +4301,15 @@ var Calls = class extends EventEmitter3 {
4185
4301
  const archToo = was === "planning" && this.arch?.arch?.phase === "draft" && to !== void 0 && this.archDrafter() === to;
4186
4302
  if (archToo) this.acceptArch().catch(() => {
4187
4303
  });
4188
- this.make({ plan: id, rev: line.rev, kind: "approved", to, text: approvedText(plan, id, { archToo }) });
4304
+ this.make({ plan: id, rev: line.rev, kind: "started", to, text: startedText(plan, id, { archToo, again: was === "approved" && this.statusesStarted(id) }) });
4305
+ } else if (op.op === "plan.set" && op.phase === "approved") {
4306
+ phased = true;
4307
+ for (const [actor, o] of this.stops) if (o.plan === id) this.stops.delete(actor);
4308
+ const to = this.worker(id);
4309
+ const archToo = was === "planning" && this.arch?.arch?.phase === "draft" && to !== void 0 && this.archDrafter() === to;
4310
+ if (archToo) this.acceptArch().catch(() => {
4311
+ });
4312
+ 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 })) }) });
4189
4313
  } else if (op.op === "plan.set" && op.phase) {
4190
4314
  phased = true;
4191
4315
  this.dropQueued(id);
@@ -4207,7 +4331,7 @@ var Calls = class extends EventEmitter3 {
4207
4331
  if (who) tell.add(who);
4208
4332
  }
4209
4333
  }
4210
- if (!phased && plan.phase === "executing") for (const actor of tell) this.soon(id, actor, line.rev);
4334
+ if (!phased && (plan.phase === "executing" || plan.phase === "approved")) for (const actor of tell) this.soon(id, actor, line.rev);
4211
4335
  }
4212
4336
  /**
4213
4337
  * A batch landed on the architecture. Only yours can make a call. Accepting the draft an agent drew tells it that its
@@ -4220,9 +4344,13 @@ var Calls = class extends EventEmitter3 {
4220
4344
  if (!arch2 || line.actor !== "you" || line.proposed || quiet) return;
4221
4345
  const log = this.arch?.log ?? [];
4222
4346
  const settled = /* @__PURE__ */ new Map();
4347
+ let edited = false;
4223
4348
  for (const op of line.ops ?? []) {
4224
4349
  if (op.op === "arch.set" && op.phase === "accepted" && phaseWas === "draft") {
4225
- this.make({ plan: ARCH_SCOPE, rev, kind: "archAccepted", to: this.archDrafter(), text: archAcceptedText(arch2) });
4350
+ const live2 = this.livePlan();
4351
+ this.make({ plan: ARCH_SCOPE, rev, kind: "archAccepted", to: this.archDrafter() ?? (live2 ? this.worker(live2.id) : void 0), text: archAcceptedText(arch2, live2?.phase) });
4352
+ } else if (arch_exports.STRUCTURAL.has(op.op) || op.op === "arch.set" && (op.title !== void 0 || op.goal !== void 0)) {
4353
+ edited = true;
4226
4354
  } else if (op.op === "proposal.accept" || op.op === "proposal.reject") {
4227
4355
  const made = [...log].reverse().find((l) => l.proposed === op.id && l.rev < rev);
4228
4356
  if (!made || made.actor.startsWith("server:")) continue;
@@ -4232,6 +4360,78 @@ var Calls = class extends EventEmitter3 {
4232
4360
  }
4233
4361
  }
4234
4362
  for (const [to, notes] of settled) this.archSettled(to, rev, notes);
4363
+ const live = this.livePlan();
4364
+ if (edited && live && (live.phase === "approved" || live.phase === "executing")) {
4365
+ const actor = this.worker(live.id);
4366
+ if (actor) this.soonArch(live.id, actor, rev);
4367
+ }
4368
+ }
4369
+ /**
4370
+ * The plan being worked on: the one running, else the one waiting for Start, else a draft (see core's `activePlan`).
4371
+ * @returns {{ id: string, phase: string } | undefined}
4372
+ */
4373
+ livePlan() {
4374
+ const plans = this.store.list().filter((p) => p.title !== void 0);
4375
+ return activePlan(
4376
+ /** @type {Array<{ id: string, phase: string }>} */
4377
+ plans
4378
+ );
4379
+ }
4380
+ /**
4381
+ * Your edits to the architecture, for the agent working on the plan: told a moment after the last one, like your edits to
4382
+ * the plan, so a box added, named and connected is one call.
4383
+ * @param {string} planId @param {string} actor @param {number} rev
4384
+ */
4385
+ soonArch(planId, actor, rev) {
4386
+ const key2 = `${ARCH_SCOPE}\0${actor}`;
4387
+ const was = this.pending.get(key2);
4388
+ if (was) clearTimeout(was.timer);
4389
+ const from = was?.from ?? rev;
4390
+ const timer = setTimeout(() => {
4391
+ this.pending.delete(key2);
4392
+ this.archChanged(planId, actor, from, rev);
4393
+ }, this.changeMs);
4394
+ timer.unref?.();
4395
+ this.pending.set(key2, { from, timer });
4396
+ }
4397
+ /**
4398
+ * Tell the agent what you changed in the architecture from `from` to `rev`, unless it has been shown that already (it read the
4399
+ * architecture since). Not while the plan is paused: Resume says it, with what changed on the plan.
4400
+ * @param {string} planId @param {string} actor @param {number} from @param {number} rev
4401
+ */
4402
+ archChanged(planId, actor, from, rev) {
4403
+ const plan = this.store.get(planId).plan;
4404
+ const a = this.arch?.arch;
4405
+ if (!plan || !a || plan.phase !== "executing" && plan.phase !== "approved") return;
4406
+ if (!this.lastHeard.has(actor) && ![...this.waiters].some((w) => w.actor === actor)) return;
4407
+ const seen = this.seen(actor, ARCH_SCOPE);
4408
+ if (seen !== void 0 && seen >= rev) return;
4409
+ for (const c of this.calls) if (c.plan === ARCH_SCOPE && c.to === actor && c.kind === "archChanged" && c.state === "queued") this.settle(c, "dropped");
4410
+ const since = Math.min(seen ?? from - 1, from - 1);
4411
+ const lines = arch_exports.describeChanges(this.arch?.since(since) ?? [], since, { not: actor });
4412
+ if (!lines.length) return;
4413
+ const bare = this.bareBoxes(since);
4414
+ 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 } : {} });
4415
+ }
4416
+ /**
4417
+ * What you changed on the plan and on the architecture since this agent last looked, for the message that wakes it when a
4418
+ * paused plan resumes: Pause is where you edit, and both sides are said once.
4419
+ * @param {string} id @param {string} actor @param {number} [before] only what happened before this revision of the plan (the Resume itself is not news)
4420
+ * @returns {{ plan: string[], arch: string[] }}
4421
+ */
4422
+ bothSides(id, actor, before = Infinity) {
4423
+ const seenPlan = this.seen(actor, id);
4424
+ const seenArch = this.seen(actor, ARCH_SCOPE);
4425
+ return {
4426
+ plan: seenPlan === void 0 ? [] : describeChanges(this.store.changesSince(id, seenPlan).filter((l) => l.rev < before), seenPlan, { not: actor }),
4427
+ arch: seenArch === void 0 || !this.arch ? [] : arch_exports.describeChanges(this.arch.since(seenArch), seenArch, { not: actor })
4428
+ };
4429
+ }
4430
+ /** Has anything been done on this plan, so that Start is a carry-on and not a first start? @param {string} id */
4431
+ statusesStarted(id) {
4432
+ const plan = this.store.get(id).plan;
4433
+ if (Object.values(plan?.nodes ?? {}).some((n) => n.status !== void 0 && n.status !== "not_started")) return true;
4434
+ return (this.store.entries.get(id)?.log ?? []).some((l) => (l.ops ?? []).some((o) => o.op === "plan.stop"));
4235
4435
  }
4236
4436
  /**
4237
4437
  * Tell an agent what you decided about its proposals. One that is still waiting for the agent's turn to end is said again
@@ -4246,7 +4446,7 @@ var Calls = class extends EventEmitter3 {
4246
4446
  this.settle(c, "dropped");
4247
4447
  }
4248
4448
  }
4249
- const made = this.make({ plan: ARCH_SCOPE, rev, kind: "archSettled", to, text: archSettledText(this.arch?.arch, all) });
4449
+ const made = this.make({ plan: ARCH_SCOPE, rev, kind: "archSettled", to, text: archSettledText(this.arch?.arch, all, { drawPlan: !this.livePlan() }) });
4250
4450
  if (made) made.notes = all;
4251
4451
  }
4252
4452
  /**
@@ -4290,7 +4490,7 @@ var Calls = class extends EventEmitter3 {
4290
4490
  if (l.proposed) continue;
4291
4491
  const ops = l.ops ?? [];
4292
4492
  for (let j = ops.length - 1; j >= 0; j--) {
4293
- if (ops[j].op === "plan.stop") return "planning";
4493
+ if (ops[j].op === "plan.stop") return "approved";
4294
4494
  if (ops[j].op === "plan.set" && ops[j].phase) return ops[j].phase;
4295
4495
  }
4296
4496
  }
@@ -4430,14 +4630,90 @@ var Calls = class extends EventEmitter3 {
4430
4630
  */
4431
4631
  changed(id, actor, from, rev) {
4432
4632
  const plan = this.store.get(id).plan;
4433
- if (!plan || plan.phase !== "executing") return;
4633
+ if (!plan || plan.phase !== "executing" && plan.phase !== "approved") return;
4434
4634
  if (!this.lastHeard.has(actor) && ![...this.waiters].some((w) => w.actor === actor)) return;
4435
4635
  const seen = this.seen(actor, id);
4436
4636
  if (seen !== void 0 && seen >= rev) return;
4437
4637
  for (const c of this.calls) if (c.plan === id && c.to === actor && c.kind === "changed" && c.state === "queued") this.settle(c, "dropped");
4438
4638
  const since = seen ?? from - 1;
4439
4639
  const changes = describeChanges(this.store.changesSince(id, since), since, { not: actor });
4440
- this.make({ plan: id, rev, kind: "changed", to: actor, text: changedText(plan, id, this.store.attentionFor(id, actor, since), changes) });
4640
+ 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)));
4641
+ const bare = this.bareSteps(id, since);
4642
+ 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 } : {} });
4643
+ }
4644
+ /**
4645
+ * Steps you added by name only (no description, no files, no boxes): those you added since `since`, or with no `since`, every such
4646
+ * step of the plan. A step you filled in while the edit waited is not bare any more.
4647
+ * @param {string} id @param {number} [since]
4648
+ * @returns {string[]}
4649
+ */
4650
+ bareSteps(id, since) {
4651
+ const plan = this.store.get(id).plan;
4652
+ if (!plan) return [];
4653
+ 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) => (
4654
+ /** @type {string} */
4655
+ o.id
4656
+ )));
4657
+ return [...new Set(added)].filter((s) => {
4658
+ const n = plan.nodes[s];
4659
+ return n && n.kind !== "context" && !n.detail && !n.files?.length && !n.touches?.length && (n.status === void 0 || n.status === "not_started");
4660
+ });
4661
+ }
4662
+ /**
4663
+ * Boxes you added by name only (no description, technology or files) since `since`.
4664
+ * @param {number} since @returns {string[]}
4665
+ */
4666
+ bareBoxes(since) {
4667
+ const a = this.arch?.arch;
4668
+ if (!a) return [];
4669
+ 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) => (
4670
+ /** @type {string} */
4671
+ o.id
4672
+ )));
4673
+ return [...new Set(added)].filter((b) => {
4674
+ const n = a.nodes[b];
4675
+ return n && n.kind !== "group" && !n.detail && !n.tech && !n.files?.length;
4676
+ });
4677
+ }
4678
+ /**
4679
+ * You asked your agent to look at something the plan does not cover or got wrong: files edited outside it (`drift`), steps whose
4680
+ * upstream changed (`review`), or a step that failed (`failure`). The agent is woken with what you pressed and what it is about.
4681
+ * Nobody to tell comes back as a call in the state `none`, which the editor says in words.
4682
+ * @param {string} id @param {{ kind: 'drift' | 'review' | 'failure', step?: string, steps?: string[] }} request
4683
+ * @returns {Call}
4684
+ */
4685
+ askAgent(id, { kind, step: step3, steps }) {
4686
+ const view = this.store.get(id);
4687
+ const plan = view.plan;
4688
+ if (!plan) throw new HttpError(409, `${id}.plan.json is not a valid plan yet`);
4689
+ let to;
4690
+ let text2;
4691
+ if (kind === "drift") {
4692
+ const drift = this.store.driftOf(id);
4693
+ if (!drift.length) throw new HttpError(409, "nothing is outside the plan");
4694
+ to = this.worker(id);
4695
+ text2 = driftText(plan, id, drift);
4696
+ } else if (kind === "failure") {
4697
+ const n = step3 ? plan.nodes[step3] : void 0;
4698
+ if (!step3 || !n) throw new HttpError(404, `there is no step ${step3 ?? ""} in ${id}`);
4699
+ if (n.status !== "failed") throw new HttpError(409, `${step3} has not failed`);
4700
+ const behind = Object.keys(view.derived?.atRisk ?? {}).filter((s) => (view.derived?.atRisk?.[s] ?? []).includes(step3));
4701
+ to = this.holder(id, step3) ?? this.worker(id);
4702
+ text2 = failureText(plan, id, step3, behind);
4703
+ } else {
4704
+ const waiting = (steps?.length ? steps : Object.keys(view.review ?? {})).filter((s) => plan.nodes[s]);
4705
+ if (!waiting.length) throw new HttpError(409, "nothing needs review");
4706
+ to = this.worker(id);
4707
+ text2 = reviewText(plan, id, waiting.map((s) => ({ id: s, because: view.review?.[s]?.because ?? [] })));
4708
+ }
4709
+ const call = (
4710
+ /** @type {Call} */
4711
+ this.make({ plan: id, rev: plan.rev, kind: "replan", ...kind === "failure" && step3 ? { step: step3 } : {}, ...to ? { to } : {}, text: text2 })
4712
+ );
4713
+ if (call.state === "queued" && to && !this.lastHeard.has(to) && ![...this.waiters].some((w) => w.actor === to) && !this.busy(to)) {
4714
+ this.settle(call, "none", "nothing is listening for the editor");
4715
+ }
4716
+ return { ...call };
4441
4717
  }
4442
4718
  /** The revision of a plan an agent was last shown, if it ever was. @param {string} actor @param {string} id */
4443
4719
  seen(actor, id) {
@@ -4471,7 +4747,7 @@ var Calls = class extends EventEmitter3 {
4471
4747
  if (this.calls.length > KEEP) this.calls.shift();
4472
4748
  if (call.state === "none") {
4473
4749
  this.emit("call", { ...call });
4474
- return;
4750
+ return call;
4475
4751
  }
4476
4752
  if (!this.offer(call)) {
4477
4753
  this.emit("call", { ...call });
@@ -4515,8 +4791,10 @@ var Calls = class extends EventEmitter3 {
4515
4791
  }
4516
4792
  const plan = this.store.get(call.plan).plan;
4517
4793
  if (!plan) return false;
4518
- if (call.kind === "approved" || call.kind === "resumed") return plan.phase === "executing";
4519
- if (call.kind === "stopped") return plan.phase === "planning" && call.to !== void 0 && this.stoppedFor(call.to) === call.plan;
4794
+ if (call.kind === "started" || call.kind === "resumed") return plan.phase === "executing";
4795
+ if (call.kind === "replan") return plan.phase !== "done";
4796
+ if (call.kind === "planApproved") return plan.phase === "approved";
4797
+ if (call.kind === "stopped") return plan.phase === "approved" && call.to !== void 0 && this.stoppedFor(call.to) === call.plan;
4520
4798
  if (call.kind === "passed") {
4521
4799
  const e = call.gate && plan.edges.find((x) => x.from === call.gate?.from && x.to === call.gate?.to);
4522
4800
  return plan.phase === "executing" && Boolean(e?.passed) && (plan.nodes[call.gate?.to ?? ""]?.status ?? "not_started") === "not_started";
@@ -4524,7 +4802,7 @@ var Calls = class extends EventEmitter3 {
4524
4802
  if (call.kind === "sentBack") return plan.phase === "executing" && plan.nodes[call.step ?? ""]?.status === "not_started";
4525
4803
  if (call.kind === "changed") {
4526
4804
  const seen = call.to ? this.seen(call.to, call.plan) : void 0;
4527
- return plan.phase === "executing" && !(seen !== void 0 && seen >= call.rev);
4805
+ return (plan.phase === "executing" || plan.phase === "approved") && !(seen !== void 0 && seen >= call.rev);
4528
4806
  }
4529
4807
  const n = call.step ? plan.nodes[call.step] : void 0;
4530
4808
  return Boolean(n && n.owner === call.to && n.status === "in_progress");
@@ -4618,15 +4896,60 @@ var Calls = class extends EventEmitter3 {
4618
4896
  this.pending.clear();
4619
4897
  }
4620
4898
  };
4621
- function approvedText(plan, id, { archToo = false } = {}) {
4899
+ var clipped = (s, max = 300) => s.length > max ? `${s.slice(0, max - 1)}\u2026` : s;
4900
+ function driftText(plan, id, drift) {
4901
+ return [
4902
+ `[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:`,
4903
+ ...drift.slice(0, 20).map((d) => `- ${d.file} (edited ${d.count}\xD7 by ${d.by})`),
4904
+ "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."
4905
+ ].join("\n");
4906
+ }
4907
+ function failureText(plan, id, step3, behind) {
4908
+ const n = plan.nodes[step3];
4909
+ return [
4910
+ `[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)}` : "."}`,
4911
+ ...behind.length ? [`These wait behind it: ${behind.join(", ")}.`] : [],
4912
+ "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."
4913
+ ].join("\n");
4914
+ }
4915
+ function reviewText(plan, id, steps) {
4916
+ return [
4917
+ `[DiaCode] The person asks you to review steps of the plan "${plan.title}" (${id}) that a change upstream of them may have made wrong:`,
4918
+ ...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)}` : ""}`),
4919
+ "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."
4920
+ ].join("\n");
4921
+ }
4922
+ function planApprovedText(plan, id, { archToo = false, hasArch = true, bare = [] } = {}) {
4923
+ return [
4924
+ `[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.`,
4925
+ 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.",
4926
+ ...bare.length ? [bareStepsWords(bare)] : [],
4927
+ "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."
4928
+ ].join("\n");
4929
+ }
4930
+ function bareStepsWords(bare) {
4931
+ const list = bare.slice(0, 10).map((b) => `${b.id} ("${b.label}")`).join(", ");
4932
+ 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.`;
4933
+ }
4934
+ function bareBoxesWords(bare) {
4935
+ const list = bare.slice(0, 10).map((b) => `${b.id} ("${b.label}")`).join(", ");
4936
+ 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.`;
4937
+ }
4938
+ function startedText(plan, id, { archToo = false, again = false } = {}) {
4622
4939
  return [
4623
- `[DiaCode] The person approved the plan "${plan.title}" (${id}) in the editor${archToo ? ", and with it the architecture you drew (your changes to the architecture are proposals from now on)" : ""}. Carry it out now with the dcursed tools, one step at a time:`,
4940
+ `[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:`,
4624
4941
  "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.",
4625
- "If a step is unclear, stop on it with step_wait and say what you need."
4942
+ "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."
4626
4943
  ].join(" ");
4627
4944
  }
4628
- function resumedText(plan, id) {
4629
- return `[DiaCode] The person resumed the plan "${plan.title}" (${id}) in the editor. Read it with plan_read (they may have changed it while it was paused) and carry on with what is left for you, one step at a time.`;
4945
+ function resumedText(plan, id, sides = { plan: [], arch: [] }) {
4946
+ const clip2 = (s) => s.length > 400 ? `${s.slice(0, 399)}\u2026` : s;
4947
+ return [
4948
+ `[DiaCode] The person resumed the plan "${plan.title}" (${id}) in the editor. Read it with plan_read (they may have changed it while it was paused) and carry on with what is left for you, one step at a time.`,
4949
+ ...sides.plan.length ? ["While it was paused they changed the plan:", ...sides.plan.slice(-20).map((c) => `- ${clip2(c)}`)] : [],
4950
+ ...sides.arch.length ? ["While it was paused they changed the architecture:", ...sides.arch.slice(-20).map((c) => `- ${clip2(c)}`)] : [],
4951
+ ...sides.plan.length || sides.arch.length ? ["Make the other side agree: for what they changed on the plan, propose the matching change to the architecture (arch_edit); for what they changed on the architecture, the matching change to the plan (plan_edit). Say why in the reason. If nothing needs to change, say so."] : []
4952
+ ].join("\n");
4630
4953
  }
4631
4954
  function stopOrder(id) {
4632
4955
  return `The person STOPPED plan ${id} in the DiaCode editor. Stop now: do not finish the step you were on and do not use another tool. End your turn, saying in a sentence where you stopped. The plan is back in planning; they will approve it again when they want it carried on.`;
@@ -4654,30 +4977,111 @@ function answeredText(plan, id, step3, answer) {
4654
4977
  return `[DiaCode] The person answered your question on step ${step3}${label ? ` ("${label}")` : ""} in plan ${id}: ${answer}
4655
4978
  Carry on with ${step3} using that answer.`;
4656
4979
  }
4657
- function changedText(plan, id, attention, changes) {
4980
+ function changedText(plan, id, attention, changes, { sync = true, bare = [] } = {}) {
4658
4981
  const clip2 = (s) => s.length > 400 ? `${s.slice(0, 399)}\u2026` : s;
4982
+ const waiting = plan.phase === "approved";
4659
4983
  return [
4660
4984
  `[DiaCode] While you were between turns, the person changed the plan "${plan.title}" (${id}) in the editor.`,
4661
4985
  ...attention.length ? ["HEADS UP, about your steps:", ...attention.map((a) => `- ${clip2(a)}`)] : [],
4662
4986
  ...changes.length ? ["What changed:", ...changes.slice(-20).map((c) => `- ${clip2(c)}`)] : [],
4663
- "Read the plan with plan_read and 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."
4987
+ ...bare.length ? [bareStepsWords(bare)] : [],
4988
+ 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.",
4989
+ 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."
4990
+ ].join("\n");
4991
+ }
4992
+ function archChangedText(plan, id, arch2, lines, { bare = [] } = {}) {
4993
+ const clip2 = (s) => s.length > 400 ? `${s.slice(0, 399)}\u2026` : s;
4994
+ return [
4995
+ `[DiaCode] The person changed the architecture ("${arch2.title}") in the editor:`,
4996
+ ...lines.slice(-20).map((l) => `- ${clip2(l)}`),
4997
+ ...bare.length ? [bareBoxesWords(bare)] : [],
4998
+ `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.`,
4999
+ 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."
4664
5000
  ].join("\n");
4665
5001
  }
4666
- function archAcceptedText(arch2) {
5002
+ function archAcceptedText(arch2, planPhase) {
5003
+ const head = `[DiaCode] The person approved the architecture${arch2.title ? ` ("${arch2.title}")` : ""} in the editor, with their changes. It is the shared truth now: from here on your changes to it (arch_edit) arrive as proposals for them to accept or reject, so say why in \`reason\`.`;
5004
+ if (planPhase === "planning") {
5005
+ return [head, "You have drafted a plan already: arch_read the architecture as approved (they may have changed it), plan_read the plan, and make the plan agree (plan_edit lands at once while it is a draft). Say in a sentence what you changed. Do not start any step; stop, and wait for them to approve the plan."].join("\n");
5006
+ }
5007
+ if (planPhase === "approved" || planPhase === "executing" || planPhase === "paused") {
5008
+ return [head, "The plan is approved already. Read it again against the architecture; if they no longer agree, propose the matching change (plan_edit). Otherwise there is nothing to do: say so in a sentence and stop. Do not start any step the person has not started."].join("\n");
5009
+ }
4667
5010
  return [
4668
- `[DiaCode] The person accepted the architecture you drew ("${arch2.title}") in the editor. It is the shared truth now: from here on your changes to it (arch_edit) arrive as proposals for them to accept or reject, so say why in \`reason\`.`,
4669
- "If you were waiting on this to carry on with something they asked, carry on. Otherwise there is nothing to do: say so in a sentence and stop."
5011
+ head,
5012
+ 'If the person gave you a task, draw the plan on it NOW: arch_read, then plan_create (every step with what it waits for, the files it touches, what done means, and the boxes it changes as touches). A question the task told you to ask before building 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>" }]; you call step_ask on that step when it is next), not a question in this window and not a step of its own. Then stop and say the plan is ready to review. Do not start any step.'
4670
5013
  ].join("\n");
4671
5014
  }
4672
- function archSettledText(arch2, notes) {
5015
+ function archSettledText(arch2, notes, { drawPlan = false } = {}) {
4673
5016
  const clip2 = (s) => s.length > 400 ? `${s.slice(0, 399)}\u2026` : s;
4674
5017
  return [
4675
5018
  `[DiaCode] The person settled ${notes.length === 1 ? "your proposal" : "your proposals"} to the architecture${arch2 ? ` ("${arch2.title}")` : ""}:`,
4676
5019
  ...notes.slice(-20).map((n) => `- ${clip2(n)}`),
4677
- "Read it with arch_read before you change it again. If something you are doing depended on what was rejected, say so and adjust. If nothing is left for you to do, say so in a sentence and stop."
5020
+ drawPlan ? "Read it with arch_read. There is no plan yet: if you were waiting on this to draw the plan for the person's task, draw it NOW on the architecture as it stands (plan_create), then stop and say it is ready to review; do not start any step. If there is no task waiting, say so in a sentence and stop." : "Read it with arch_read before you change it again. If a step of the plan depended on something that was rejected, propose the matching change to the plan (plan_edit, with a reason). If nothing is left for you to do, say so in a sentence and stop."
4678
5021
  ].join("\n");
4679
5022
  }
4680
5023
 
5024
+ // packages/server/src/flow.js
5025
+ function flowNow({ store, arch: arch2, presence }) {
5026
+ const plans = store.list().filter((p) => p.title !== void 0);
5027
+ const plan = activePlan(
5028
+ /** @type {Array<{ id: string, phase: string, proposals?: number }>} */
5029
+ plans
5030
+ );
5031
+ const a = arch2.arch;
5032
+ const busy = [...presence?.agents?.values() ?? []].some((e) => presence?.shown(
5033
+ /** @type {any} */
5034
+ e
5035
+ ) === "working");
5036
+ const waiting = (a?.proposals ?? []).length + (plan?.proposals ?? 0);
5037
+ const finished = plans.some((p) => p.phase === "done");
5038
+ const flow = flowOf({ arch: a ? { phase: a.phase } : null, plan, waiting, busy, finished });
5039
+ const waits = {
5040
+ plan: (plan?.proposals ?? 0) + (flow.stage === "plan" || flow.stage === "start" ? 1 : 0),
5041
+ architecture: (a?.proposals ?? []).length + (flow.stage === "architecture" ? 1 : 0)
5042
+ };
5043
+ return { flow, plan, arch: a, waits };
5044
+ }
5045
+ function agentBrief(flow, { plan } = {}) {
5046
+ switch (flow.stage) {
5047
+ case "task":
5048
+ return [
5049
+ "DiaCode keeps this order: the architecture, then the plan, then Start. The person approves each in the DiaCode editor before the next. You are at the first.",
5050
+ "If they have just given you something to build or change, do this and nothing else: call arch_draft to draw the architecture of the system AS IT WILL BE (its people, services, parts, stores and queues; mark every part that does not exist yet with planned: true; in an empty repository that is all of them), then STOP and say in a sentence that it is ready to review in the editor.",
5051
+ "Do not call plan_create, do not write code, and do not ask the person questions in this window: assume what you need and say so in a box's detail or the goal, and they correct the drawing. If the task tells you to ask them something before building, that comes later, as a step in the plan behind an ask checkpoint."
5052
+ ].join("\n");
5053
+ case "architecture":
5054
+ return `DiaCode: the person is reviewing the architecture${plan ? " (the plan waits for it)" : ""}. Do not plan or build until they approve it: their approval is sent to you as a message that starts with [DiaCode]. If you have nothing else to do, stop and say you are waiting for them.`;
5055
+ case "plan-wait":
5056
+ return [
5057
+ "DiaCode: the architecture is approved. If the person has given you a task, draw the plan on it now: arch_read, then plan_create (every step, what it waits for, the files it touches, what done means, and the architecture's boxes it changes as touches). Then STOP and say it is ready to review: do not start any step.",
5058
+ 'A question the task told you to ask before building 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>" }]), asked with step_ask on that step when it is next; do not ask it in this window, and make no step of its own for asking.'
5059
+ ].join("\n");
5060
+ case "plan":
5061
+ return "DiaCode: the person is reviewing the plan. Do not start any step: their approval is sent to you as a message that starts with [DiaCode]. If you have nothing else to do, stop and say you are waiting for them.";
5062
+ case "start":
5063
+ return "DiaCode: the person approved the plan but has not started it. Do not start any step. If you were asked to check the architecture against the plan, do that and stop; their Start is sent to you as a message that starts with [DiaCode].";
5064
+ default:
5065
+ return "";
5066
+ }
5067
+ }
5068
+ function footLine(flow) {
5069
+ switch (flow.stage) {
5070
+ case "task":
5071
+ return "Stage: no architecture yet. If the person gave you a task, arch_draft now (mark what does not exist yet planned: true), then stop and say it is ready to review.";
5072
+ case "architecture":
5073
+ return "Stage: the person is reviewing the architecture. Do not plan or build: wait for their [DiaCode] message.";
5074
+ case "plan-wait":
5075
+ return "Stage: the architecture is approved. Draw the plan on it with plan_create, then stop and say it is ready to review.";
5076
+ case "plan":
5077
+ return "Stage: the person is reviewing the plan. Do not start a step: wait for their [DiaCode] message.";
5078
+ case "start":
5079
+ return "Stage: the plan is approved, not started. Check the architecture against it (arch_edit, as proposals), then stop. Do not start a step: wait for their Start.";
5080
+ default:
5081
+ return "";
5082
+ }
5083
+ }
5084
+
4681
5085
  // packages/server/src/mcp.js
4682
5086
  var VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];
4683
5087
  var MAX_SESSIONS = 200;
@@ -4739,7 +5143,7 @@ var OP_EXAMPLES = {
4739
5143
  "edge.remove": '{"op":"edge.remove","from":"tests","to":"lint"}',
4740
5144
  "edge.rewire": '{"op":"edge.rewire","from":"a","to":"b","newTo":"c"} (or newFrom)',
4741
5145
  "edge.reverse": '{"op":"edge.reverse","from":"a","to":"b"}',
4742
- "edge.set": '{"op":"edge.set","from":"a","to":"b","label":"parsed rows"} (or "kind": needs, after, approve, ask or input)',
5146
+ "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)',
4743
5147
  "group.rename": '{"op":"group.rename","from":"old name","to":"new name"}',
4744
5148
  "plan.set": '{"op":"plan.set","goal":"what the plan is for"} (or title)',
4745
5149
  review: '{"op":"review","ids":["tests"]}'
@@ -4767,6 +5171,13 @@ var FINISHERS = [
4767
5171
  { 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." },
4768
5172
  { 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." }
4769
5173
  ];
5174
+ var OPTIONS = {
5175
+ type: "array",
5176
+ minItems: 1,
5177
+ maxItems: OPTIONS_MAX,
5178
+ items: { type: "string", maxLength: OPTION_MAX },
5179
+ 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`
5180
+ };
4770
5181
  var KIND2 = {
4771
5182
  type: "string",
4772
5183
  enum: ["needs", "after", "approve", "ask", "input"],
@@ -4807,6 +5218,7 @@ WARNING: the plan file has an edit that breaks a rule (${view.error}). Writes wa
4807
5218
  properties: {
4808
5219
  title: { type: "string" },
4809
5220
  goal: { type: "string", description: "what the whole plan is for, and when it is done" },
5221
+ no_architecture: { type: "boolean", description: "only if the person told you they do not want an architecture drawn first" },
4810
5222
  steps: {
4811
5223
  type: "array",
4812
5224
  minItems: 1,
@@ -4822,8 +5234,8 @@ WARNING: the plan file has an edit that breaks a rule (${view.error}). Writes wa
4822
5234
  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" },
4823
5235
  after: {
4824
5236
  type: "array",
4825
- 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)',
4826
- items: { anyOf: [{ type: "string" }, { type: "object", required: ["id"], properties: { id: { type: "string" }, kind: KIND2, label: { type: "string" } } }] }
5237
+ 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)',
5238
+ items: { anyOf: [{ type: "string" }, { type: "object", required: ["id"], properties: { id: { type: "string" }, kind: KIND2, label: { type: "string" }, options: OPTIONS } }] }
4827
5239
  },
4828
5240
  kind: { type: "string", enum: ["task", "context"], description: "context: something that already exists, shown for reference" }
4829
5241
  }
@@ -4833,18 +5245,21 @@ WARNING: the plan file has an edit that breaks a rule (${view.error}). Writes wa
4833
5245
  },
4834
5246
  async run(args2, s, ctx) {
4835
5247
  const title = str(args2.title, "title");
5248
+ const refusal2 = planBeforeArchitecture(ctx, args2.no_architecture === true);
5249
+ if (refusal2) return { error: true, text: refusal2 };
4836
5250
  const ops = stepsToOps(args2.steps);
4837
5251
  const dry = applyBatch(newPlan({ id: "draft", title }), ops, ctx.who(s));
4838
5252
  if (dry.kind === "rejected") return refused(dry);
4839
5253
  const made = await ctx.store.create({ title, goal: typeof args2.goal === "string" ? args2.goal : void 0 }, ctx.who(s));
4840
5254
  const done = await send(ctx, s, made.id, ops, { reason: "drafted by the agent", baseRev: 0 });
4841
5255
  if (done.error) return done;
5256
+ await ctx.arch.adoptPlanned(made.id);
4842
5257
  const view = viewOf(ctx, made.id);
4843
5258
  const loose = args2.steps.length >= 3 && !args2.steps.some((st) => Array.isArray(st?.after) && st.after.length);
4844
5259
  const check = loose ? `
4845
5260
 
4846
5261
  NOTE: no step depends on another, so all of them can start at once. If any step needs another's work first, add those dependencies now with plan_edit, as edge.add operations ({"op":"edge.add","from":"<the step that comes first>","to":"<the step that waits>"}), before saying the plan is ready.` : "";
4847
- const next = "The person reviews it in the editor now. Stop here and say it is ready to review; do not start its steps until it is approved. The approval is sent to you as a message that starts with [DiaCode].";
5262
+ const next = "The person reviews it in the editor now. Stop here and say it is ready to review; do not start its steps. They approve it, then you check the architecture against it, then they press Start: each is sent to you as a message that starts with [DiaCode].";
4848
5263
  return { text: `Created plan ${made.id}.
4849
5264
 
4850
5265
  ${describePlan(view)}${check}
@@ -4856,7 +5271,7 @@ ${next}`, data: { plan: made.id, rev: view.rev } };
4856
5271
  name: "plan_edit",
4857
5272
  description: [
4858
5273
  "Change a plan with a batch of operations, all or nothing. Operations:",
4859
- "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).",
5274
+ "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).",
4860
5275
  "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."
4861
5276
  ].join("\n"),
4862
5277
  inputSchema: {
@@ -4901,17 +5316,18 @@ You have it, and it is in progress.` };
4901
5316
  },
4902
5317
  {
4903
5318
  name: "step_ask",
4904
- 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.',
4905
- 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" } } },
5319
+ 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.',
5320
+ 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 } },
4906
5321
  async run(args2, s, ctx) {
4907
5322
  const planId = planOf(ctx, args2.plan);
4908
5323
  const id = str(args2.id, "id");
4909
5324
  const question = str(args2.question, "question");
5325
+ const options = args2.options === void 0 ? void 0 : args2.options;
4910
5326
  const { plan } = viewOf(ctx, planId);
4911
5327
  if (!plan.nodes[id]) throw new HttpError(404, `there is no step ${id} in ${planId}`);
4912
5328
  const asks = plan.edges.filter((e) => e.to === id && e.kind === "ask" && !e.passed);
4913
5329
  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.` };
4914
- 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}` });
5330
+ 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}` });
4915
5331
  if (outcome.error) return outcome;
4916
5332
  return { ...outcome, text: `${outcome.text}
4917
5333
 
@@ -5014,12 +5430,12 @@ function archDraftToOps(args2) {
5014
5430
  visiting.delete(id);
5015
5431
  placed.add(id);
5016
5432
  const { label, kind, tech, detail, files, external } = raw;
5017
- ops.push({ op: "box.add", id, label, kind, ...raw.in ? { in: raw.in } : {}, ...tech ? { tech } : {}, ...detail ? { detail } : {}, ...files?.length ? { files } : {}, ...external ? { external: true } : {} });
5433
+ ops.push({ op: "box.add", id, label, kind, ...raw.in ? { in: raw.in } : {}, ...tech ? { tech } : {}, ...detail ? { detail } : {}, ...files?.length ? { files } : {}, ...external ? { external: true } : {}, ...raw.planned === true ? { planned: PLAN_TO_COME } : {} });
5018
5434
  };
5019
5435
  for (const id of byId.keys()) place(id);
5020
5436
  for (const a of Array.isArray(args2.arrows) ? args2.arrows : []) {
5021
5437
  if (!a || typeof a !== "object") throw new HttpError(400, "each arrow is an object with from and to");
5022
- ops.push({ op: "arrow.add", from: a.from, to: a.to, ...a.label ? { label: a.label } : {}, ...a.tech ? { tech: a.tech } : {}, ...a.async ? { async: true } : {}, ...a.via ? { via: a.via } : {} });
5438
+ ops.push({ op: "arrow.add", from: a.from, to: a.to, ...a.label ? { label: a.label } : {}, ...a.tech ? { tech: a.tech } : {}, ...a.async ? { async: true } : {}, ...a.via ? { via: a.via } : {}, ...a.planned === true ? { planned: PLAN_TO_COME } : {} });
5023
5439
  }
5024
5440
  for (const f of Array.isArray(args2.flows) ? args2.flows : []) {
5025
5441
  if (!f || typeof f !== "object") throw new HttpError(400, "each flow is an object with id, title and steps");
@@ -5063,9 +5479,9 @@ WARNING: the architecture file has an edit that breaks a rule (${view.error}). W
5063
5479
  {
5064
5480
  name: "arch_draft",
5065
5481
  description: [
5066
- "Draw the repository's architecture in one call, by reading the code: the boxes (each with an id, a label and a kind), the arrows between them (an arrow from A to B means A USES B), and the flows (what happens, in order, for the things a user does).",
5482
+ "Draw the repository's architecture in one call, by reading the code (or, in an empty repository, from the task): the boxes (each with an id, a label and a kind), the arrows between them (an arrow from A to B means A USES B), and the flows (what happens, in order, for the things a user does).",
5067
5483
  'Kinds: person (a user or role), service (something that runs: an app, API or worker), component (a part inside a service: a package, folder or file), store (a database, cache or bucket), queue (a message channel), group (a frame round other boxes). external: true for what someone else runs. `in` puts a box inside a service or a group. A box with boxes inside it is a frame, and takes no arrows: the arrows belong to the boxes inside. Give each box its tech ("Python, FastAPI") and the files that are its (globs). Draw what runs, not tests, build scripts or docs: those are files of the box they belong to.',
5068
- "Only when there is no architecture yet. After drafting, stop: tell the person it is ready to review in the editor. Once they accept it, your changes to it become proposals."
5484
+ "Draw it as the system WILL BE: a part that does not exist yet gets planned: true (in an empty repository, every box does). Only when there is no architecture yet. After drafting, stop: tell the person it is ready to review in the editor. They approve it, and that approval is sent to you as a [DiaCode] message; then you draw the plan on it. After that, your changes to it become proposals."
5069
5485
  ].join("\n"),
5070
5486
  inputSchema: {
5071
5487
  type: "object",
@@ -5087,7 +5503,8 @@ WARNING: the architecture file has an edit that breaks a rule (${view.error}). W
5087
5503
  tech: { type: "string" },
5088
5504
  detail: { type: "string", description: "what it is for, in a sentence or two" },
5089
5505
  files: { type: "array", items: { type: "string" } },
5090
- external: { type: "boolean", description: "someone else runs it" }
5506
+ external: { type: "boolean", description: "someone else runs it" },
5507
+ planned: { type: "boolean", description: "true when it does not exist yet: the plan you draw next builds it. In an empty repository every box is planned." }
5091
5508
  }
5092
5509
  }
5093
5510
  },
@@ -5102,7 +5519,8 @@ WARNING: the architecture file has an edit that breaks a rule (${view.error}). W
5102
5519
  label: { type: "string", description: 'what for: "Store/load chats", not "uses"' },
5103
5520
  tech: { type: "string", description: "how: REST, SQL, a queue name" },
5104
5521
  async: { type: "boolean", description: "from does not wait for the answer" },
5105
- via: { type: "string", description: "the id of the queue that carries it" }
5522
+ via: { type: "string", description: "the id of the queue that carries it" },
5523
+ planned: { type: "boolean", description: "true when this connection does not exist yet" }
5106
5524
  }
5107
5525
  }
5108
5526
  },
@@ -5130,7 +5548,7 @@ WARNING: the architecture file has an edit that breaks a rule (${view.error}). W
5130
5548
  const r = await ctx.arch.apply({ baseRev: 0, reason: "drafted by the agent", ops }, ctx.who(s));
5131
5549
  if (r.kind === "rejected") return refusedArch(r);
5132
5550
  const view = archOf(ctx);
5133
- const next = "The person reviews it in the editor now. Stop here and say it is ready to review. Once they accept it, your changes to it become proposals for them to accept.";
5551
+ const next = "The person reviews it in the editor now. Stop here and say it is ready to review: do not draw the plan yet. They approve it, and that approval is sent to you as a message that starts with [DiaCode]; then you draw the plan on it. After that, your changes to it become proposals for them to accept.";
5134
5552
  return { text: `Drew the architecture.
5135
5553
 
5136
5554
  ${arch_exports.describeArch(view)}
@@ -5142,7 +5560,7 @@ ${next}`, data: { rev: view.rev } };
5142
5560
  name: "arch_edit",
5143
5561
  description: [
5144
5562
  "Change the architecture with a batch of operations, all or nothing. Operations:",
5145
- "box.add{label,kind,id?,in?,tech?,detail?,files?,external?,planned?} \xB7 box.set{id,label?,kind?,in?,tech?,detail?,files?,external?,planned?,retiring?} \xB7 box.remove{id} \xB7 arrow.add{from,to,label?,tech?,async?,via?,planned?} \xB7 arrow.remove{from,to} \xB7 arrow.rewire{from,to,newFrom?,newTo?} \xB7 arrow.reverse{from,to} \xB7 arrow.set{from,to,label?,tech?,async?,via?} \xB7 flow.add{id,title,steps} \xB7 flow.set{id,title?,steps?} \xB7 flow.remove{id} \xB7 arch.set{title?,goal?}.",
5563
+ "box.add{label,kind,id?,in?,tech?,detail?,files?,external?,planned?} (planned: true = it does not exist yet; the plan builds it) \xB7 box.set{id,label?,kind?,in?,tech?,detail?,files?,external?,planned?,retiring?} \xB7 box.remove{id} \xB7 arrow.add{from,to,label?,tech?,async?,via?,planned?} \xB7 arrow.remove{from,to} \xB7 arrow.rewire{from,to,newFrom?,newTo?} \xB7 arrow.reverse{from,to} \xB7 arrow.set{from,to,label?,tech?,async?,via?} \xB7 flow.add{id,title,steps} \xB7 flow.set{id,title?,steps?} \xB7 flow.remove{id} \xB7 arch.set{title?,goal?}.",
5146
5564
  'An arrow from A to B means A uses B. A box with boxes inside it is a frame and takes no arrows; a group takes none; a box sits only in a service or a group. To say a plan will add a box, give it planned: "<plan id>"; to say a plan will remove one, retiring: "<plan id>": when that plan is done the person is asked to make it real.',
5147
5565
  "Once the person has accepted the architecture, your changes to it arrive as a proposal for them to accept; say why in `reason`. While it is still your draft they land at once."
5148
5566
  ].join("\n"),
@@ -5159,9 +5577,10 @@ ${next}`, data: { rev: view.rev } };
5159
5577
  const view = archOf(ctx);
5160
5578
  try {
5161
5579
  const rev = s.seen.get(ARCH_KEY) ?? view.rev;
5162
- const reply = await ctx.arch.apply({ baseRev: rev, ...typeof args2.reason === "string" && args2.reason ? { reason: args2.reason } : {}, ...args2.propose === true ? { propose: true } : {}, ops: args2.ops }, ctx.who(s));
5580
+ const ops = Array.isArray(args2.ops) ? args2.ops.map((o) => o && typeof o === "object" && o.planned === true ? { ...o, planned: PLAN_TO_COME } : o) : args2.ops;
5581
+ const reply = await ctx.arch.apply({ baseRev: rev, ...typeof args2.reason === "string" && args2.reason ? { reason: args2.reason } : {}, ...args2.propose === true ? { propose: true } : {}, ops }, ctx.who(s));
5163
5582
  if (reply.kind === "rejected") return refusedArch(reply);
5164
- return { text: archApplied(reply, args2.ops), data: { rev: reply.rev, kind: reply.kind, ...reply.proposal ? { proposal: reply.proposal.id } : {} } };
5583
+ return { text: archApplied(reply, ops), data: { rev: reply.rev, kind: reply.kind, ...reply.proposal ? { proposal: reply.proposal.id } : {} } };
5165
5584
  } catch (e) {
5166
5585
  if (e instanceof HttpError && e.status === 400) throw new HttpError(400, `${e.message}
5167
5586
 
@@ -5190,7 +5609,7 @@ function stepsToOps(steps) {
5190
5609
  if (typeof a === "string") return { id: a };
5191
5610
  if (a && typeof a === "object" && typeof /** @type {any} */
5192
5611
  a.id === "string") return (
5193
- /** @type {{ id: string, kind?: unknown, label?: unknown }} */
5612
+ /** @type {{ id: string, kind?: unknown, label?: unknown, options?: unknown }} */
5194
5613
  a
5195
5614
  );
5196
5615
  throw new HttpError(400, 'each "after" entry is a step id, or { id, kind, label }');
@@ -5207,7 +5626,8 @@ function stepsToOps(steps) {
5207
5626
  place(a.id);
5208
5627
  const kind2 = typeof a.kind === "string" && a.kind !== "needs" ? a.kind : void 0;
5209
5628
  const label2 = typeof a.label === "string" && a.label.trim() ? a.label.trim() : void 0;
5210
- if (kind2 || label2) kinds.push({ op: "edge.set", from: a.id, to: id, ...kind2 ? { kind: kind2 } : {}, ...label2 ? { label: label2 } : {} });
5629
+ const options = Array.isArray(a.options) && a.options.length ? a.options : void 0;
5630
+ if (kind2 || label2 || options) kinds.push({ op: "edge.set", from: a.id, to: id, ...kind2 ? { kind: kind2 } : {}, ...label2 ? { label: label2 } : {}, ...options ? { options } : {} });
5211
5631
  }
5212
5632
  visiting.delete(id);
5213
5633
  placed.add(id);
@@ -5217,6 +5637,15 @@ function stepsToOps(steps) {
5217
5637
  for (const id of byId.keys()) place(id);
5218
5638
  return [...ops, ...kinds];
5219
5639
  }
5640
+ function planBeforeArchitecture(ctx, skip) {
5641
+ const a = ctx.arch.arch;
5642
+ if (!a) {
5643
+ if (skip) return void 0;
5644
+ return "Not yet: the architecture comes first. Call arch_draft to draw the architecture of the system as it will be (its people, services, parts and stores; mark every part that does not exist yet planned: true, in an empty repository that is all of them), then stop and say it is ready to review. The person approves it, and you are told with a [DiaCode] message to draw the plan. (If the person told you they do not want an architecture, call plan_create again with no_architecture: true.)";
5645
+ }
5646
+ if (a.phase === "draft") return "Not yet: the person has not approved the architecture. Stop and say you are waiting for them. Their approval is sent to you as a [DiaCode] message, and then you draw the plan on it.";
5647
+ return void 0;
5648
+ }
5220
5649
  var TOOLS = [...PLAN_TOOLS, ...ARCH_TOOLS];
5221
5650
  var isCall = (m) => Boolean(m) && typeof m === "object" && typeof m.method === "string";
5222
5651
  function createMcp({ store, arch: arch2, presence, stopped = () => void 0, version = "0" }) {
@@ -5250,7 +5679,7 @@ function createMcp({ store, arch: arch2, presence, stopped = () => void 0, versi
5250
5679
  const seen = s.seen.get(ARCH_KEY);
5251
5680
  out = await tool.run(a, s, ctx);
5252
5681
  if (arch2.exists) out = archChanges(out, ctx, s, seen);
5253
- return { content: [{ type: "text", text: out.text }], ...out.error ? { isError: true } : {} };
5682
+ return { content: [{ type: "text", text: withStage(out.text) }], ...out.error ? { isError: true } : {} };
5254
5683
  }
5255
5684
  planId = typeof a.plan === "string" ? a.plan : store.list().length === 1 ? store.list()[0].id : void 0;
5256
5685
  const before = planId && store.entries.has(planId) ? s.seen.get(planId) : void 0;
@@ -5262,10 +5691,16 @@ function createMcp({ store, arch: arch2, presence, stopped = () => void 0, versi
5262
5691
  out = { error: true, text: e instanceof HttpError ? message : `Something went wrong inside the plan server: ${message}` };
5263
5692
  }
5264
5693
  return {
5265
- content: [{ type: "text", text: out.text }],
5694
+ content: [{ type: "text", text: withStage(out.text) }],
5266
5695
  ...out.error ? { isError: true } : {}
5267
5696
  };
5268
5697
  }
5698
+ function withStage(text2) {
5699
+ const foot = footLine(flowNow({ store, arch: arch2, presence }).flow);
5700
+ return foot ? `${text2}
5701
+
5702
+ [DiaCode \xB7 ${foot}]` : text2;
5703
+ }
5269
5704
  function withChanges(out, id, before, s) {
5270
5705
  const rev = store.get(id).rev ?? 0;
5271
5706
  let text2 = out.text;
@@ -5584,6 +6019,14 @@ Your last attempt tried "${r.refused}", which is refused here and ended the sess
5584
6019
  }
5585
6020
  };
5586
6021
  }
6022
+ function plainFailure(raw) {
6023
+ const t = raw.replace(ANSI, "");
6024
+ 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.";
6025
+ if (/could not run|ENOENT|installed/i.test(t)) return "OpenCode is not installed, or is not on the PATH.";
6026
+ 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.";
6027
+ 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.";
6028
+ return "OpenCode could not answer. Run `opencode run hello` in a terminal to see why.";
6029
+ }
5587
6030
  function once({ root: root2, model, agent = "plan", bin = "opencode", timeoutMs = 24e4 }, prompt) {
5588
6031
  return new Promise((resolve7, reject) => {
5589
6032
  const args2 = ["run", "--dir", root2, "--format", "json", "--agent", agent, ...model ? ["--model", model] : [], prompt];
@@ -5593,7 +6036,7 @@ function once({ root: root2, model, agent = "plan", bin = "opencode", timeoutMs
5593
6036
  let err = "";
5594
6037
  const timer = setTimeout(() => {
5595
6038
  child.kill("SIGKILL");
5596
- reject(new Error(`OpenCode did not answer within ${Math.round(timeoutMs / 1e3)} seconds (a rate-limited model retries in silence)`));
6039
+ reject(new Error(plainFailure(`OpenCode did not answer within ${Math.round(timeoutMs / 1e3)} seconds`)));
5597
6040
  }, timeoutMs);
5598
6041
  child.stdout.on("data", (d) => {
5599
6042
  out += d;
@@ -5603,10 +6046,10 @@ function once({ root: root2, model, agent = "plan", bin = "opencode", timeoutMs
5603
6046
  });
5604
6047
  child.on("error", (e) => {
5605
6048
  clearTimeout(timer);
5606
- reject(new Error(
6049
+ reject(new Error(plainFailure(
5607
6050
  /** @type {any} */
5608
6051
  e.code === "ENOENT" ? `could not run "${bin}": is OpenCode installed?` : e.message
5609
- ));
6052
+ )));
5610
6053
  });
5611
6054
  child.on("close", () => {
5612
6055
  clearTimeout(timer);
@@ -5614,14 +6057,14 @@ function once({ root: root2, model, agent = "plan", bin = "opencode", timeoutMs
5614
6057
  for (const line of out.split("\n")) {
5615
6058
  try {
5616
6059
  const e = JSON.parse(line);
5617
- if (e.type === "error") return reject(new Error(String(e.error?.data?.message ?? e.error?.name ?? "OpenCode reported an error")));
6060
+ if (e.type === "error") return reject(new Error(plainFailure(String(e.error?.data?.message ?? e.error?.name ?? "OpenCode reported an error"))));
5618
6061
  if (e.type === "text" && typeof e.part?.text === "string") texts.push(e.part.text);
5619
6062
  } catch {
5620
6063
  }
5621
6064
  }
5622
6065
  if (texts.length) return resolve7({ text: texts.join("\n") });
5623
6066
  const refused2 = /permission requested: (.+?); auto-rejecting/.exec(err.replace(ANSI, ""));
5624
- return refused2 ? resolve7({ refused: refused2[1] }) : reject(new Error(err.replace(ANSI, "").trim().split("\n").pop() || "OpenCode said nothing"));
6067
+ return refused2 ? resolve7({ refused: refused2[1] }) : reject(new Error(plainFailure(err.replace(ANSI, "").trim().split("\n").pop() || "OpenCode said nothing")));
5625
6068
  });
5626
6069
  });
5627
6070
  }
@@ -6137,9 +6580,11 @@ var SILENT_MS = 15 * 6e4;
6137
6580
  var OURS = /(^|[^a-z])(plan_list|plan_read|plan_create|plan_edit|step_start|step_done|step_failed|step_wait|step_ask)$|^dcursed_/;
6138
6581
  var Agents = class {
6139
6582
  /**
6140
- * @param {{ store: import('./store.js').PlanStore, presence: import('./presence.js').Presence, now?: () => number }} options
6583
+ * @param {{ store: import('./store.js').PlanStore, presence: import('./presence.js').Presence, now?: () => number, stage?: () => string }} options
6584
+ * `stage`: what the agent is told about where the work stands (flow.js), at the start of a turn; nothing while a plan runs
6141
6585
  */
6142
- constructor({ store, presence, now = Date.now }) {
6586
+ constructor({ store, presence, now = Date.now, stage = () => "" }) {
6587
+ this.stage = stage;
6143
6588
  this.store = store;
6144
6589
  this.presence = presence;
6145
6590
  this.now = now;
@@ -6175,7 +6620,8 @@ var Agents = class {
6175
6620
  }
6176
6621
  this.say(actor, s, ev.event === "prompt");
6177
6622
  if (b.text && b.plan) this.presence.noteRead(actor, b.plan, b.rev ?? 0);
6178
- return b.text ? { context: b.text, ...s.plan ? { plan: s.plan } : {} } : {};
6623
+ const context = [this.stage(), b.text].filter(Boolean).join("\n\n");
6624
+ return context ? { context, ...s.plan ? { plan: s.plan } : {} } : {};
6179
6625
  }
6180
6626
  case "invocation": {
6181
6627
  const first = s.rev === 0 && !s.plan;
@@ -6187,7 +6633,8 @@ var Agents = class {
6187
6633
  }
6188
6634
  this.say(actor, s, true);
6189
6635
  if (b.text && b.plan) this.presence.noteRead(actor, b.plan, b.rev ?? 0);
6190
- return this.merge(s, b.text ? { context: b.text, ...s.plan ? { plan: s.plan } : {} } : {});
6636
+ const context = [this.stage(), b.text].filter(Boolean).join("\n\n");
6637
+ return this.merge(s, context ? { context, ...s.plan ? { plan: s.plan } : {} } : {});
6191
6638
  }
6192
6639
  const told = await this.after(actor, s, { event: "tool-after", tool: "invocation" });
6193
6640
  this.say(actor, s, true);
@@ -6454,6 +6901,44 @@ var EventRing = class {
6454
6901
  // packages/server/src/permissions.js
6455
6902
  import { EventEmitter as EventEmitter6 } from "node:events";
6456
6903
  import { randomBytes } from "node:crypto";
6904
+ function runsAnything(r) {
6905
+ if (r.toolName !== "Bash") return false;
6906
+ const c = (r.ruleContent ?? "").trim();
6907
+ if (!c || /^[*:\s]+$/.test(c)) return true;
6908
+ 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);
6909
+ }
6910
+ function alwaysFrom(suggestions) {
6911
+ if (!Array.isArray(suggestions)) return void 0;
6912
+ for (const s of suggestions) {
6913
+ if (!s || typeof s !== "object") continue;
6914
+ if (s.type === "setMode" && s.mode === "acceptEdits") return { label: "file edits", update: { type: "setMode", mode: "acceptEdits", destination: "session" } };
6915
+ if (s.type !== "addRules" || s.behavior !== "allow" || !Array.isArray(s.rules) || !s.rules.length || s.rules.length > 8) continue;
6916
+ if (s.rules.some((r) => r && typeof r.toolName === "string" && runsAnything({ toolName: r.toolName, ruleContent: typeof r.ruleContent === "string" ? r.ruleContent : void 0 }))) continue;
6917
+ if (s.rules.some((r) => r && r.toolName === "Bash" && typeof r.ruleContent === "string" && !/(:|\s)\*$/.test(r.ruleContent))) continue;
6918
+ const rules = [];
6919
+ for (const r of s.rules) {
6920
+ if (!r || typeof r.toolName !== "string" || !r.toolName || r.toolName.length > 200) break;
6921
+ if (r.ruleContent !== void 0 && (typeof r.ruleContent !== "string" || r.ruleContent.length > 500)) break;
6922
+ rules.push({ toolName: r.toolName, ...r.ruleContent !== void 0 ? { ruleContent: r.ruleContent } : {} });
6923
+ }
6924
+ if (rules.length !== s.rules.length) continue;
6925
+ const clip2 = (t) => {
6926
+ const one = t.replace(/\s+/g, " ").trim();
6927
+ return one.length > 50 ? `${one.slice(0, 49)}\u2026` : one;
6928
+ };
6929
+ const where = (r) => {
6930
+ const verb = { Read: "reading anything", Edit: "editing anything", Write: "writing anything", MultiEdit: "editing anything", Glob: "listing anything", Grep: "searching anything" }[
6931
+ /** @type {'Read'} */
6932
+ r.toolName
6933
+ ];
6934
+ const path = r.ruleContent?.match(/^(\/\/?[^*]*?)\/?\*\*$/)?.[1];
6935
+ return verb && path ? `${verb} under ${clip2(path.replace(/^\/\//, "/"))}` : void 0;
6936
+ };
6937
+ 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`)))];
6938
+ return { label: words.join(", ").slice(0, 140), update: { type: "addRules", rules, behavior: "allow", destination: "session" } };
6939
+ }
6940
+ return void 0;
6941
+ }
6457
6942
  function describeRequest(tool, input2) {
6458
6943
  const clip2 = (s) => {
6459
6944
  const t = String(s ?? "").replace(/\s+/g, " ").trim();
@@ -6475,10 +6960,10 @@ var Permissions = class extends EventEmitter6 {
6475
6960
  /**
6476
6961
  * An agent asks. Resolves with your decision, or with nothing when it is answered elsewhere, `holdMs` passes, or the
6477
6962
  * request is cancelled (the hook went away). A newer prompt from the same session replaces an older one.
6478
- * @param {{ actor: string, session?: string, tool: string, input: Record<string, any>, holdMs: number }} ask
6963
+ * @param {{ actor: string, session?: string, tool: string, input: Record<string, any>, holdMs: number, suggestions?: unknown }} ask
6479
6964
  * @returns {{ permission: Permission, result: Promise<Decision | null>, cancel: () => void }}
6480
6965
  */
6481
- ask({ actor, session, tool, input: input2, holdMs }) {
6966
+ ask({ actor, session, tool, input: input2, holdMs, suggestions }) {
6482
6967
  this.heard(actor, session);
6483
6968
  const id = randomBytes(9).toString("base64url");
6484
6969
  let done = () => {
@@ -6487,14 +6972,15 @@ var Permissions = class extends EventEmitter6 {
6487
6972
  done = resolve7;
6488
6973
  });
6489
6974
  let timer;
6490
- const permission = { id, actor, ...session ? { session } : {}, tool, what: describeRequest(tool, input2), at: new Date(this.now()).toISOString() };
6975
+ const always = alwaysFrom(suggestions);
6976
+ const permission = { id, actor, ...session ? { session } : {}, tool, what: describeRequest(tool, input2), at: new Date(this.now()).toISOString(), ...always ? { always: { label: always.label } } : {} };
6491
6977
  const settle = (d) => {
6492
6978
  clearTimeout(timer);
6493
6979
  if (!this.pending.delete(id)) return;
6494
6980
  done(d);
6495
6981
  this.emit("change", { id, settled: d?.behavior ?? "released" });
6496
6982
  };
6497
- this.pending.set(id, { ...permission, settle });
6983
+ this.pending.set(id, { ...permission, settle, ...always ? { offer: always } : {} });
6498
6984
  timer = setTimeout(() => settle(null), holdMs);
6499
6985
  timer.unref?.();
6500
6986
  this.emit("change", { id, asked: true });
@@ -6502,16 +6988,18 @@ var Permissions = class extends EventEmitter6 {
6502
6988
  }
6503
6989
  /** The prompts waiting, oldest first, for one agent or all. @param {string} [actor] @returns {Permission[]} */
6504
6990
  list(actor) {
6505
- return [...this.pending.values()].filter((p) => !actor || p.actor === actor).map(({ settle: _s, ...p }) => p);
6991
+ return [...this.pending.values()].filter((p) => !actor || p.actor === actor).map(({ settle: _s, offer: _o, ...p }) => p);
6506
6992
  }
6507
6993
  /**
6508
6994
  * Your answer. @param {string} id @param {'allow' | 'deny'} decision @param {string} [reason] for a deny: the agent is told it
6509
- * @returns {boolean} whether it was still waiting
6995
+ * @param {boolean} [always] for an allow: and do not ask again for what Claude Code offered (this session only)
6996
+ * @returns {boolean | 'no-always'} whether it was still waiting; `no-always`: it was, but offered no such choice (nothing was answered)
6510
6997
  */
6511
- decide(id, decision, reason) {
6998
+ decide(id, decision, reason, always = false) {
6512
6999
  const p = this.pending.get(id);
6513
7000
  if (!p) return false;
6514
- 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." });
7001
+ if (always && (decision !== "allow" || !p.offer)) return "no-always";
7002
+ 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." });
6515
7003
  return true;
6516
7004
  }
6517
7005
  /**
@@ -6547,10 +7035,14 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
6547
7035
  const ring = new EventRing(100, { log: debug ? (line) => console.error(line) : void 0 });
6548
7036
  const store = new PlanStore(root2, { now });
6549
7037
  const archStore = new ArchStore(root2, { now });
7038
+ const opencodeReplans = rc.enabled ?? Boolean(rc.run || rc.auto || rc.model || rc.bin);
6550
7039
  const reconciler = new Reconciler(store, { run: rc.run ?? openCodeRunner({ root: root2, model: rc.model, bin: rc.bin }) });
6551
7040
  const presence = new Presence(presenceOptions);
6552
7041
  const repoFiles = new RepoFiles(root2);
6553
- const agents = new Agents({ store, presence });
7042
+ const agents = new Agents({ store, presence, stage: () => {
7043
+ const f = flowNow({ store, arch: archStore, presence });
7044
+ return agentBrief(f.flow, { plan: f.plan });
7045
+ } });
6554
7046
  const calls = new Calls({
6555
7047
  ...callOptions,
6556
7048
  store,
@@ -6576,7 +7068,7 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
6576
7068
  return agents2.map((a) => {
6577
7069
  const b = a.state === "gone" && on.has(a.actor) ? { ...a, state: "idle" } : a;
6578
7070
  const p = permissions.list(a.actor)[0];
6579
- return p ? { ...b, state: "asking", detail: `wants to ${p.what}`, permission: { id: p.id, what: p.what, tool: p.tool } } : b;
7071
+ return p ? { ...b, state: "asking", detail: `wants to ${p.what}`, permission: { id: p.id, what: p.what, tool: p.tool, ...p.always ? { always: p.always } : {} } } : b;
6580
7072
  });
6581
7073
  };
6582
7074
  const mcp = createMcp({ store, arch: archStore, presence, stopped: (actor) => calls.stoppedFor(actor), version: VERSION });
@@ -6598,7 +7090,7 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
6598
7090
  (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}`));
6599
7091
  });
6600
7092
  const pending = /* @__PURE__ */ new Map();
6601
- if (rc.auto) {
7093
+ if (rc.auto && opencodeReplans) {
6602
7094
  store.on("change", (e) => {
6603
7095
  const failed = e.line?.actor !== "opencode:reconciler" && (e.line?.ops ?? []).find((o) => o.op === "status.set" && o.status === "failed");
6604
7096
  if (failed) {
@@ -6665,7 +7157,15 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
6665
7157
  }
6666
7158
  const url = new URL(req.url ?? "/", "http://localhost");
6667
7159
  const parts = url.pathname.split("/").filter(Boolean).map(decodeURIComponent);
6668
- 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] });
7160
+ 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], replanner: opencodeReplans ? "opencode" : "agent" });
7161
+ if (req.method === "GET" && url.pathname === "/api/flow") {
7162
+ const f = flowNow({ store, arch: archStore, presence });
7163
+ const p2 = (
7164
+ /** @type {any} */
7165
+ f.plan
7166
+ );
7167
+ return send2(res, 200, { ...f.flow, plan: p2?.id ?? null, planInfo: p2 ? { id: p2.id, phase: p2.phase, steps: p2.steps, done: p2.done } : null, waiting: f.waits, listening: calls.listening() });
7168
+ }
6669
7169
  if (req.method === "GET" && url.pathname === "/api/diagnostics") {
6670
7170
  return send2(res, 200, { version: VERSION, api: API_VERSION, node: process.versions.node, platform: `${process.platform}-${process.arch}`, uptimeSeconds: Math.round((Date.now() - startedAt) / 1e3), plans: store.list().length, events: ring.list() });
6671
7171
  }
@@ -6747,12 +7247,13 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
6747
7247
  if (parts.length === 2 && req.method === "GET") return send2(res, 200, { permissions: permissions.list() });
6748
7248
  if (parts.length === 3 && req.method === "POST") {
6749
7249
  if (whoOf(req).actor !== "you") throw new HttpError(403, "only you answer a permission prompt");
6750
- const { decision, reason } = (
6751
- /** @type {{ decision?: unknown, reason?: unknown }} */
7250
+ const { decision, reason, always } = (
7251
+ /** @type {{ decision?: unknown, reason?: unknown, always?: unknown }} */
6752
7252
  await body(req)
6753
7253
  );
6754
7254
  if (decision !== "allow" && decision !== "deny") throw new HttpError(400, "decision is allow or deny");
6755
- const ok2 = permissions.decide(parts[2], decision, typeof reason === "string" ? reason : void 0);
7255
+ const ok2 = permissions.decide(parts[2], decision, typeof reason === "string" ? reason : void 0, always === true);
7256
+ 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` });
6756
7257
  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" });
6757
7258
  }
6758
7259
  }
@@ -6788,12 +7289,13 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
6788
7289
  }
6789
7290
  if (req.method === "GET" && parts[0] === "api" && parts[1] === "brief" && parts.length === 2) {
6790
7291
  const asked = req.headers["x-dcursed-agent"] === void 0 ? void 0 : whoOf(req).actor;
6791
- const { text: text2, plan: plan2, rev } = store.brief(url.searchParams.get("plan") ?? void 0, asked);
7292
+ const { text: planText, plan: plan2, rev } = store.brief(url.searchParams.get("plan") ?? void 0, asked);
7293
+ const text2 = [agents.stage(), planText].filter(Boolean).join("\n\n");
6792
7294
  return sendText(res, 200, text2, plan2 === void 0 ? {} : { "x-dcursed-plan": plan2, "x-dcursed-rev": String(rev) });
6793
7295
  }
6794
7296
  if (req.method === "GET" && parts[0] === "api" && parts[1] === "events" && parts.length === 2) return listEvents(req, res);
6795
7297
  if (parts[0] === "api" && parts[1] === "architecture") {
6796
- 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());
7298
+ 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());
6797
7299
  if (parts.length === 2 && req.method === "POST") return send2(res, 201, await archStore.create(
6798
7300
  /** @type {any} */
6799
7301
  await body(req),
@@ -6854,6 +7356,12 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
6854
7356
  /** @type {{ steps?: unknown, kind?: unknown, step?: unknown }} */
6855
7357
  await body(req)
6856
7358
  );
7359
+ if (!opencodeReplans) {
7360
+ if (kind !== void 0 && kind !== "review" && kind !== "failure" && kind !== "drift") throw new HttpError(400, "kind is review, failure or drift");
7361
+ if (kind === "failure" && typeof step3 !== "string") throw new HttpError(400, 'a failure re-plan names the step that failed: { kind: "failure", step }');
7362
+ if (steps !== void 0 && !(Array.isArray(steps) && steps.every((s) => typeof s === "string"))) throw new HttpError(400, "steps is a list of step ids");
7363
+ return send2(res, 202, { call: calls.askAgent(id, { kind: kind === "failure" || kind === "drift" ? kind : "review", ...typeof step3 === "string" ? { step: step3 } : {}, ...Array.isArray(steps) ? { steps } : {} }) });
7364
+ }
6857
7365
  if (kind === "failure") {
6858
7366
  if (typeof step3 !== "string") throw new HttpError(400, 'a failure re-plan names the step that failed: { kind: "failure", step }');
6859
7367
  return send2(res, 202, { job: reconciler.startFailure(id, step3) });
@@ -6863,6 +7371,16 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
6863
7371
  if (steps !== void 0 && !(Array.isArray(steps) && steps.every((s) => typeof s === "string"))) throw new HttpError(400, "steps is a list of step ids");
6864
7372
  return send2(res, 202, { job: reconciler.start(id, steps) });
6865
7373
  }
7374
+ if (parts.length === 4 && parts[3] === "drift" && req.method === "POST") {
7375
+ if (whoOf(req).actor !== "you") throw new HttpError(403, "only you decide that a file outside the plan needs no step");
7376
+ const { ignore } = (
7377
+ /** @type {{ ignore?: unknown }} */
7378
+ await body(req)
7379
+ );
7380
+ if (ignore !== true && typeof ignore !== "string") throw new HttpError(400, "ignore is a file path, or true for all of them");
7381
+ store.get(id);
7382
+ return send2(res, 200, { ignored: store.ignoreOutside(id, ignore === true ? void 0 : ignore) });
7383
+ }
6866
7384
  if (parts.length === 4 && parts[3] === "observe" && req.method === "POST") {
6867
7385
  const who = whoOf(req);
6868
7386
  if (who.actor === "you") throw new HttpError(400, "observe is for a harness plugin: send x-dcursed-agent: <harness>:<agent>");
@@ -6898,7 +7416,7 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
6898
7416
  function plan(id) {
6899
7417
  const view = store.get(id);
6900
7418
  const stalled = presence.stalled(view.plan);
6901
- 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 } } : {} };
7419
+ 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 } } : {} };
6902
7420
  }
6903
7421
  function stoppingOn(id) {
6904
7422
  return [...calls.stops.keys()].filter((actor) => calls.stoppedFor(actor) === id).sort();
@@ -7040,7 +7558,8 @@ data: ${JSON.stringify(data)}
7040
7558
  }
7041
7559
  const session = typeof payload.session_id === "string" ? payload.session_id : void 0;
7042
7560
  const input2 = payload.tool_input && typeof payload.tool_input === "object" ? payload.tool_input : {};
7043
- const asked = permissions.ask({ actor, session, tool, input: input2, holdMs: holdOf(url, HOLD.hook) });
7561
+ if (debug) ring.add("hook", `permission ${tool}: suggestions ${JSON.stringify(payload.permission_suggestions ?? null).slice(0, 600)}`);
7562
+ const asked = permissions.ask({ actor, session, tool, input: input2, holdMs: holdOf(url, HOLD.hook), suggestions: payload.permission_suggestions });
7044
7563
  const pid = Number(url.searchParams.get("pid"));
7045
7564
  agents.handle(actor, { event: "asking", session, detail: `wants to ${asked.permission.what}`, ...Number.isInteger(pid) && pid > 1 ? { pid } : {} }).catch(() => {
7046
7565
  });
@@ -7247,7 +7766,7 @@ ${END}`;
7247
7766
  ` : rules.includes(BEGIN) && rules.includes(END) ? rules.replace(new RegExp(`${escape(BEGIN)}[\\s\\S]*?${escape(END)}`), () => block) : `${rules.replace(/\n*$/, "\n\n")}${block}
7248
7767
  `;
7249
7768
  said.push(await put(rulesPath, next, "AGENTS.md (how to work with the plan)"));
7250
- said.push("", serveHint(port2));
7769
+ said.push("", FLOW_HINT, "", serveHint(port2));
7251
7770
  return said;
7252
7771
  }
7253
7772
  function escape(s) {
@@ -7276,6 +7795,25 @@ var askHook = (port2, harness, hook, agent) => `curl -s --max-time 2 -X POST -H
7276
7795
  var ALLOW_TOOLS = "mcp__dcursed";
7277
7796
  var WAKE_SECONDS = 86400;
7278
7797
  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`;
7798
+ var ACCEPT_EDITS_WORDS = [
7799
+ "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",
7800
+ "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",
7801
+ "does anything outside this folder. It is in .claude/settings.local.json, which is not committed. `init claude-code --remove` takes it out again.",
7802
+ "Claude Code's folder-trust dialog lists the allow rule (mcp__dcursed) but does not mention this mode, so this message, `doctor` and that file are where it is written down."
7803
+ ];
7804
+ async function setAcceptEdits(root2) {
7805
+ const rel = ".claude/settings.local.json";
7806
+ const path = join4(root2, rel);
7807
+ const { data, ok: ok2 } = await readJson(path);
7808
+ if (!ok2) return [`NOT DONE ${rel}: it has comments or is not plain JSON, so add this yourself:
7809
+ "permissions": { "defaultMode": "acceptEdits" }`];
7810
+ const was = data?.permissions?.defaultMode;
7811
+ 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.`];
7812
+ data.permissions = data.permissions ?? {};
7813
+ data.permissions.defaultMode = "acceptEdits";
7814
+ return [await put(path, `${JSON.stringify(data, null, 2)}
7815
+ `, `${rel} (Claude Code's mode: accept edits)`), ...ACCEPT_EDITS_WORDS];
7816
+ }
7279
7817
  var PERMISSION_SECONDS = 600;
7280
7818
  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`;
7281
7819
  var ownRules = (root2, rel, text2, what) => put(join4(root2, rel), text2, `${rel} (${what})`);
@@ -7314,7 +7852,7 @@ async function letGitSeeAgain(root2, rel) {
7314
7852
  await writeFile2(file, rest);
7315
7853
  return `updated ${file.startsWith(`${root2}/`) ? file.slice(root2.length + 1) : file} (our line for ${rel} removed)`;
7316
7854
  }
7317
- async function initClaudeCode({ root: root2, port: port2 = 7300, agent = "main", shared = false }) {
7855
+ async function initClaudeCode({ root: root2, port: port2 = 7300, agent = "main", shared = false, acceptEdits = false }) {
7318
7856
  const p = String(port2);
7319
7857
  const said = [];
7320
7858
  const url = `http://127.0.0.1:${p}/mcp/claude-code?agent=${encodeURIComponent(agent)}`;
@@ -7355,8 +7893,15 @@ async function initClaudeCode({ root: root2, port: port2 = 7300, agent = "main",
7355
7893
  const kept = await keepOutOfGit(root2, ".claude/settings.local.json");
7356
7894
  if (kept) said.push(kept);
7357
7895
  }
7896
+ if (acceptEdits) {
7897
+ said.push(...await setAcceptEdits(root2));
7898
+ if (shared) {
7899
+ const kept = await keepOutOfGit(root2, ".claude/settings.local.json");
7900
+ if (kept) said.push(kept);
7901
+ }
7902
+ }
7358
7903
  said.push(await ownRules(root2, ".claude/rules/dcursed.md", `${RULES_BODY}`, "how to work with the plan"));
7359
- said.push("", serveHint(port2), "Then start a new Claude Code session in this folder (approve the dcursed MCP server when asked).");
7904
+ said.push("", FLOW_HINT, "", serveHint(port2), "Then start a new Claude Code session in this folder (approve the dcursed MCP server when asked).");
7360
7905
  return said;
7361
7906
  }
7362
7907
  async function initCursor({ root: root2, port: port2 = 7300, agent = "agent" }) {
@@ -7391,7 +7936,7 @@ alwaysApply: true
7391
7936
  ---
7392
7937
 
7393
7938
  ${RULES_BODY}`, "how to work with the plan"));
7394
- said.push("", serveHint(port2), "Then enable the dcursed server in Cursor Settings \u2192 MCP, and start a new chat.");
7939
+ said.push("", FLOW_HINT, "", serveHint(port2), "Then enable the dcursed server in Cursor Settings \u2192 MCP, and start a new chat.");
7395
7940
  return said;
7396
7941
  }
7397
7942
  async function initAntigravity({ root: root2, port: port2 = 7300, agent = "agent" }) {
@@ -7420,11 +7965,11 @@ description: How to work with this repository's DiaCode plans
7420
7965
  ---
7421
7966
 
7422
7967
  ${RULES_BODY}`, "how to work with the plan"));
7423
- said.push("", serveHint(port2), "Then trust this folder in Antigravity (workspace hooks load only for a trusted folder) and start a new conversation.");
7968
+ said.push("", FLOW_HINT, "", serveHint(port2), "Then trust this folder in Antigravity (workspace hooks load only for a trusted folder) and start a new conversation.");
7424
7969
  return said;
7425
7970
  }
7426
7971
  var HARNESS_INIT = (
7427
- /** @type {Record<string, (o: { root: string, port?: number, agent?: string, shared?: boolean }) => Promise<string[]>>} */
7972
+ /** @type {Record<string, (o: { root: string, port?: number, agent?: string, shared?: boolean, acceptEdits?: boolean }) => Promise<string[]>>} */
7428
7973
  {
7429
7974
  opencode: initOpenCode,
7430
7975
  "claude-code": initClaudeCode,
@@ -7524,7 +8069,11 @@ async function removeClaudeCode({ root: root2 }) {
7524
8069
  pruneEmpty(d.permissions, "allow");
7525
8070
  pruneEmpty(d, "permissions");
7526
8071
  }
7527
- }, (d) => onlyOurs(d), /\/hooks\/claude-code\/|mcp__dcursed/, 'the hooks whose address contains /hooks/claude-code/, and the "mcp__dcursed" allow rule'));
8072
+ if (rel === ".claude/settings.local.json" && d.permissions?.defaultMode === "acceptEdits") {
8073
+ delete d.permissions.defaultMode;
8074
+ pruneEmpty(d, "permissions");
8075
+ }
8076
+ }, (d) => onlyOurs(d), /\/hooks\/claude-code\/|mcp__dcursed|"defaultMode":\s*"acceptEdits"/, 'the hooks whose address contains /hooks/claude-code/, the "mcp__dcursed" allow rule, and "defaultMode": "acceptEdits" in settings.local.json'));
7528
8077
  }
7529
8078
  said.push(await drop(root2, ".claude/rules/dcursed.md", "the rules"));
7530
8079
  const unhidden = await letGitSeeAgain(root2, ".claude/settings.local.json");
@@ -7645,7 +8194,9 @@ async function hooksEntry(root2, files, harness, events, hooksOf) {
7645
8194
  return { finding: ok(`all ${events.length} hooks are set, in ${where}`), ports: [...new Set(ports)] };
7646
8195
  }
7647
8196
  async function rulesFile(root2, rel, what) {
7648
- return await text(root2, rel) === null ? problem(`${rel} is missing: ${what}`, "{init}") : ok(`${rel} (how to work with the plan)`);
8197
+ const t = await text(root2, rel);
8198
+ if (t === null) return problem(`${rel} is missing: ${what}`, "{init}");
8199
+ return t.includes("THE ORDER") ? ok(`${rel} (how to work with the plan)`) : problem(`${rel} is from an older DiaCode: it does not tell the agent the order (architecture, then plan, then Start)`, "{init}");
7649
8200
  }
7650
8201
  async function openCode(root2) {
7651
8202
  const configFile = await text(root2, "opencode.json") !== null ? "opencode.json" : await text(root2, "opencode.jsonc") !== null ? "opencode.jsonc" : "opencode.json";
@@ -7667,7 +8218,7 @@ async function openCode(root2) {
7667
8218
  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}"));
7668
8219
  else findings.push(ok(".dcursed/opencode-plugin.js is this version's plugin"));
7669
8220
  const agents = await text(root2, "AGENTS.md");
7670
- findings.push(agents?.includes(BEGIN) ? ok("AGENTS.md (how to work with the plan)") : problem("AGENTS.md has no DiaCode block: the agent is not told how to work with the plan", "{init}"));
8221
+ 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}"));
7671
8222
  return { harness: "opencode", label: "OpenCode", ports, findings };
7672
8223
  }
7673
8224
  async function claudeCode(root2) {
@@ -7698,6 +8249,8 @@ async function claudeCode(root2) {
7698
8249
  if (hookText.includes("/hooks/claude-code/Stop") && !hookText.includes(ALLOW_TOOLS)) {
7699
8250
  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)`));
7700
8251
  }
8252
+ const local = present[1] ?? "";
8253
+ 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."));
7701
8254
  return { harness: "claude-code", label: "Claude Code", ports: [...mcp.ports, ...hooks.ports], findings };
7702
8255
  }
7703
8256
  async function cursor(root2) {
@@ -7789,6 +8342,25 @@ async function liveChecks(port2, root2, connections) {
7789
8342
  }
7790
8343
  return out;
7791
8344
  }
8345
+ async function replannerFindings(port2, connections) {
8346
+ let health = null;
8347
+ try {
8348
+ health = await (await fetch(`http://127.0.0.1:${port2}/api/health`, { signal: AbortSignal.timeout(1500) })).json();
8349
+ } catch {
8350
+ }
8351
+ if (health?.replanner === "opencode") {
8352
+ return [
8353
+ 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"),
8354
+ 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")
8355
+ ];
8356
+ }
8357
+ const wakes = connections.filter((c) => c.harness === "claude-code" || c.harness === "opencode").map((c) => c.label);
8358
+ const others = connections.filter((c) => c.harness === "cursor" || c.harness === "antigravity").map((c) => c.label);
8359
+ return [
8360
+ 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"),
8361
+ ...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`)] : []
8362
+ ];
8363
+ }
7792
8364
  async function diagnose({ root: root2, port: port2 }) {
7793
8365
  root2 = resolve4(root2);
7794
8366
  const sections = [];
@@ -7818,7 +8390,7 @@ async function diagnose({ root: root2, port: port2 }) {
7818
8390
  }
7819
8391
  sections.push({ title: "The plan server", findings: await liveChecks(chosen, root2, connections) });
7820
8392
  for (const c of connections) sections.push({ title: c.label, findings: c.findings });
7821
- 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.`)] });
8393
+ sections.push({ title: "The re-planner", findings: await replannerFindings(chosen, connections) });
7822
8394
  const flags = `${resolve4(root2) === process.cwd() ? "" : ` --root ${root2}`} --port ${chosen}`;
7823
8395
  for (const s of sections) {
7824
8396
  const harness = connections.find((c) => c.label === s.title)?.harness;
@@ -7836,7 +8408,7 @@ function formatReport(report) {
7836
8408
  if (f.fix) lines.push(` ${f.fix}`);
7837
8409
  }
7838
8410
  }
7839
- lines.push("", report.problems ? `${report.problems} problem${report.problems === 1 ? "" : "s"}.` : "Nothing is wrong that this can see.");
8411
+ lines.push("", report.problems ? `${report.problems} problem${report.problems === 1 ? "" : "s"}.` : "Nothing is wrong that this can see.", "", FLOW_HINT);
7840
8412
  return lines.join("\n").replace(/^\n/, "");
7841
8413
  }
7842
8414
  function redact(text2, root2) {
@@ -7951,12 +8523,16 @@ var cmd = invocation();
7951
8523
  var usage = [
7952
8524
  `diacode ${VERSION}: a plan you and your coding agents share`,
7953
8525
  "",
7954
- `usage: ${cmd} init <opencode|claude-code|cursor|antigravity|all> [--root <repo>] [--port 7300] [--agent <name>] [--shared] [--remove]`,
8526
+ `usage: ${cmd} init <opencode|claude-code|cursor|antigravity|all> [--root <repo>] [--port 7300] [--agent <name>] [--shared] [--accept-edits] [--remove]`,
7955
8527
  " connect a repository to an agent (its MCP entry, hooks or plugin, and rules);",
7956
- " --shared puts Claude Code's hooks in the committed .claude/settings.json, not your own settings.local.json",
8528
+ " --shared puts Claude Code's hooks in the committed .claude/settings.json, not your own settings.local.json;",
8529
+ " --accept-edits (Claude Code only, off unless you ask) sets its mode to accept edits in settings.local.json: it then edits files in",
8530
+ " the folder, and runs mkdir, touch, rm, rmdir, mv, cp and sed there, without asking; --remove takes it out again",
7957
8531
  " --remove takes out again only what init wrote, and leaves your plans and your own settings",
7958
8532
  ` ${cmd} serve [--root <repo>] [--port 7300] [--reconcile auto|manual] [--reconciler-model <provider/model>]`,
7959
- " the plan server, and the editor at http://127.0.0.1:<port>/",
8533
+ " the plan server, and the editor at http://127.0.0.1:<port>/;",
8534
+ ' "Should the plan cover this?" and the other re-plan buttons ask the agent you connected; --reconcile or --reconciler-model',
8535
+ " make them run a separate OpenCode session instead (OpenCode must be installed and signed in)",
7960
8536
  ` ${cmd} doctor [--root <repo>] [--port <n>] [--report]`,
7961
8537
  " check that the repository, the agents and the server fit together;",
7962
8538
  " --report prints the findings with what the server has noticed, paths replaced, to paste into an issue",
@@ -7998,7 +8574,8 @@ if (args[0] === "--version" || args[0] === "-v" || args[0] === "version") {
7998
8574
  // Itself and nothing else, unless told: any page on a port such as :8080 is some other program's.
7999
8575
  // (`npm run dev` needs no flag: Vite's proxy presents the server's own origin for the dev page.)
8000
8576
  allowedOrigins: origins,
8001
- reconciler: { auto: option("reconcile", "manual") === "auto", model: option("reconciler-model"), bin: option("opencode") },
8577
+ // The re-planner buttons ask the agent you connected. OpenCode does that job only when you set it up for it, here.
8578
+ reconciler: { enabled: args.includes("--reconcile") || args.includes("--reconciler-model") || args.includes("--opencode"), auto: option("reconcile", "manual") === "auto", model: option("reconciler-model"), bin: option("opencode") },
8002
8579
  ...option("editor") ? { editor: resolve6(
8003
8580
  /** @type {string} */
8004
8581
  option("editor")
@@ -8052,13 +8629,21 @@ Use that one, or stop it first (Ctrl-C in its terminal, or kill ${lock.held.pid}
8052
8629
  } else if (args[0] === "init" && args[1] && (args[1] === "all" || args[1] in HARNESS_INIT)) {
8053
8630
  const which = args[1] === "all" ? Object.keys(HARNESS_INIT) : [args[1]];
8054
8631
  const remove = args.includes("--remove");
8632
+ if (args.includes("--accept-edits") && !which.includes("claude-code")) {
8633
+ console.error("--accept-edits is for Claude Code: use it with `init claude-code` (or `init all`).");
8634
+ process.exit(1);
8635
+ }
8636
+ if (args.includes("--accept-edits") && remove) {
8637
+ console.error("--accept-edits is for adding it; `init claude-code --remove` takes it out again.");
8638
+ process.exit(1);
8639
+ }
8055
8640
  for (const h of which) {
8056
8641
  console.log(`\u2500\u2500 ${h}`);
8057
8642
  if (remove) {
8058
8643
  for (const line of await HARNESS_REMOVE[h]({ root })) console.log(line);
8059
8644
  continue;
8060
8645
  }
8061
- for (const line of await HARNESS_INIT[h]({ root, port, ...option("agent") ? { agent: option("agent") } : {}, shared: args.includes("--shared") })) console.log(line);
8646
+ 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);
8062
8647
  }
8063
8648
  if (remove) console.log(`
8064
8649
  Plans stay where they are: ${plansDir(root)}`);