diacode 0.2.0 → 0.2.2

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 = (
@@ -312,12 +312,14 @@ function validateBatch(batch) {
312
312
  var isFinished = (n) => n.kind === "context" || n.status === "done" || n.status === "cancelled";
313
313
  var checkpointsBefore = (plan, id) => plan.edges.filter((e) => e.to === id && CHECKPOINTS.has(e.kind ?? "needs") && !e.passed);
314
314
  var isRunning = (plan) => plan.phase === "executing" || plan.phase === "paused";
315
+ var isApproved = (plan) => plan.phase === "approved" || isRunning(plan);
315
316
  function checkpointWords(e) {
316
317
  if (e.kind === "approve") return `the person to approve ${e.from}'s result`;
317
318
  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
319
  return `input from the person${e.label ? ` (${e.label})` : ""}`;
319
320
  }
320
321
  var isStructural = (op) => STRUCTURAL.has(op.op) || op.op === "plan.set" && (op.title !== void 0 || op.goal !== void 0);
322
+ 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
323
  var Refusal = class extends Error {
322
324
  };
323
325
  var refuse = (why) => {
@@ -328,7 +330,7 @@ function applyBatch(plan, ops, who) {
328
330
  const problems = validateOp(ops[i]);
329
331
  if (problems.length) return { kind: "rejected", index: i, op: ops[i], why: problems.join("; ") };
330
332
  }
331
- if ((isRunning(plan) || who.propose) && who.actor !== "you" && ops.some(isStructural)) {
333
+ if ((isApproved(plan) || who.propose) && who.actor !== "you" && ops.some(isStructural)) {
332
334
  const structural = ops.filter(isStructural);
333
335
  const rest = ops.filter((op) => !isStructural(op));
334
336
  const dry = run(plan, structural, { ...who, actor: "you" });
@@ -423,7 +425,7 @@ function step(p, op, ctx) {
423
425
  ["status", "statusFrom", "statusBy", "note", "owner"]
424
426
  ) delete n[k];
425
427
  ctx.touched.add(op.id);
426
- const meaningChanged = n.label !== before.label || n.kind !== before.kind || n.detail !== before.detail || JSON.stringify(n.files) !== JSON.stringify(before.files);
428
+ const meaningChanged = n.kind !== before.kind || n.detail !== before.detail || JSON.stringify(n.files) !== JSON.stringify(before.files);
427
429
  if (meaningChanged) {
428
430
  for (const [d, dist] of downstreamOf(p, op.id, true)) affect(d, dist, `${op.id} changed`);
429
431
  sharers(op.id, [...before.files ?? [], ...n.files ?? []], "changed");
@@ -510,6 +512,7 @@ function step(p, op, ctx) {
510
512
  if (frozen(op.id)) refuse(`${op.id} is done; only you can reopen it`);
511
513
  if (!you && n.owner && n.owner !== who.actor) refuse(`${op.id} is ${n.owner}'s`);
512
514
  if (op.status === "cancelled" && !you) refuse("only you cancel a step; an agent proposes removing it");
515
+ if (op.status === "in_progress" && !you && (p.phase === "planning" || p.phase === "approved")) refuse(notStarted(p));
513
516
  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
517
  if ((op.status === "in_progress" || op.status === "done") && !you) {
515
518
  const waiting = prerequisitesOf(p, op.id).filter((f) => !isFinished(p.nodes[f]));
@@ -535,6 +538,7 @@ function step(p, op, ctx) {
535
538
  if (n.kind === "context") refuse(`${op.id} is context; nobody works on it`);
536
539
  if (!you && n.owner && n.owner !== who.actor) refuse(`${op.id} is ${n.owner}'s`);
537
540
  if (!you && p.phase === "paused" && n.owner !== who.actor) refuse("the person paused the plan: start nothing new until they resume it");
541
+ if (!you && (p.phase === "planning" || p.phase === "approved")) refuse(notStarted(p));
538
542
  n.owner = who.actor;
539
543
  return op;
540
544
  }
@@ -563,7 +567,7 @@ function step(p, op, ctx) {
563
567
  case "plan.stop":
564
568
  if (!you) refuse("only the person stops the plan");
565
569
  if (!isRunning(p)) refuse(`the plan is ${p.phase}, not running: there is nothing to stop`);
566
- p.phase = "planning";
570
+ p.phase = "approved";
567
571
  for (const [id, n] of Object.entries(p.nodes)) {
568
572
  if (n.status === "in_progress" || n.status === "waiting") reopen(p, id, { status: "not_started", note: "stopped by you", who });
569
573
  else if (n.owner) delete n.owner;
@@ -1146,7 +1150,7 @@ function arrange(items, depends, direction, lanes = false) {
1146
1150
  /** @type {Item} */
1147
1151
  all.find((i) => i.id === id)
1148
1152
  );
1149
- const flowOf = (b) => direction === "LR" ? b.w : b.h;
1153
+ const flowOf2 = (b) => direction === "LR" ? b.w : b.h;
1150
1154
  const crossOf = (b) => direction === "LR" ? b.h : b.w;
1151
1155
  const slot = Math.max(...items.map(crossOf)) + g.cross;
1152
1156
  const members = (k) => (
@@ -1162,7 +1166,7 @@ function arrange(items, depends, direction, lanes = false) {
1162
1166
  let cursor2 = 0;
1163
1167
  let lastGap = 0;
1164
1168
  for (const k of ranks) {
1165
- const thick = Math.max(...members(k).map((id) => flowOf(sizeOf(id))));
1169
+ const thick = Math.max(...members(k).map((id) => flowOf2(sizeOf(id))));
1166
1170
  flowAt.set(k, cursor2 + thick / 2);
1167
1171
  lastGap = direction === "LR" ? Math.max(g.gap, labelAfter(k)) : g.gap;
1168
1172
  cursor2 += thick + lastGap;
@@ -1417,13 +1421,14 @@ function describeAttention({ lines, plan, actor, since }) {
1417
1421
  if (op.phase !== void 0 && op.phase !== phase) {
1418
1422
  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
1423
  else if (news && op.phase === "executing" && phase === "paused") say(`${who} resumed the plan. Read it with plan_read and carry on.`);
1424
+ 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
1425
  phase = op.phase;
1421
1426
  }
1422
1427
  break;
1423
1428
  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.`);
1429
+ 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
1430
  held.clear();
1426
- phase = "planning";
1431
+ phase = "approved";
1427
1432
  break;
1428
1433
  case "gate.pass":
1429
1434
  if (news && (asked.has(`${op.from}\0${op.to}`) || finished.has(op.from))) {
@@ -1960,6 +1965,54 @@ function importDiagram(text2, filename = "") {
1960
1965
  };
1961
1966
  }
1962
1967
 
1968
+ // packages/core/src/flow.js
1969
+ var AT = { task: 0, architecture: 1, "plan-wait": 2, plan: 2, start: 3, running: 4, done: 5 };
1970
+ function activePlan(plans) {
1971
+ for (const group of [["executing", "paused"], ["approved"], ["planning"]]) {
1972
+ const found = plans.filter((p) => group.includes(p.phase));
1973
+ if (found.length) return found[found.length - 1];
1974
+ }
1975
+ return void 0;
1976
+ }
1977
+ function flowOf({ arch: arch2, plan, waiting = 0, busy = false, finished = false }) {
1978
+ const live = plan && plan.phase !== "done" && plan.phase !== "abandoned" ? plan : void 0;
1979
+ const at = (stage, next, label, line, why) => ({ stage, at: AT[stage], next, label, why, line });
1980
+ if (live && (live.phase === "executing" || live.phase === "paused")) {
1981
+ 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.");
1982
+ }
1983
+ if (arch2?.phase === "draft") {
1984
+ return at(
1985
+ "architecture",
1986
+ "approveArchitecture",
1987
+ "Approve architecture",
1988
+ 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."
1989
+ );
1990
+ }
1991
+ if (live?.phase === "approved") {
1992
+ 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;
1993
+ return at(
1994
+ "start",
1995
+ "start",
1996
+ "Start",
1997
+ 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.",
1998
+ why
1999
+ );
2000
+ }
2001
+ if (live) {
2002
+ return at(
2003
+ "plan",
2004
+ "approvePlan",
2005
+ "Approve plan",
2006
+ "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."
2007
+ );
2008
+ }
2009
+ if (arch2?.phase === "accepted") {
2010
+ 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.`);
2011
+ 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.");
2012
+ }
2013
+ 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.");
2014
+ }
2015
+
1963
2016
  // packages/core/src/arch/index.js
1964
2017
  var arch_exports = {};
1965
2018
  __export(arch_exports, {
@@ -2318,7 +2371,8 @@ function applyBatch2(arch2, ops, who) {
2318
2371
  const problems = validateOp2(ops[i]);
2319
2372
  if (problems.length) return { kind: "rejected", index: i, op: ops[i], why: problems.join("; ") };
2320
2373
  }
2321
- if ((arch2.phase === "accepted" || who.propose) && who.actor !== "you" && ops.some(isStructural2)) {
2374
+ const bookkeeping = who.actor.startsWith("server:") && !who.propose;
2375
+ if ((arch2.phase === "accepted" || who.propose) && who.actor !== "you" && !bookkeeping && ops.some(isStructural2)) {
2322
2376
  const structural = ops.filter(isStructural2);
2323
2377
  const rest = ops.filter((op) => !isStructural2(op));
2324
2378
  const dry = run2(arch2, structural, { ...who, actor: "you" });
@@ -3323,6 +3377,7 @@ var HttpError = class extends Error {
3323
3377
  };
3324
3378
  var DRIFT_IGNORED = /(^|\/)(\.dcursed|\.opencode|\.git|node_modules|dist|build|coverage)\/|(^|\/)(package-lock\.json|yarn\.lock|pnpm-lock\.yaml)$/;
3325
3379
  var same3 = (a, b) => JSON.stringify(canonicalPlan(a)) === JSON.stringify(canonicalPlan(b));
3380
+ var LIVE = /* @__PURE__ */ new Set(["planning", "approved", "executing", "paused"]);
3326
3381
  var PlanStore = class extends EventEmitter {
3327
3382
  /**
3328
3383
  * @param {string} root the repository; plans live in <root>/.dcursed/plans/
@@ -3424,7 +3479,8 @@ var PlanStore = class extends EventEmitter {
3424
3479
  plan: e.plan,
3425
3480
  layout: e.layout,
3426
3481
  derived: { blocked: Object.fromEntries(blocked), held: Object.fromEntries(held), gates, ready: [...ready], proposed: Object.fromEntries(proposed), atRisk: Object.fromEntries(atRisk), progress },
3427
- review: Object.fromEntries(e.review),
3482
+ // A finished plan is history: what was flagged while it ran no longer asks anything of you (reopen it and it does).
3483
+ review: e.plan.phase === "done" ? {} : Object.fromEntries(e.review),
3428
3484
  // The latest changes, newest last: who did what, for the editor's Changes panel.
3429
3485
  recent: e.log.filter((l) => !l.snapshot).slice(-30),
3430
3486
  error: e.error
@@ -3520,7 +3576,7 @@ var PlanStore = class extends EventEmitter {
3520
3576
  * @param {string} actor @returns {string | undefined}
3521
3577
  */
3522
3578
  planFor(actor) {
3523
- const live = [...this.entries].filter(([, e]) => e.plan && (e.plan.phase === "planning" || e.plan.phase === "executing"));
3579
+ const live = [...this.entries].filter(([, e]) => e.plan && LIVE.has(e.plan.phase));
3524
3580
  if (live.length === 1) return live[0][0];
3525
3581
  const latest = ([, e]) => e.log.filter((l) => l.actor === actor).at(-1)?.at ?? "";
3526
3582
  const newest = (list) => [...list].sort((a, b) => latest(b).localeCompare(latest(a)))[0]?.[0];
@@ -3542,7 +3598,10 @@ var PlanStore = class extends EventEmitter {
3542
3598
  return view.plan ? { text: describeBrief(view), plan: id, rev: view.rev } : { text: "" };
3543
3599
  };
3544
3600
  if (planId) return one(planId);
3545
- const live = this.list().filter((p) => p.title !== void 0 && (p.phase === "planning" || p.phase === "executing"));
3601
+ const live = this.list().filter((p) => p.title !== void 0 && LIVE.has(
3602
+ /** @type {string} */
3603
+ p.phase
3604
+ ));
3546
3605
  if (!live.length) return { text: "" };
3547
3606
  if (live.length === 1) return one(live[0].id);
3548
3607
  const mine = actor ? this.planFor(actor) : void 0;
@@ -3745,6 +3804,8 @@ import { EventEmitter as EventEmitter2 } from "node:events";
3745
3804
  import { watch as watch2, mkdirSync as mkdirSync2 } from "node:fs";
3746
3805
  var arch = arch_exports;
3747
3806
  var FOOTPRINT_ACTOR = "server:footprint";
3807
+ var PLAN_ACTOR = "server:plan";
3808
+ var PLAN_TO_COME = "next";
3748
3809
  var same4 = (a, b) => JSON.stringify(arch.canonicalArch(a)) === JSON.stringify(arch.canonicalArch(b));
3749
3810
  var newLayout2 = () => newLayout(arch.LAYOUT_OF);
3750
3811
  var ArchStore = class extends EventEmitter2 {
@@ -3910,6 +3971,22 @@ var ArchStore = class extends EventEmitter2 {
3910
3971
  since(baseRev) {
3911
3972
  return this.log.filter((l) => l.rev > baseRev && !l.snapshot);
3912
3973
  }
3974
+ /**
3975
+ * A plan was drawn on this architecture: whatever an agent marked `planned: true` (stored as the plan to come, `next`) is that plan's,
3976
+ * so that when it is done the person is asked to make it real. Bookkeeping, so it lands at once.
3977
+ * @param {string} planId
3978
+ */
3979
+ adoptPlanned(planId) {
3980
+ return this.enqueue(async () => {
3981
+ const a = this.arch;
3982
+ if (!a || this.error) return null;
3983
+ const ops = [];
3984
+ for (const [id, b] of Object.entries(a.nodes)) if (b.planned === PLAN_TO_COME) ops.push({ op: "box.set", id, planned: planId });
3985
+ 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 });
3986
+ if (!ops.length) return null;
3987
+ return this.applyNow({ baseRev: a.rev, reason: `these belong to the plan ${planId}`, ops }, { actor: PLAN_ACTOR, via: "server" });
3988
+ });
3989
+ }
3913
3990
  /**
3914
3991
  * 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
3915
3992
  * architecture, so it waits for you as a proposal; nothing happens if the plan changed nothing in it, or the proposal is
@@ -4072,20 +4149,28 @@ function parseLayout2(text2) {
4072
4149
  import { randomUUID } from "node:crypto";
4073
4150
 
4074
4151
  // packages/server/src/guide.js
4075
- 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.
4152
+ var FLOW_HINT = "How it goes: tell your agent the task. It draws the architecture in the editor; you change what is wrong and press Approve architecture. It draws the plan; you change it and press Approve plan. It checks the architecture against the plan and asks you about any change; then you press Start. After that, a change you make on one side is told to the agent, which proposes the matching change on the other.";
4153
+ var GUIDE = `DiaCode keeps this repository's architecture and plans as files in .dcursed/, and the person edits them in a diagram while you work, so they change under you.
4154
+
4155
+ THE ORDER. The person approves each stage in the editor before the next; do the stage you are in, then STOP and say it is ready.
4156
+ 1. THE TASK. When the person gives you something to build or change, your first and only job is the ARCHITECTURE: call arch_draft with the system AS IT WILL BE (who uses it, the services, the parts inside them, the stores and queues, and how they use each other). Mark every part that does not exist yet planned: true. An empty repository is no excuse: draw what you are about to build. Then stop and say in a sentence that it is ready to review. Do not call plan_create, do not write code, and do not ask the person questions in your own window: assume what you need, say so in the architecture (the goal, a box's detail), and they correct the drawing.
4157
+ 2. THEY APPROVE THE ARCHITECTURE. You are sent a message that starts with [DiaCode]. Draw the PLAN on it with plan_create, then stop and say it is ready to review. A question the task told you to ask before building (or at some point in the build) is an ask checkpoint on the arrow into the first step that needs the answer: that step gets after: [{ "id": "<a step before it>", "kind": "ask", "label": "<the question>" }] (a short first step such as "Set up the project" will do as the step before). When that step is next, you call step_ask on it, the step the arrow points at, and end your turn; the person answers in the editor, so do not ask it in your window and do not make a step of its own for asking. If you did ask in your window, write their answer into the detail of the step it concerns.
4158
+ 3. THEY APPROVE THE PLAN. You are sent a [DiaCode] message: the plan is NOT started. Check the architecture against it, once: every part the plan adds is a box (planned: true while it does not exist), every part it removes is marked retiring, each step lists the boxes it changes as touches. Fix what is missing with arch_edit; your changes to an approved architecture arrive as proposals the person accepts or rejects, so give each a plain reason. Then stop and say what you changed, or that nothing needed to change. Do not start any step.
4159
+ 4. THEY PRESS START. You are sent a [DiaCode] message: carry the plan out, below.
4160
+ 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.
4161
+ Each DiaCode tool's answer ends with the stage you are at. When it says to wait, wait.
4076
4162
 
4077
- How to work with it
4163
+ How to work with a plan
4078
4164
  - 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.
4079
4165
  - Some arrows say more. "order only" (after): B comes later but does not use what A makes. A CHECKPOINT is where the person comes in before B starts: they approve A's result, they give input B needs, or (ask) you ask them first with step_ask and end your turn. A step that WAITS AT A CHECKPOINT cannot be started until the person passes it; you are sent their answer when they do.
4080
4166
  - 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.
4081
4167
  - 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.
4082
- - 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.
4168
+ - 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.
4083
4169
  - 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.
4084
4170
  - 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.
4085
- - 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.
4086
- - 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.
4087
- - 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.
4088
- - 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.
4171
+ - 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.
4172
+ - Once the person has approved a plan, changes to its structure (steps, arrows, labels) become proposals the person accepts; statuses and claims land at once. Finished steps are history: you cannot rewrite them.
4173
+ - 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.
4089
4174
  - 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.
4090
4175
  - Do not edit the files in .dcursed/plans/ by hand. The tools check the rules and keep the log.
4091
4176
 
@@ -4093,16 +4178,16 @@ Working while the person watches
4093
4178
  - 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.
4094
4179
 
4095
4180
  The architecture
4096
- - 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.
4181
+ - The repository has one ARCHITECTURE, in .dcursed/architecture.json: the system as the person has approved it, which every plan is a change to. Its boxes are person, service, component, store, queue or group (external: someone else runs it); an arrow from A to B means A USES B (not "A first"); a box sits only in a service or a group, and a box with boxes inside it is a frame that takes no arrows. Flows are the ordered steps of what a user does, over those arrows.
4097
4182
  - 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.
4098
- - 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.
4099
- - 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.
4183
+ - arch_read shows it; read it before you plan work that changes the system. arch_draft makes the first one (only when there is none; a repository that already has code is drawn from the code and the task together). A plan is refused until the person has approved an architecture.
4184
+ - 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.
4100
4185
  - Do not edit .dcursed/architecture.json by hand either.`;
4101
4186
 
4102
4187
  // packages/server/src/calls.js
4103
4188
  import { EventEmitter as EventEmitter3 } from "node:events";
4104
4189
  var ARCH_SCOPE = "@architecture";
4105
- var HELD_WHILE_BUSY = /* @__PURE__ */ new Set(["changed", "archAccepted", "archSettled"]);
4190
+ var HELD_WHILE_BUSY = /* @__PURE__ */ new Set(["changed", "archAccepted", "archSettled", "archChanged"]);
4106
4191
  var KEEP = 50;
4107
4192
  var GAP_MS = 5e3;
4108
4193
  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"]);
@@ -4176,7 +4261,9 @@ var Calls = class extends EventEmitter3 {
4176
4261
  for (const op of line.ops ?? []) {
4177
4262
  if (op.op === "plan.set" && op.phase === "executing" && was === "paused") {
4178
4263
  phased = true;
4179
- for (const to of this.resumers(id)) this.make({ plan: id, rev: line.rev, kind: "resumed", to, text: resumedText(plan, id) });
4264
+ for (const to of this.resumers(id)) {
4265
+ this.make({ plan: id, rev: line.rev, kind: "resumed", to, text: resumedText(plan, id, this.bothSides(id, to, line.rev)) });
4266
+ }
4180
4267
  } else if (op.op === "plan.set" && op.phase === "executing") {
4181
4268
  phased = true;
4182
4269
  for (const [actor, o] of this.stops) if (o.plan === id) this.stops.delete(actor);
@@ -4184,7 +4271,15 @@ var Calls = class extends EventEmitter3 {
4184
4271
  const archToo = was === "planning" && this.arch?.arch?.phase === "draft" && to !== void 0 && this.archDrafter() === to;
4185
4272
  if (archToo) this.acceptArch().catch(() => {
4186
4273
  });
4187
- this.make({ plan: id, rev: line.rev, kind: "approved", to, text: approvedText(plan, id, { archToo }) });
4274
+ this.make({ plan: id, rev: line.rev, kind: "started", to, text: startedText(plan, id, { archToo, again: was === "approved" && this.statusesStarted(id) }) });
4275
+ } else if (op.op === "plan.set" && op.phase === "approved") {
4276
+ phased = true;
4277
+ for (const [actor, o] of this.stops) if (o.plan === id) this.stops.delete(actor);
4278
+ const to = this.worker(id);
4279
+ const archToo = was === "planning" && this.arch?.arch?.phase === "draft" && to !== void 0 && this.archDrafter() === to;
4280
+ if (archToo) this.acceptArch().catch(() => {
4281
+ });
4282
+ this.make({ plan: id, rev: line.rev, kind: "planApproved", to, text: planApprovedText(plan, id, { archToo, hasArch: Boolean(this.arch?.exists) }) });
4188
4283
  } else if (op.op === "plan.set" && op.phase) {
4189
4284
  phased = true;
4190
4285
  this.dropQueued(id);
@@ -4206,7 +4301,7 @@ var Calls = class extends EventEmitter3 {
4206
4301
  if (who) tell.add(who);
4207
4302
  }
4208
4303
  }
4209
- if (!phased && plan.phase === "executing") for (const actor of tell) this.soon(id, actor, line.rev);
4304
+ if (!phased && (plan.phase === "executing" || plan.phase === "approved")) for (const actor of tell) this.soon(id, actor, line.rev);
4210
4305
  }
4211
4306
  /**
4212
4307
  * A batch landed on the architecture. Only yours can make a call. Accepting the draft an agent drew tells it that its
@@ -4219,9 +4314,13 @@ var Calls = class extends EventEmitter3 {
4219
4314
  if (!arch2 || line.actor !== "you" || line.proposed || quiet) return;
4220
4315
  const log = this.arch?.log ?? [];
4221
4316
  const settled = /* @__PURE__ */ new Map();
4317
+ let edited = false;
4222
4318
  for (const op of line.ops ?? []) {
4223
4319
  if (op.op === "arch.set" && op.phase === "accepted" && phaseWas === "draft") {
4224
- this.make({ plan: ARCH_SCOPE, rev, kind: "archAccepted", to: this.archDrafter(), text: archAcceptedText(arch2) });
4320
+ const live2 = this.livePlan();
4321
+ this.make({ plan: ARCH_SCOPE, rev, kind: "archAccepted", to: this.archDrafter() ?? (live2 ? this.worker(live2.id) : void 0), text: archAcceptedText(arch2, live2?.phase) });
4322
+ } else if (arch_exports.STRUCTURAL.has(op.op) || op.op === "arch.set" && (op.title !== void 0 || op.goal !== void 0)) {
4323
+ edited = true;
4225
4324
  } else if (op.op === "proposal.accept" || op.op === "proposal.reject") {
4226
4325
  const made = [...log].reverse().find((l) => l.proposed === op.id && l.rev < rev);
4227
4326
  if (!made || made.actor.startsWith("server:")) continue;
@@ -4231,6 +4330,77 @@ var Calls = class extends EventEmitter3 {
4231
4330
  }
4232
4331
  }
4233
4332
  for (const [to, notes] of settled) this.archSettled(to, rev, notes);
4333
+ const live = this.livePlan();
4334
+ if (edited && live && (live.phase === "approved" || live.phase === "executing")) {
4335
+ const actor = this.worker(live.id);
4336
+ if (actor) this.soonArch(live.id, actor, rev);
4337
+ }
4338
+ }
4339
+ /**
4340
+ * The plan being worked on: the one running, else the one waiting for Start, else a draft (see core's `activePlan`).
4341
+ * @returns {{ id: string, phase: string } | undefined}
4342
+ */
4343
+ livePlan() {
4344
+ const plans = this.store.list().filter((p) => p.title !== void 0);
4345
+ return activePlan(
4346
+ /** @type {Array<{ id: string, phase: string }>} */
4347
+ plans
4348
+ );
4349
+ }
4350
+ /**
4351
+ * Your edits to the architecture, for the agent working on the plan: told a moment after the last one, like your edits to
4352
+ * the plan, so a box added, named and connected is one call.
4353
+ * @param {string} planId @param {string} actor @param {number} rev
4354
+ */
4355
+ soonArch(planId, actor, rev) {
4356
+ const key2 = `${ARCH_SCOPE}\0${actor}`;
4357
+ const was = this.pending.get(key2);
4358
+ if (was) clearTimeout(was.timer);
4359
+ const from = was?.from ?? rev;
4360
+ const timer = setTimeout(() => {
4361
+ this.pending.delete(key2);
4362
+ this.archChanged(planId, actor, from, rev);
4363
+ }, this.changeMs);
4364
+ timer.unref?.();
4365
+ this.pending.set(key2, { from, timer });
4366
+ }
4367
+ /**
4368
+ * Tell the agent what you changed in the architecture from `from` to `rev`, unless it has been shown that already (it read the
4369
+ * architecture since). Not while the plan is paused: Resume says it, with what changed on the plan.
4370
+ * @param {string} planId @param {string} actor @param {number} from @param {number} rev
4371
+ */
4372
+ archChanged(planId, actor, from, rev) {
4373
+ const plan = this.store.get(planId).plan;
4374
+ const a = this.arch?.arch;
4375
+ if (!plan || !a || plan.phase !== "executing" && plan.phase !== "approved") return;
4376
+ if (!this.lastHeard.has(actor) && ![...this.waiters].some((w) => w.actor === actor)) return;
4377
+ const seen = this.seen(actor, ARCH_SCOPE);
4378
+ if (seen !== void 0 && seen >= rev) return;
4379
+ for (const c of this.calls) if (c.plan === ARCH_SCOPE && c.to === actor && c.kind === "archChanged" && c.state === "queued") this.settle(c, "dropped");
4380
+ const since = Math.min(seen ?? from - 1, from - 1);
4381
+ const lines = arch_exports.describeChanges(this.arch?.since(since) ?? [], since, { not: actor });
4382
+ if (!lines.length) return;
4383
+ this.make({ plan: ARCH_SCOPE, rev, kind: "archChanged", to: actor, text: archChangedText(plan, planId, a, lines) });
4384
+ }
4385
+ /**
4386
+ * What you changed on the plan and on the architecture since this agent last looked, for the message that wakes it when a
4387
+ * paused plan resumes: Pause is where you edit, and both sides are said once.
4388
+ * @param {string} id @param {string} actor @param {number} [before] only what happened before this revision of the plan (the Resume itself is not news)
4389
+ * @returns {{ plan: string[], arch: string[] }}
4390
+ */
4391
+ bothSides(id, actor, before = Infinity) {
4392
+ const seenPlan = this.seen(actor, id);
4393
+ const seenArch = this.seen(actor, ARCH_SCOPE);
4394
+ return {
4395
+ plan: seenPlan === void 0 ? [] : describeChanges(this.store.changesSince(id, seenPlan).filter((l) => l.rev < before), seenPlan, { not: actor }),
4396
+ arch: seenArch === void 0 || !this.arch ? [] : arch_exports.describeChanges(this.arch.since(seenArch), seenArch, { not: actor })
4397
+ };
4398
+ }
4399
+ /** Has anything been done on this plan, so that Start is a carry-on and not a first start? @param {string} id */
4400
+ statusesStarted(id) {
4401
+ const plan = this.store.get(id).plan;
4402
+ if (Object.values(plan?.nodes ?? {}).some((n) => n.status !== void 0 && n.status !== "not_started")) return true;
4403
+ return (this.store.entries.get(id)?.log ?? []).some((l) => (l.ops ?? []).some((o) => o.op === "plan.stop"));
4234
4404
  }
4235
4405
  /**
4236
4406
  * Tell an agent what you decided about its proposals. One that is still waiting for the agent's turn to end is said again
@@ -4245,7 +4415,7 @@ var Calls = class extends EventEmitter3 {
4245
4415
  this.settle(c, "dropped");
4246
4416
  }
4247
4417
  }
4248
- const made = this.make({ plan: ARCH_SCOPE, rev, kind: "archSettled", to, text: archSettledText(this.arch?.arch, all) });
4418
+ const made = this.make({ plan: ARCH_SCOPE, rev, kind: "archSettled", to, text: archSettledText(this.arch?.arch, all, { drawPlan: !this.livePlan() }) });
4249
4419
  if (made) made.notes = all;
4250
4420
  }
4251
4421
  /**
@@ -4289,7 +4459,7 @@ var Calls = class extends EventEmitter3 {
4289
4459
  if (l.proposed) continue;
4290
4460
  const ops = l.ops ?? [];
4291
4461
  for (let j = ops.length - 1; j >= 0; j--) {
4292
- if (ops[j].op === "plan.stop") return "planning";
4462
+ if (ops[j].op === "plan.stop") return "approved";
4293
4463
  if (ops[j].op === "plan.set" && ops[j].phase) return ops[j].phase;
4294
4464
  }
4295
4465
  }
@@ -4429,14 +4599,15 @@ var Calls = class extends EventEmitter3 {
4429
4599
  */
4430
4600
  changed(id, actor, from, rev) {
4431
4601
  const plan = this.store.get(id).plan;
4432
- if (!plan || plan.phase !== "executing") return;
4602
+ if (!plan || plan.phase !== "executing" && plan.phase !== "approved") return;
4433
4603
  if (!this.lastHeard.has(actor) && ![...this.waiters].some((w) => w.actor === actor)) return;
4434
4604
  const seen = this.seen(actor, id);
4435
4605
  if (seen !== void 0 && seen >= rev) return;
4436
4606
  for (const c of this.calls) if (c.plan === id && c.to === actor && c.kind === "changed" && c.state === "queued") this.settle(c, "dropped");
4437
4607
  const since = seen ?? from - 1;
4438
4608
  const changes = describeChanges(this.store.changesSince(id, since), since, { not: actor });
4439
- this.make({ plan: id, rev, kind: "changed", to: actor, text: changedText(plan, id, this.store.attentionFor(id, actor, since), changes) });
4609
+ const sync = this.store.changesSince(id, since).some((l) => l.actor === "you" && !l.proposed && (l.ops ?? []).some((o) => STRUCTURAL.has(o.op) || o.op === "plan.set" && (o.title !== void 0 || o.goal !== void 0)));
4610
+ this.make({ plan: id, rev, kind: "changed", to: actor, text: changedText(plan, id, this.store.attentionFor(id, actor, since), changes, { sync }) });
4440
4611
  }
4441
4612
  /** The revision of a plan an agent was last shown, if it ever was. @param {string} actor @param {string} id */
4442
4613
  seen(actor, id) {
@@ -4514,8 +4685,9 @@ var Calls = class extends EventEmitter3 {
4514
4685
  }
4515
4686
  const plan = this.store.get(call.plan).plan;
4516
4687
  if (!plan) return false;
4517
- if (call.kind === "approved" || call.kind === "resumed") return plan.phase === "executing";
4518
- if (call.kind === "stopped") return plan.phase === "planning" && call.to !== void 0 && this.stoppedFor(call.to) === call.plan;
4688
+ if (call.kind === "started" || call.kind === "resumed") return plan.phase === "executing";
4689
+ if (call.kind === "planApproved") return plan.phase === "approved";
4690
+ if (call.kind === "stopped") return plan.phase === "approved" && call.to !== void 0 && this.stoppedFor(call.to) === call.plan;
4519
4691
  if (call.kind === "passed") {
4520
4692
  const e = call.gate && plan.edges.find((x) => x.from === call.gate?.from && x.to === call.gate?.to);
4521
4693
  return plan.phase === "executing" && Boolean(e?.passed) && (plan.nodes[call.gate?.to ?? ""]?.status ?? "not_started") === "not_started";
@@ -4523,7 +4695,7 @@ var Calls = class extends EventEmitter3 {
4523
4695
  if (call.kind === "sentBack") return plan.phase === "executing" && plan.nodes[call.step ?? ""]?.status === "not_started";
4524
4696
  if (call.kind === "changed") {
4525
4697
  const seen = call.to ? this.seen(call.to, call.plan) : void 0;
4526
- return plan.phase === "executing" && !(seen !== void 0 && seen >= call.rev);
4698
+ return (plan.phase === "executing" || plan.phase === "approved") && !(seen !== void 0 && seen >= call.rev);
4527
4699
  }
4528
4700
  const n = call.step ? plan.nodes[call.step] : void 0;
4529
4701
  return Boolean(n && n.owner === call.to && n.status === "in_progress");
@@ -4617,15 +4789,28 @@ var Calls = class extends EventEmitter3 {
4617
4789
  this.pending.clear();
4618
4790
  }
4619
4791
  };
4620
- function approvedText(plan, id, { archToo = false } = {}) {
4792
+ function planApprovedText(plan, id, { archToo = false, hasArch = true } = {}) {
4793
+ return [
4794
+ `[DiaCode] The person approved the plan "${plan.title}" (${id}) in the editor${archToo ? ", and with it the architecture you drew" : ""}. It is NOT started: do not start any step; they press Start when the architecture and the plan are final.`,
4795
+ 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.",
4796
+ "Then stop, and say in a sentence what you changed in the architecture (or that nothing needed to change). The person accepts or rejects each change, then presses Start; the Start is sent to you as another [DiaCode] message."
4797
+ ].join("\n");
4798
+ }
4799
+ function startedText(plan, id, { archToo = false, again = false } = {}) {
4621
4800
  return [
4622
- `[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:`,
4801
+ `[DiaCode] The person pressed Start${again ? " again" : ""} on the plan "${plan.title}" (${id}) in the editor${archToo ? ", and approved the architecture you drew with it (your changes to the architecture are proposals from now on)" : ""}. Carry it out now with the dcursed tools, one step at a time:`,
4623
4802
  "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.",
4624
- "If a step is unclear, stop on it with step_wait and say what you need."
4803
+ "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."
4625
4804
  ].join(" ");
4626
4805
  }
4627
- function resumedText(plan, id) {
4628
- 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.`;
4806
+ function resumedText(plan, id, sides = { plan: [], arch: [] }) {
4807
+ const clip2 = (s) => s.length > 400 ? `${s.slice(0, 399)}\u2026` : s;
4808
+ return [
4809
+ `[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.`,
4810
+ ...sides.plan.length ? ["While it was paused they changed the plan:", ...sides.plan.slice(-20).map((c) => `- ${clip2(c)}`)] : [],
4811
+ ...sides.arch.length ? ["While it was paused they changed the architecture:", ...sides.arch.slice(-20).map((c) => `- ${clip2(c)}`)] : [],
4812
+ ...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."] : []
4813
+ ].join("\n");
4629
4814
  }
4630
4815
  function stopOrder(id) {
4631
4816
  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.`;
@@ -4653,30 +4838,109 @@ function answeredText(plan, id, step3, answer) {
4653
4838
  return `[DiaCode] The person answered your question on step ${step3}${label ? ` ("${label}")` : ""} in plan ${id}: ${answer}
4654
4839
  Carry on with ${step3} using that answer.`;
4655
4840
  }
4656
- function changedText(plan, id, attention, changes) {
4841
+ function changedText(plan, id, attention, changes, { sync = true } = {}) {
4657
4842
  const clip2 = (s) => s.length > 400 ? `${s.slice(0, 399)}\u2026` : s;
4843
+ const waiting = plan.phase === "approved";
4658
4844
  return [
4659
4845
  `[DiaCode] While you were between turns, the person changed the plan "${plan.title}" (${id}) in the editor.`,
4660
4846
  ...attention.length ? ["HEADS UP, about your steps:", ...attention.map((a) => `- ${clip2(a)}`)] : [],
4661
4847
  ...changes.length ? ["What changed:", ...changes.slice(-20).map((c) => `- ${clip2(c)}`)] : [],
4662
- "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."
4848
+ sync ? "Read the plan with plan_read. Then make the architecture agree: if what they changed adds, removes or reconnects a part of the system (a box, an arrow, a service), propose the matching change with arch_edit, giving a plain reason; if the architecture needs nothing, say so." : "Read the plan with plan_read. If they settled a proposal of yours, adjust what depended on it.",
4849
+ waiting ? "The plan is not started: do not start any step, and stop when you have said what you changed or that nothing needed to." : "Then carry on with what is left for you. A finished step is the person's to reopen: if one of those changed, say whether it needs reopening. If nothing is left for you to do, say so and stop."
4850
+ ].join("\n");
4851
+ }
4852
+ function archChangedText(plan, id, arch2, lines) {
4853
+ const clip2 = (s) => s.length > 400 ? `${s.slice(0, 399)}\u2026` : s;
4854
+ return [
4855
+ `[DiaCode] The person changed the architecture ("${arch2.title}") in the editor:`,
4856
+ ...lines.slice(-20).map((l) => `- ${clip2(l)}`),
4857
+ `Read it with arch_read, then make the plan "${plan.title}" (${id}) agree: if a step no longer matches (a box was removed that a step builds or changes, a part was added that no step builds, a step's files moved), propose the matching change with plan_edit, giving a plain reason. If the plan needs nothing, say so.`,
4858
+ 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."
4663
4859
  ].join("\n");
4664
4860
  }
4665
- function archAcceptedText(arch2) {
4861
+ function archAcceptedText(arch2, planPhase) {
4862
+ 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\`.`;
4863
+ if (planPhase === "planning") {
4864
+ 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");
4865
+ }
4866
+ if (planPhase === "approved" || planPhase === "executing" || planPhase === "paused") {
4867
+ 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");
4868
+ }
4666
4869
  return [
4667
- `[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\`.`,
4668
- "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."
4870
+ head,
4871
+ '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.'
4669
4872
  ].join("\n");
4670
4873
  }
4671
- function archSettledText(arch2, notes) {
4874
+ function archSettledText(arch2, notes, { drawPlan = false } = {}) {
4672
4875
  const clip2 = (s) => s.length > 400 ? `${s.slice(0, 399)}\u2026` : s;
4673
4876
  return [
4674
4877
  `[DiaCode] The person settled ${notes.length === 1 ? "your proposal" : "your proposals"} to the architecture${arch2 ? ` ("${arch2.title}")` : ""}:`,
4675
4878
  ...notes.slice(-20).map((n) => `- ${clip2(n)}`),
4676
- "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."
4879
+ 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."
4677
4880
  ].join("\n");
4678
4881
  }
4679
4882
 
4883
+ // packages/server/src/flow.js
4884
+ function flowNow({ store, arch: arch2, presence }) {
4885
+ const plans = store.list().filter((p) => p.title !== void 0);
4886
+ const plan = activePlan(
4887
+ /** @type {Array<{ id: string, phase: string, proposals?: number }>} */
4888
+ plans
4889
+ );
4890
+ const a = arch2.arch;
4891
+ const busy = [...presence?.agents?.values() ?? []].some((e) => presence?.shown(
4892
+ /** @type {any} */
4893
+ e
4894
+ ) === "working");
4895
+ const waiting = (a?.proposals ?? []).length + (plan?.proposals ?? 0);
4896
+ const finished = plans.some((p) => p.phase === "done");
4897
+ const flow = flowOf({ arch: a ? { phase: a.phase } : null, plan, waiting, busy, finished });
4898
+ const waits = {
4899
+ plan: (plan?.proposals ?? 0) + (flow.stage === "plan" || flow.stage === "start" ? 1 : 0),
4900
+ architecture: (a?.proposals ?? []).length + (flow.stage === "architecture" ? 1 : 0)
4901
+ };
4902
+ return { flow, plan, arch: a, waits };
4903
+ }
4904
+ function agentBrief(flow, { plan } = {}) {
4905
+ switch (flow.stage) {
4906
+ case "task":
4907
+ return [
4908
+ "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.",
4909
+ "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.",
4910
+ "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."
4911
+ ].join("\n");
4912
+ case "architecture":
4913
+ 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.`;
4914
+ case "plan-wait":
4915
+ return [
4916
+ "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.",
4917
+ '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.'
4918
+ ].join("\n");
4919
+ case "plan":
4920
+ 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.";
4921
+ case "start":
4922
+ 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].";
4923
+ default:
4924
+ return "";
4925
+ }
4926
+ }
4927
+ function footLine(flow) {
4928
+ switch (flow.stage) {
4929
+ case "task":
4930
+ 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.";
4931
+ case "architecture":
4932
+ return "Stage: the person is reviewing the architecture. Do not plan or build: wait for their [DiaCode] message.";
4933
+ case "plan-wait":
4934
+ return "Stage: the architecture is approved. Draw the plan on it with plan_create, then stop and say it is ready to review.";
4935
+ case "plan":
4936
+ return "Stage: the person is reviewing the plan. Do not start a step: wait for their [DiaCode] message.";
4937
+ case "start":
4938
+ 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.";
4939
+ default:
4940
+ return "";
4941
+ }
4942
+ }
4943
+
4680
4944
  // packages/server/src/mcp.js
4681
4945
  var VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];
4682
4946
  var MAX_SESSIONS = 200;
@@ -4806,6 +5070,7 @@ WARNING: the plan file has an edit that breaks a rule (${view.error}). Writes wa
4806
5070
  properties: {
4807
5071
  title: { type: "string" },
4808
5072
  goal: { type: "string", description: "what the whole plan is for, and when it is done" },
5073
+ no_architecture: { type: "boolean", description: "only if the person told you they do not want an architecture drawn first" },
4809
5074
  steps: {
4810
5075
  type: "array",
4811
5076
  minItems: 1,
@@ -4832,18 +5097,21 @@ WARNING: the plan file has an edit that breaks a rule (${view.error}). Writes wa
4832
5097
  },
4833
5098
  async run(args2, s, ctx) {
4834
5099
  const title = str(args2.title, "title");
5100
+ const refusal2 = planBeforeArchitecture(ctx, args2.no_architecture === true);
5101
+ if (refusal2) return { error: true, text: refusal2 };
4835
5102
  const ops = stepsToOps(args2.steps);
4836
5103
  const dry = applyBatch(newPlan({ id: "draft", title }), ops, ctx.who(s));
4837
5104
  if (dry.kind === "rejected") return refused(dry);
4838
5105
  const made = await ctx.store.create({ title, goal: typeof args2.goal === "string" ? args2.goal : void 0 }, ctx.who(s));
4839
5106
  const done = await send(ctx, s, made.id, ops, { reason: "drafted by the agent", baseRev: 0 });
4840
5107
  if (done.error) return done;
5108
+ await ctx.arch.adoptPlanned(made.id);
4841
5109
  const view = viewOf(ctx, made.id);
4842
5110
  const loose = args2.steps.length >= 3 && !args2.steps.some((st) => Array.isArray(st?.after) && st.after.length);
4843
5111
  const check = loose ? `
4844
5112
 
4845
5113
  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.` : "";
4846
- 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].";
5114
+ 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].";
4847
5115
  return { text: `Created plan ${made.id}.
4848
5116
 
4849
5117
  ${describePlan(view)}${check}
@@ -5013,12 +5281,12 @@ function archDraftToOps(args2) {
5013
5281
  visiting.delete(id);
5014
5282
  placed.add(id);
5015
5283
  const { label, kind, tech, detail, files, external } = raw;
5016
- ops.push({ op: "box.add", id, label, kind, ...raw.in ? { in: raw.in } : {}, ...tech ? { tech } : {}, ...detail ? { detail } : {}, ...files?.length ? { files } : {}, ...external ? { external: true } : {} });
5284
+ 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 } : {} });
5017
5285
  };
5018
5286
  for (const id of byId.keys()) place(id);
5019
5287
  for (const a of Array.isArray(args2.arrows) ? args2.arrows : []) {
5020
5288
  if (!a || typeof a !== "object") throw new HttpError(400, "each arrow is an object with from and to");
5021
- 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 } : {} });
5289
+ 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 } : {} });
5022
5290
  }
5023
5291
  for (const f of Array.isArray(args2.flows) ? args2.flows : []) {
5024
5292
  if (!f || typeof f !== "object") throw new HttpError(400, "each flow is an object with id, title and steps");
@@ -5062,9 +5330,9 @@ WARNING: the architecture file has an edit that breaks a rule (${view.error}). W
5062
5330
  {
5063
5331
  name: "arch_draft",
5064
5332
  description: [
5065
- "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).",
5333
+ "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).",
5066
5334
  '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.',
5067
- "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."
5335
+ "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."
5068
5336
  ].join("\n"),
5069
5337
  inputSchema: {
5070
5338
  type: "object",
@@ -5086,7 +5354,8 @@ WARNING: the architecture file has an edit that breaks a rule (${view.error}). W
5086
5354
  tech: { type: "string" },
5087
5355
  detail: { type: "string", description: "what it is for, in a sentence or two" },
5088
5356
  files: { type: "array", items: { type: "string" } },
5089
- external: { type: "boolean", description: "someone else runs it" }
5357
+ external: { type: "boolean", description: "someone else runs it" },
5358
+ 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." }
5090
5359
  }
5091
5360
  }
5092
5361
  },
@@ -5101,7 +5370,8 @@ WARNING: the architecture file has an edit that breaks a rule (${view.error}). W
5101
5370
  label: { type: "string", description: 'what for: "Store/load chats", not "uses"' },
5102
5371
  tech: { type: "string", description: "how: REST, SQL, a queue name" },
5103
5372
  async: { type: "boolean", description: "from does not wait for the answer" },
5104
- via: { type: "string", description: "the id of the queue that carries it" }
5373
+ via: { type: "string", description: "the id of the queue that carries it" },
5374
+ planned: { type: "boolean", description: "true when this connection does not exist yet" }
5105
5375
  }
5106
5376
  }
5107
5377
  },
@@ -5129,7 +5399,7 @@ WARNING: the architecture file has an edit that breaks a rule (${view.error}). W
5129
5399
  const r = await ctx.arch.apply({ baseRev: 0, reason: "drafted by the agent", ops }, ctx.who(s));
5130
5400
  if (r.kind === "rejected") return refusedArch(r);
5131
5401
  const view = archOf(ctx);
5132
- 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.";
5402
+ 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.";
5133
5403
  return { text: `Drew the architecture.
5134
5404
 
5135
5405
  ${arch_exports.describeArch(view)}
@@ -5141,7 +5411,7 @@ ${next}`, data: { rev: view.rev } };
5141
5411
  name: "arch_edit",
5142
5412
  description: [
5143
5413
  "Change the architecture with a batch of operations, all or nothing. Operations:",
5144
- "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?}.",
5414
+ "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?}.",
5145
5415
  '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.',
5146
5416
  "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."
5147
5417
  ].join("\n"),
@@ -5158,9 +5428,10 @@ ${next}`, data: { rev: view.rev } };
5158
5428
  const view = archOf(ctx);
5159
5429
  try {
5160
5430
  const rev = s.seen.get(ARCH_KEY) ?? view.rev;
5161
- 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));
5431
+ 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;
5432
+ 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));
5162
5433
  if (reply.kind === "rejected") return refusedArch(reply);
5163
- return { text: archApplied(reply, args2.ops), data: { rev: reply.rev, kind: reply.kind, ...reply.proposal ? { proposal: reply.proposal.id } : {} } };
5434
+ return { text: archApplied(reply, ops), data: { rev: reply.rev, kind: reply.kind, ...reply.proposal ? { proposal: reply.proposal.id } : {} } };
5164
5435
  } catch (e) {
5165
5436
  if (e instanceof HttpError && e.status === 400) throw new HttpError(400, `${e.message}
5166
5437
 
@@ -5216,6 +5487,15 @@ function stepsToOps(steps) {
5216
5487
  for (const id of byId.keys()) place(id);
5217
5488
  return [...ops, ...kinds];
5218
5489
  }
5490
+ function planBeforeArchitecture(ctx, skip) {
5491
+ const a = ctx.arch.arch;
5492
+ if (!a) {
5493
+ if (skip) return void 0;
5494
+ 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.)";
5495
+ }
5496
+ 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.";
5497
+ return void 0;
5498
+ }
5219
5499
  var TOOLS = [...PLAN_TOOLS, ...ARCH_TOOLS];
5220
5500
  var isCall = (m) => Boolean(m) && typeof m === "object" && typeof m.method === "string";
5221
5501
  function createMcp({ store, arch: arch2, presence, stopped = () => void 0, version = "0" }) {
@@ -5249,7 +5529,7 @@ function createMcp({ store, arch: arch2, presence, stopped = () => void 0, versi
5249
5529
  const seen = s.seen.get(ARCH_KEY);
5250
5530
  out = await tool.run(a, s, ctx);
5251
5531
  if (arch2.exists) out = archChanges(out, ctx, s, seen);
5252
- return { content: [{ type: "text", text: out.text }], ...out.error ? { isError: true } : {} };
5532
+ return { content: [{ type: "text", text: withStage(out.text) }], ...out.error ? { isError: true } : {} };
5253
5533
  }
5254
5534
  planId = typeof a.plan === "string" ? a.plan : store.list().length === 1 ? store.list()[0].id : void 0;
5255
5535
  const before = planId && store.entries.has(planId) ? s.seen.get(planId) : void 0;
@@ -5261,10 +5541,16 @@ function createMcp({ store, arch: arch2, presence, stopped = () => void 0, versi
5261
5541
  out = { error: true, text: e instanceof HttpError ? message : `Something went wrong inside the plan server: ${message}` };
5262
5542
  }
5263
5543
  return {
5264
- content: [{ type: "text", text: out.text }],
5544
+ content: [{ type: "text", text: withStage(out.text) }],
5265
5545
  ...out.error ? { isError: true } : {}
5266
5546
  };
5267
5547
  }
5548
+ function withStage(text2) {
5549
+ const foot = footLine(flowNow({ store, arch: arch2, presence }).flow);
5550
+ return foot ? `${text2}
5551
+
5552
+ [DiaCode \xB7 ${foot}]` : text2;
5553
+ }
5268
5554
  function withChanges(out, id, before, s) {
5269
5555
  const rev = store.get(id).rev ?? 0;
5270
5556
  let text2 = out.text;
@@ -6136,9 +6422,11 @@ var SILENT_MS = 15 * 6e4;
6136
6422
  var OURS = /(^|[^a-z])(plan_list|plan_read|plan_create|plan_edit|step_start|step_done|step_failed|step_wait|step_ask)$|^dcursed_/;
6137
6423
  var Agents = class {
6138
6424
  /**
6139
- * @param {{ store: import('./store.js').PlanStore, presence: import('./presence.js').Presence, now?: () => number }} options
6425
+ * @param {{ store: import('./store.js').PlanStore, presence: import('./presence.js').Presence, now?: () => number, stage?: () => string }} options
6426
+ * `stage`: what the agent is told about where the work stands (flow.js), at the start of a turn; nothing while a plan runs
6140
6427
  */
6141
- constructor({ store, presence, now = Date.now }) {
6428
+ constructor({ store, presence, now = Date.now, stage = () => "" }) {
6429
+ this.stage = stage;
6142
6430
  this.store = store;
6143
6431
  this.presence = presence;
6144
6432
  this.now = now;
@@ -6174,7 +6462,8 @@ var Agents = class {
6174
6462
  }
6175
6463
  this.say(actor, s, ev.event === "prompt");
6176
6464
  if (b.text && b.plan) this.presence.noteRead(actor, b.plan, b.rev ?? 0);
6177
- return b.text ? { context: b.text, ...s.plan ? { plan: s.plan } : {} } : {};
6465
+ const context = [this.stage(), b.text].filter(Boolean).join("\n\n");
6466
+ return context ? { context, ...s.plan ? { plan: s.plan } : {} } : {};
6178
6467
  }
6179
6468
  case "invocation": {
6180
6469
  const first = s.rev === 0 && !s.plan;
@@ -6186,7 +6475,8 @@ var Agents = class {
6186
6475
  }
6187
6476
  this.say(actor, s, true);
6188
6477
  if (b.text && b.plan) this.presence.noteRead(actor, b.plan, b.rev ?? 0);
6189
- return this.merge(s, b.text ? { context: b.text, ...s.plan ? { plan: s.plan } : {} } : {});
6478
+ const context = [this.stage(), b.text].filter(Boolean).join("\n\n");
6479
+ return this.merge(s, context ? { context, ...s.plan ? { plan: s.plan } : {} } : {});
6190
6480
  }
6191
6481
  const told = await this.after(actor, s, { event: "tool-after", tool: "invocation" });
6192
6482
  this.say(actor, s, true);
@@ -6510,9 +6800,20 @@ var Permissions = class extends EventEmitter6 {
6510
6800
  decide(id, decision, reason) {
6511
6801
  const p = this.pending.get(id);
6512
6802
  if (!p) return false;
6513
- p.settle(decision === "allow" ? { behavior: "allow" } : { behavior: "deny", message: reason?.trim() ? `The person denied this in the DcurseD editor: ${reason.trim().slice(0, 500)}` : "The person denied this in the DcurseD editor." });
6803
+ p.settle(decision === "allow" ? { behavior: "allow" } : { behavior: "deny", message: reason?.trim() ? `The person denied this in the DiaCode editor: ${reason.trim().slice(0, 500)}` : "The person denied this in the DiaCode editor." });
6514
6804
  return true;
6515
6805
  }
6806
+ /**
6807
+ * You stopped the plan this agent is working on: whatever it has asked and not been answered is refused now, and it is
6808
+ * told why. Without this its window keeps the prompt, and Allow there would run a command you stopped it from running.
6809
+ * @param {string} actor @param {string} message what the agent is told
6810
+ * @returns {number} how many prompts were refused
6811
+ */
6812
+ denyAll(actor, message) {
6813
+ const asked = [...this.pending.values()].filter((p) => p.actor === actor);
6814
+ for (const p of asked) p.settle({ behavior: "deny", message });
6815
+ return asked.length;
6816
+ }
6516
6817
  /** The session was heard from again: what it asked has been answered in its own window. @param {string} actor @param {string} [session] */
6517
6818
  heard(actor, session) {
6518
6819
  for (const p of [...this.pending.values()]) if (p.actor === actor && (session === void 0 || p.session === void 0 || p.session === session)) p.settle(null);
@@ -6538,7 +6839,10 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
6538
6839
  const reconciler = new Reconciler(store, { run: rc.run ?? openCodeRunner({ root: root2, model: rc.model, bin: rc.bin }) });
6539
6840
  const presence = new Presence(presenceOptions);
6540
6841
  const repoFiles = new RepoFiles(root2);
6541
- const agents = new Agents({ store, presence });
6842
+ const agents = new Agents({ store, presence, stage: () => {
6843
+ const f = flowNow({ store, arch: archStore, presence });
6844
+ return agentBrief(f.flow, { plan: f.plan });
6845
+ } });
6542
6846
  const calls = new Calls({
6543
6847
  ...callOptions,
6544
6848
  store,
@@ -6553,6 +6857,12 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
6553
6857
  });
6554
6858
  const permissions = new Permissions();
6555
6859
  permissions.on("change", () => presence.announce?.());
6860
+ calls.on("stops", () => {
6861
+ for (const actor of calls.stops.keys()) {
6862
+ const plan2 = calls.stoppedFor(actor);
6863
+ if (plan2) permissions.denyAll(actor, `The person pressed Stop in the DiaCode editor: plan ${plan2} is stopped. Do not run this. Say that you have stopped, and end your turn.`);
6864
+ }
6865
+ });
6556
6866
  const heard = (agents2) => {
6557
6867
  const on = new Set(calls.listening());
6558
6868
  return agents2.map((a) => {
@@ -6648,6 +6958,14 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
6648
6958
  const url = new URL(req.url ?? "/", "http://localhost");
6649
6959
  const parts = url.pathname.split("/").filter(Boolean).map(decodeURIComponent);
6650
6960
  if (req.method === "GET" && url.pathname === "/api/health") return send2(res, 200, { ok: true, root: root2, version: VERSION, api: API_VERSION, schemas: [SCHEMA, "dcursed.plan/0", arch_exports.SCHEMA] });
6961
+ if (req.method === "GET" && url.pathname === "/api/flow") {
6962
+ const f = flowNow({ store, arch: archStore, presence });
6963
+ const p2 = (
6964
+ /** @type {any} */
6965
+ f.plan
6966
+ );
6967
+ 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() });
6968
+ }
6651
6969
  if (req.method === "GET" && url.pathname === "/api/diagnostics") {
6652
6970
  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() });
6653
6971
  }
@@ -6770,7 +7088,8 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
6770
7088
  }
6771
7089
  if (req.method === "GET" && parts[0] === "api" && parts[1] === "brief" && parts.length === 2) {
6772
7090
  const asked = req.headers["x-dcursed-agent"] === void 0 ? void 0 : whoOf(req).actor;
6773
- const { text: text2, plan: plan2, rev } = store.brief(url.searchParams.get("plan") ?? void 0, asked);
7091
+ const { text: planText, plan: plan2, rev } = store.brief(url.searchParams.get("plan") ?? void 0, asked);
7092
+ const text2 = [agents.stage(), planText].filter(Boolean).join("\n\n");
6774
7093
  return sendText(res, 200, text2, plan2 === void 0 ? {} : { "x-dcursed-plan": plan2, "x-dcursed-rev": String(rev) });
6775
7094
  }
6776
7095
  if (req.method === "GET" && parts[0] === "api" && parts[1] === "events" && parts.length === 2) return listEvents(req, res);
@@ -7229,7 +7548,7 @@ ${END}`;
7229
7548
  ` : rules.includes(BEGIN) && rules.includes(END) ? rules.replace(new RegExp(`${escape(BEGIN)}[\\s\\S]*?${escape(END)}`), () => block) : `${rules.replace(/\n*$/, "\n\n")}${block}
7230
7549
  `;
7231
7550
  said.push(await put(rulesPath, next, "AGENTS.md (how to work with the plan)"));
7232
- said.push("", serveHint(port2));
7551
+ said.push("", FLOW_HINT, "", serveHint(port2));
7233
7552
  return said;
7234
7553
  }
7235
7554
  function escape(s) {
@@ -7255,6 +7574,7 @@ async function mergeJson(root2, rel, change, what, snippet) {
7255
7574
  }
7256
7575
  var curlHook = (port2, harness, hook, agent, fallback = "{}") => `curl -s --max-time 2 -X POST -H 'content-type: application/json' --data-binary @- 'http://127.0.0.1:${port2}/hooks/${harness}/${hook}?agent=${agent}' || echo '${fallback}'`;
7257
7576
  var askHook = (port2, harness, hook, agent) => `curl -s --max-time 2 -X POST -H 'content-type: application/json' --data-binary @- 'http://127.0.0.1:${port2}/hooks/${harness}/${hook}?agent=${agent}&pid='"$PPID" || echo '{}'`;
7577
+ var ALLOW_TOOLS = "mcp__dcursed";
7258
7578
  var WAKE_SECONDS = 86400;
7259
7579
  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`;
7260
7580
  var PERMISSION_SECONDS = 600;
@@ -7328,13 +7648,16 @@ async function initClaudeCode({ root: root2, port: port2 = 7300, agent = "main",
7328
7648
  said.push(await mergeJson(root2, settings, (d) => {
7329
7649
  d.hooks = d.hooks ?? {};
7330
7650
  for (const [event, group] of Object.entries(ours)) d.hooks[event] = [...(d.hooks[event] ?? []).filter((g) => !mine(g)), group];
7331
- }, "the hooks that tell the plan server what the agent does, and tell the agent what changed", `"hooks": ${JSON.stringify(ours)}`));
7651
+ d.permissions = d.permissions ?? {};
7652
+ const allow = Array.isArray(d.permissions.allow) ? d.permissions.allow : [];
7653
+ d.permissions.allow = allow.includes(ALLOW_TOOLS) ? allow : [...allow, ALLOW_TOOLS];
7654
+ }, "the hooks that tell the plan server what the agent does and what changed, and the rule that lets it call these plan tools without asking", `"hooks": ${JSON.stringify(ours)}, "permissions": { "allow": ["${ALLOW_TOOLS}"] }`));
7332
7655
  if (!shared) {
7333
7656
  const kept = await keepOutOfGit(root2, ".claude/settings.local.json");
7334
7657
  if (kept) said.push(kept);
7335
7658
  }
7336
7659
  said.push(await ownRules(root2, ".claude/rules/dcursed.md", `${RULES_BODY}`, "how to work with the plan"));
7337
- said.push("", serveHint(port2), "Then start a new Claude Code session in this folder (approve the dcursed MCP server when asked).");
7660
+ said.push("", FLOW_HINT, "", serveHint(port2), "Then start a new Claude Code session in this folder (approve the dcursed MCP server when asked).");
7338
7661
  return said;
7339
7662
  }
7340
7663
  async function initCursor({ root: root2, port: port2 = 7300, agent = "agent" }) {
@@ -7369,7 +7692,7 @@ alwaysApply: true
7369
7692
  ---
7370
7693
 
7371
7694
  ${RULES_BODY}`, "how to work with the plan"));
7372
- said.push("", serveHint(port2), "Then enable the dcursed server in Cursor Settings \u2192 MCP, and start a new chat.");
7695
+ said.push("", FLOW_HINT, "", serveHint(port2), "Then enable the dcursed server in Cursor Settings \u2192 MCP, and start a new chat.");
7373
7696
  return said;
7374
7697
  }
7375
7698
  async function initAntigravity({ root: root2, port: port2 = 7300, agent = "agent" }) {
@@ -7398,7 +7721,7 @@ description: How to work with this repository's DiaCode plans
7398
7721
  ---
7399
7722
 
7400
7723
  ${RULES_BODY}`, "how to work with the plan"));
7401
- said.push("", serveHint(port2), "Then trust this folder in Antigravity (workspace hooks load only for a trusted folder) and start a new conversation.");
7724
+ 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.");
7402
7725
  return said;
7403
7726
  }
7404
7727
  var HARNESS_INIT = (
@@ -7497,7 +7820,12 @@ async function removeClaudeCode({ root: root2 }) {
7497
7820
  pruneEmpty(d.hooks, event);
7498
7821
  }
7499
7822
  pruneEmpty(d, "hooks");
7500
- }, (d) => onlyOurs(d), /\/hooks\/claude-code\//, "the hooks whose address contains /hooks/claude-code/"));
7823
+ if (Array.isArray(d.permissions?.allow)) {
7824
+ d.permissions.allow = d.permissions.allow.filter((r) => r !== ALLOW_TOOLS);
7825
+ pruneEmpty(d.permissions, "allow");
7826
+ pruneEmpty(d, "permissions");
7827
+ }
7828
+ }, (d) => onlyOurs(d), /\/hooks\/claude-code\/|mcp__dcursed/, 'the hooks whose address contains /hooks/claude-code/, and the "mcp__dcursed" allow rule'));
7501
7829
  }
7502
7830
  said.push(await drop(root2, ".claude/rules/dcursed.md", "the rules"));
7503
7831
  const unhidden = await letGitSeeAgain(root2, ".claude/settings.local.json");
@@ -7618,7 +7946,9 @@ async function hooksEntry(root2, files, harness, events, hooksOf) {
7618
7946
  return { finding: ok(`all ${events.length} hooks are set, in ${where}`), ports: [...new Set(ports)] };
7619
7947
  }
7620
7948
  async function rulesFile(root2, rel, what) {
7621
- return await text(root2, rel) === null ? problem(`${rel} is missing: ${what}`, "{init}") : ok(`${rel} (how to work with the plan)`);
7949
+ const t = await text(root2, rel);
7950
+ if (t === null) return problem(`${rel} is missing: ${what}`, "{init}");
7951
+ 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}");
7622
7952
  }
7623
7953
  async function openCode(root2) {
7624
7954
  const configFile = await text(root2, "opencode.json") !== null ? "opencode.json" : await text(root2, "opencode.jsonc") !== null ? "opencode.jsonc" : "opencode.json";
@@ -7640,7 +7970,7 @@ async function openCode(root2) {
7640
7970
  else if (installed !== await pluginSource()) findings.push(problem(".dcursed/opencode-plugin.js is not the plugin that ships with this dcursed (an older one, or edited)", "{init}"));
7641
7971
  else findings.push(ok(".dcursed/opencode-plugin.js is this version's plugin"));
7642
7972
  const agents = await text(root2, "AGENTS.md");
7643
- 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}"));
7973
+ 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}"));
7644
7974
  return { harness: "opencode", label: "OpenCode", ports, findings };
7645
7975
  }
7646
7976
  async function claudeCode(root2) {
@@ -7668,6 +7998,9 @@ async function claudeCode(root2) {
7668
7998
  if (hookText.includes("/hooks/claude-code/Stop") && !hookText.includes("/hooks/claude-code/PreToolUse")) {
7669
7999
  findings.push(problem("no PreToolUse hook: Stop in the editor cannot halt the agent mid-turn (it hears it at its next dcursed tool)", "{init}"));
7670
8000
  }
8001
+ if (hookText.includes("/hooks/claude-code/Stop") && !hookText.includes(ALLOW_TOOLS)) {
8002
+ findings.push(note(`Claude Code asks permission before each plan call; init adds one rule, "${ALLOW_TOOLS}", that covers only the plan tools (run init again to add it, or skip it if you want the prompts)`));
8003
+ }
7671
8004
  return { harness: "claude-code", label: "Claude Code", ports: [...mcp.ports, ...hooks.ports], findings };
7672
8005
  }
7673
8006
  async function cursor(root2) {
@@ -7806,7 +8139,7 @@ function formatReport(report) {
7806
8139
  if (f.fix) lines.push(` ${f.fix}`);
7807
8140
  }
7808
8141
  }
7809
- lines.push("", report.problems ? `${report.problems} problem${report.problems === 1 ? "" : "s"}.` : "Nothing is wrong that this can see.");
8142
+ lines.push("", report.problems ? `${report.problems} problem${report.problems === 1 ? "" : "s"}.` : "Nothing is wrong that this can see.", "", FLOW_HINT);
7810
8143
  return lines.join("\n").replace(/^\n/, "");
7811
8144
  }
7812
8145
  function redact(text2, root2) {