diacode 0.2.1 → 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" });
@@ -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/
@@ -3521,7 +3576,7 @@ var PlanStore = class extends EventEmitter {
3521
3576
  * @param {string} actor @returns {string | undefined}
3522
3577
  */
3523
3578
  planFor(actor) {
3524
- 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));
3525
3580
  if (live.length === 1) return live[0][0];
3526
3581
  const latest = ([, e]) => e.log.filter((l) => l.actor === actor).at(-1)?.at ?? "";
3527
3582
  const newest = (list) => [...list].sort((a, b) => latest(b).localeCompare(latest(a)))[0]?.[0];
@@ -3543,7 +3598,10 @@ var PlanStore = class extends EventEmitter {
3543
3598
  return view.plan ? { text: describeBrief(view), plan: id, rev: view.rev } : { text: "" };
3544
3599
  };
3545
3600
  if (planId) return one(planId);
3546
- 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
+ ));
3547
3605
  if (!live.length) return { text: "" };
3548
3606
  if (live.length === 1) return one(live[0].id);
3549
3607
  const mine = actor ? this.planFor(actor) : void 0;
@@ -3746,6 +3804,8 @@ import { EventEmitter as EventEmitter2 } from "node:events";
3746
3804
  import { watch as watch2, mkdirSync as mkdirSync2 } from "node:fs";
3747
3805
  var arch = arch_exports;
3748
3806
  var FOOTPRINT_ACTOR = "server:footprint";
3807
+ var PLAN_ACTOR = "server:plan";
3808
+ var PLAN_TO_COME = "next";
3749
3809
  var same4 = (a, b) => JSON.stringify(arch.canonicalArch(a)) === JSON.stringify(arch.canonicalArch(b));
3750
3810
  var newLayout2 = () => newLayout(arch.LAYOUT_OF);
3751
3811
  var ArchStore = class extends EventEmitter2 {
@@ -3911,6 +3971,22 @@ var ArchStore = class extends EventEmitter2 {
3911
3971
  since(baseRev) {
3912
3972
  return this.log.filter((l) => l.rev > baseRev && !l.snapshot);
3913
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
+ }
3914
3990
  /**
3915
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
3916
3992
  * architecture, so it waits for you as a proposal; nothing happens if the plan changed nothing in it, or the proposal is
@@ -4073,20 +4149,28 @@ function parseLayout2(text2) {
4073
4149
  import { randomUUID } from "node:crypto";
4074
4150
 
4075
4151
  // 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.
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.
4077
4162
 
4078
- How to work with it
4163
+ How to work with a plan
4079
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.
4080
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.
4081
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.
4082
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.
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.
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.
4084
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.
4085
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.
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.
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.
4090
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.
4091
4175
  - Do not edit the files in .dcursed/plans/ by hand. The tools check the rules and keep the log.
4092
4176
 
@@ -4094,16 +4178,16 @@ Working while the person watches
4094
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.
4095
4179
 
4096
4180
  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.
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.
4098
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.
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.
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.
4101
4185
  - Do not edit .dcursed/architecture.json by hand either.`;
4102
4186
 
4103
4187
  // packages/server/src/calls.js
4104
4188
  import { EventEmitter as EventEmitter3 } from "node:events";
4105
4189
  var ARCH_SCOPE = "@architecture";
4106
- var HELD_WHILE_BUSY = /* @__PURE__ */ new Set(["changed", "archAccepted", "archSettled"]);
4190
+ var HELD_WHILE_BUSY = /* @__PURE__ */ new Set(["changed", "archAccepted", "archSettled", "archChanged"]);
4107
4191
  var KEEP = 50;
4108
4192
  var GAP_MS = 5e3;
4109
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"]);
@@ -4177,7 +4261,9 @@ var Calls = class extends EventEmitter3 {
4177
4261
  for (const op of line.ops ?? []) {
4178
4262
  if (op.op === "plan.set" && op.phase === "executing" && was === "paused") {
4179
4263
  phased = true;
4180
- 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
+ }
4181
4267
  } else if (op.op === "plan.set" && op.phase === "executing") {
4182
4268
  phased = true;
4183
4269
  for (const [actor, o] of this.stops) if (o.plan === id) this.stops.delete(actor);
@@ -4185,7 +4271,15 @@ var Calls = class extends EventEmitter3 {
4185
4271
  const archToo = was === "planning" && this.arch?.arch?.phase === "draft" && to !== void 0 && this.archDrafter() === to;
4186
4272
  if (archToo) this.acceptArch().catch(() => {
4187
4273
  });
4188
- 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) }) });
4189
4283
  } else if (op.op === "plan.set" && op.phase) {
4190
4284
  phased = true;
4191
4285
  this.dropQueued(id);
@@ -4207,7 +4301,7 @@ var Calls = class extends EventEmitter3 {
4207
4301
  if (who) tell.add(who);
4208
4302
  }
4209
4303
  }
4210
- 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);
4211
4305
  }
4212
4306
  /**
4213
4307
  * A batch landed on the architecture. Only yours can make a call. Accepting the draft an agent drew tells it that its
@@ -4220,9 +4314,13 @@ var Calls = class extends EventEmitter3 {
4220
4314
  if (!arch2 || line.actor !== "you" || line.proposed || quiet) return;
4221
4315
  const log = this.arch?.log ?? [];
4222
4316
  const settled = /* @__PURE__ */ new Map();
4317
+ let edited = false;
4223
4318
  for (const op of line.ops ?? []) {
4224
4319
  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) });
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;
4226
4324
  } else if (op.op === "proposal.accept" || op.op === "proposal.reject") {
4227
4325
  const made = [...log].reverse().find((l) => l.proposed === op.id && l.rev < rev);
4228
4326
  if (!made || made.actor.startsWith("server:")) continue;
@@ -4232,6 +4330,77 @@ var Calls = class extends EventEmitter3 {
4232
4330
  }
4233
4331
  }
4234
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"));
4235
4404
  }
4236
4405
  /**
4237
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
@@ -4246,7 +4415,7 @@ var Calls = class extends EventEmitter3 {
4246
4415
  this.settle(c, "dropped");
4247
4416
  }
4248
4417
  }
4249
- 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() }) });
4250
4419
  if (made) made.notes = all;
4251
4420
  }
4252
4421
  /**
@@ -4290,7 +4459,7 @@ var Calls = class extends EventEmitter3 {
4290
4459
  if (l.proposed) continue;
4291
4460
  const ops = l.ops ?? [];
4292
4461
  for (let j = ops.length - 1; j >= 0; j--) {
4293
- if (ops[j].op === "plan.stop") return "planning";
4462
+ if (ops[j].op === "plan.stop") return "approved";
4294
4463
  if (ops[j].op === "plan.set" && ops[j].phase) return ops[j].phase;
4295
4464
  }
4296
4465
  }
@@ -4430,14 +4599,15 @@ var Calls = class extends EventEmitter3 {
4430
4599
  */
4431
4600
  changed(id, actor, from, rev) {
4432
4601
  const plan = this.store.get(id).plan;
4433
- if (!plan || plan.phase !== "executing") return;
4602
+ if (!plan || plan.phase !== "executing" && plan.phase !== "approved") return;
4434
4603
  if (!this.lastHeard.has(actor) && ![...this.waiters].some((w) => w.actor === actor)) return;
4435
4604
  const seen = this.seen(actor, id);
4436
4605
  if (seen !== void 0 && seen >= rev) return;
4437
4606
  for (const c of this.calls) if (c.plan === id && c.to === actor && c.kind === "changed" && c.state === "queued") this.settle(c, "dropped");
4438
4607
  const since = seen ?? from - 1;
4439
4608
  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) });
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 }) });
4441
4611
  }
4442
4612
  /** The revision of a plan an agent was last shown, if it ever was. @param {string} actor @param {string} id */
4443
4613
  seen(actor, id) {
@@ -4515,8 +4685,9 @@ var Calls = class extends EventEmitter3 {
4515
4685
  }
4516
4686
  const plan = this.store.get(call.plan).plan;
4517
4687
  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;
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;
4520
4691
  if (call.kind === "passed") {
4521
4692
  const e = call.gate && plan.edges.find((x) => x.from === call.gate?.from && x.to === call.gate?.to);
4522
4693
  return plan.phase === "executing" && Boolean(e?.passed) && (plan.nodes[call.gate?.to ?? ""]?.status ?? "not_started") === "not_started";
@@ -4524,7 +4695,7 @@ var Calls = class extends EventEmitter3 {
4524
4695
  if (call.kind === "sentBack") return plan.phase === "executing" && plan.nodes[call.step ?? ""]?.status === "not_started";
4525
4696
  if (call.kind === "changed") {
4526
4697
  const seen = call.to ? this.seen(call.to, call.plan) : void 0;
4527
- return plan.phase === "executing" && !(seen !== void 0 && seen >= call.rev);
4698
+ return (plan.phase === "executing" || plan.phase === "approved") && !(seen !== void 0 && seen >= call.rev);
4528
4699
  }
4529
4700
  const n = call.step ? plan.nodes[call.step] : void 0;
4530
4701
  return Boolean(n && n.owner === call.to && n.status === "in_progress");
@@ -4618,15 +4789,28 @@ var Calls = class extends EventEmitter3 {
4618
4789
  this.pending.clear();
4619
4790
  }
4620
4791
  };
4621
- function approvedText(plan, id, { archToo = false } = {}) {
4792
+ function planApprovedText(plan, id, { archToo = false, hasArch = true } = {}) {
4622
4793
  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:`,
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 } = {}) {
4800
+ return [
4801
+ `[DiaCode] The person pressed Start${again ? " again" : ""} on the plan "${plan.title}" (${id}) in the editor${archToo ? ", and approved the architecture you drew with it (your changes to the architecture are proposals from now on)" : ""}. Carry it out now with the dcursed tools, one step at a time:`,
4624
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.",
4625
- "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."
4626
4804
  ].join(" ");
4627
4805
  }
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.`;
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");
4630
4814
  }
4631
4815
  function stopOrder(id) {
4632
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.`;
@@ -4654,30 +4838,109 @@ function answeredText(plan, id, step3, answer) {
4654
4838
  return `[DiaCode] The person answered your question on step ${step3}${label ? ` ("${label}")` : ""} in plan ${id}: ${answer}
4655
4839
  Carry on with ${step3} using that answer.`;
4656
4840
  }
4657
- function changedText(plan, id, attention, changes) {
4841
+ function changedText(plan, id, attention, changes, { sync = true } = {}) {
4658
4842
  const clip2 = (s) => s.length > 400 ? `${s.slice(0, 399)}\u2026` : s;
4843
+ const waiting = plan.phase === "approved";
4659
4844
  return [
4660
4845
  `[DiaCode] While you were between turns, the person changed the plan "${plan.title}" (${id}) in the editor.`,
4661
4846
  ...attention.length ? ["HEADS UP, about your steps:", ...attention.map((a) => `- ${clip2(a)}`)] : [],
4662
4847
  ...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."
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."
4664
4859
  ].join("\n");
4665
4860
  }
4666
- 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
+ }
4667
4869
  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."
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.'
4670
4872
  ].join("\n");
4671
4873
  }
4672
- function archSettledText(arch2, notes) {
4874
+ function archSettledText(arch2, notes, { drawPlan = false } = {}) {
4673
4875
  const clip2 = (s) => s.length > 400 ? `${s.slice(0, 399)}\u2026` : s;
4674
4876
  return [
4675
4877
  `[DiaCode] The person settled ${notes.length === 1 ? "your proposal" : "your proposals"} to the architecture${arch2 ? ` ("${arch2.title}")` : ""}:`,
4676
4878
  ...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."
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."
4678
4880
  ].join("\n");
4679
4881
  }
4680
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
+
4681
4944
  // packages/server/src/mcp.js
4682
4945
  var VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];
4683
4946
  var MAX_SESSIONS = 200;
@@ -4807,6 +5070,7 @@ WARNING: the plan file has an edit that breaks a rule (${view.error}). Writes wa
4807
5070
  properties: {
4808
5071
  title: { type: "string" },
4809
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" },
4810
5074
  steps: {
4811
5075
  type: "array",
4812
5076
  minItems: 1,
@@ -4833,18 +5097,21 @@ WARNING: the plan file has an edit that breaks a rule (${view.error}). Writes wa
4833
5097
  },
4834
5098
  async run(args2, s, ctx) {
4835
5099
  const title = str(args2.title, "title");
5100
+ const refusal2 = planBeforeArchitecture(ctx, args2.no_architecture === true);
5101
+ if (refusal2) return { error: true, text: refusal2 };
4836
5102
  const ops = stepsToOps(args2.steps);
4837
5103
  const dry = applyBatch(newPlan({ id: "draft", title }), ops, ctx.who(s));
4838
5104
  if (dry.kind === "rejected") return refused(dry);
4839
5105
  const made = await ctx.store.create({ title, goal: typeof args2.goal === "string" ? args2.goal : void 0 }, ctx.who(s));
4840
5106
  const done = await send(ctx, s, made.id, ops, { reason: "drafted by the agent", baseRev: 0 });
4841
5107
  if (done.error) return done;
5108
+ await ctx.arch.adoptPlanned(made.id);
4842
5109
  const view = viewOf(ctx, made.id);
4843
5110
  const loose = args2.steps.length >= 3 && !args2.steps.some((st) => Array.isArray(st?.after) && st.after.length);
4844
5111
  const check = loose ? `
4845
5112
 
4846
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.` : "";
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].";
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].";
4848
5115
  return { text: `Created plan ${made.id}.
4849
5116
 
4850
5117
  ${describePlan(view)}${check}
@@ -5014,12 +5281,12 @@ function archDraftToOps(args2) {
5014
5281
  visiting.delete(id);
5015
5282
  placed.add(id);
5016
5283
  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 } : {} });
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 } : {} });
5018
5285
  };
5019
5286
  for (const id of byId.keys()) place(id);
5020
5287
  for (const a of Array.isArray(args2.arrows) ? args2.arrows : []) {
5021
5288
  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 } : {} });
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 } : {} });
5023
5290
  }
5024
5291
  for (const f of Array.isArray(args2.flows) ? args2.flows : []) {
5025
5292
  if (!f || typeof f !== "object") throw new HttpError(400, "each flow is an object with id, title and steps");
@@ -5063,9 +5330,9 @@ WARNING: the architecture file has an edit that breaks a rule (${view.error}). W
5063
5330
  {
5064
5331
  name: "arch_draft",
5065
5332
  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).",
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).",
5067
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.',
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."
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."
5069
5336
  ].join("\n"),
5070
5337
  inputSchema: {
5071
5338
  type: "object",
@@ -5087,7 +5354,8 @@ WARNING: the architecture file has an edit that breaks a rule (${view.error}). W
5087
5354
  tech: { type: "string" },
5088
5355
  detail: { type: "string", description: "what it is for, in a sentence or two" },
5089
5356
  files: { type: "array", items: { type: "string" } },
5090
- 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." }
5091
5359
  }
5092
5360
  }
5093
5361
  },
@@ -5102,7 +5370,8 @@ WARNING: the architecture file has an edit that breaks a rule (${view.error}). W
5102
5370
  label: { type: "string", description: 'what for: "Store/load chats", not "uses"' },
5103
5371
  tech: { type: "string", description: "how: REST, SQL, a queue name" },
5104
5372
  async: { type: "boolean", description: "from does not wait for the answer" },
5105
- 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" }
5106
5375
  }
5107
5376
  }
5108
5377
  },
@@ -5130,7 +5399,7 @@ WARNING: the architecture file has an edit that breaks a rule (${view.error}). W
5130
5399
  const r = await ctx.arch.apply({ baseRev: 0, reason: "drafted by the agent", ops }, ctx.who(s));
5131
5400
  if (r.kind === "rejected") return refusedArch(r);
5132
5401
  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.";
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.";
5134
5403
  return { text: `Drew the architecture.
5135
5404
 
5136
5405
  ${arch_exports.describeArch(view)}
@@ -5142,7 +5411,7 @@ ${next}`, data: { rev: view.rev } };
5142
5411
  name: "arch_edit",
5143
5412
  description: [
5144
5413
  "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?}.",
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?}.",
5146
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.',
5147
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."
5148
5417
  ].join("\n"),
@@ -5159,9 +5428,10 @@ ${next}`, data: { rev: view.rev } };
5159
5428
  const view = archOf(ctx);
5160
5429
  try {
5161
5430
  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));
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));
5163
5433
  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 } : {} } };
5434
+ return { text: archApplied(reply, ops), data: { rev: reply.rev, kind: reply.kind, ...reply.proposal ? { proposal: reply.proposal.id } : {} } };
5165
5435
  } catch (e) {
5166
5436
  if (e instanceof HttpError && e.status === 400) throw new HttpError(400, `${e.message}
5167
5437
 
@@ -5217,6 +5487,15 @@ function stepsToOps(steps) {
5217
5487
  for (const id of byId.keys()) place(id);
5218
5488
  return [...ops, ...kinds];
5219
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
+ }
5220
5499
  var TOOLS = [...PLAN_TOOLS, ...ARCH_TOOLS];
5221
5500
  var isCall = (m) => Boolean(m) && typeof m === "object" && typeof m.method === "string";
5222
5501
  function createMcp({ store, arch: arch2, presence, stopped = () => void 0, version = "0" }) {
@@ -5250,7 +5529,7 @@ function createMcp({ store, arch: arch2, presence, stopped = () => void 0, versi
5250
5529
  const seen = s.seen.get(ARCH_KEY);
5251
5530
  out = await tool.run(a, s, ctx);
5252
5531
  if (arch2.exists) out = archChanges(out, ctx, s, seen);
5253
- return { content: [{ type: "text", text: out.text }], ...out.error ? { isError: true } : {} };
5532
+ return { content: [{ type: "text", text: withStage(out.text) }], ...out.error ? { isError: true } : {} };
5254
5533
  }
5255
5534
  planId = typeof a.plan === "string" ? a.plan : store.list().length === 1 ? store.list()[0].id : void 0;
5256
5535
  const before = planId && store.entries.has(planId) ? s.seen.get(planId) : void 0;
@@ -5262,10 +5541,16 @@ function createMcp({ store, arch: arch2, presence, stopped = () => void 0, versi
5262
5541
  out = { error: true, text: e instanceof HttpError ? message : `Something went wrong inside the plan server: ${message}` };
5263
5542
  }
5264
5543
  return {
5265
- content: [{ type: "text", text: out.text }],
5544
+ content: [{ type: "text", text: withStage(out.text) }],
5266
5545
  ...out.error ? { isError: true } : {}
5267
5546
  };
5268
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
+ }
5269
5554
  function withChanges(out, id, before, s) {
5270
5555
  const rev = store.get(id).rev ?? 0;
5271
5556
  let text2 = out.text;
@@ -6137,9 +6422,11 @@ var SILENT_MS = 15 * 6e4;
6137
6422
  var OURS = /(^|[^a-z])(plan_list|plan_read|plan_create|plan_edit|step_start|step_done|step_failed|step_wait|step_ask)$|^dcursed_/;
6138
6423
  var Agents = class {
6139
6424
  /**
6140
- * @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
6141
6427
  */
6142
- constructor({ store, presence, now = Date.now }) {
6428
+ constructor({ store, presence, now = Date.now, stage = () => "" }) {
6429
+ this.stage = stage;
6143
6430
  this.store = store;
6144
6431
  this.presence = presence;
6145
6432
  this.now = now;
@@ -6175,7 +6462,8 @@ var Agents = class {
6175
6462
  }
6176
6463
  this.say(actor, s, ev.event === "prompt");
6177
6464
  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 } : {} } : {};
6465
+ const context = [this.stage(), b.text].filter(Boolean).join("\n\n");
6466
+ return context ? { context, ...s.plan ? { plan: s.plan } : {} } : {};
6179
6467
  }
6180
6468
  case "invocation": {
6181
6469
  const first = s.rev === 0 && !s.plan;
@@ -6187,7 +6475,8 @@ var Agents = class {
6187
6475
  }
6188
6476
  this.say(actor, s, true);
6189
6477
  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 } : {} } : {});
6478
+ const context = [this.stage(), b.text].filter(Boolean).join("\n\n");
6479
+ return this.merge(s, context ? { context, ...s.plan ? { plan: s.plan } : {} } : {});
6191
6480
  }
6192
6481
  const told = await this.after(actor, s, { event: "tool-after", tool: "invocation" });
6193
6482
  this.say(actor, s, true);
@@ -6550,7 +6839,10 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
6550
6839
  const reconciler = new Reconciler(store, { run: rc.run ?? openCodeRunner({ root: root2, model: rc.model, bin: rc.bin }) });
6551
6840
  const presence = new Presence(presenceOptions);
6552
6841
  const repoFiles = new RepoFiles(root2);
6553
- 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
+ } });
6554
6846
  const calls = new Calls({
6555
6847
  ...callOptions,
6556
6848
  store,
@@ -6666,6 +6958,14 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
6666
6958
  const url = new URL(req.url ?? "/", "http://localhost");
6667
6959
  const parts = url.pathname.split("/").filter(Boolean).map(decodeURIComponent);
6668
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
+ }
6669
6969
  if (req.method === "GET" && url.pathname === "/api/diagnostics") {
6670
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() });
6671
6971
  }
@@ -6788,7 +7088,8 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
6788
7088
  }
6789
7089
  if (req.method === "GET" && parts[0] === "api" && parts[1] === "brief" && parts.length === 2) {
6790
7090
  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);
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");
6792
7093
  return sendText(res, 200, text2, plan2 === void 0 ? {} : { "x-dcursed-plan": plan2, "x-dcursed-rev": String(rev) });
6793
7094
  }
6794
7095
  if (req.method === "GET" && parts[0] === "api" && parts[1] === "events" && parts.length === 2) return listEvents(req, res);
@@ -7247,7 +7548,7 @@ ${END}`;
7247
7548
  ` : rules.includes(BEGIN) && rules.includes(END) ? rules.replace(new RegExp(`${escape(BEGIN)}[\\s\\S]*?${escape(END)}`), () => block) : `${rules.replace(/\n*$/, "\n\n")}${block}
7248
7549
  `;
7249
7550
  said.push(await put(rulesPath, next, "AGENTS.md (how to work with the plan)"));
7250
- said.push("", serveHint(port2));
7551
+ said.push("", FLOW_HINT, "", serveHint(port2));
7251
7552
  return said;
7252
7553
  }
7253
7554
  function escape(s) {
@@ -7356,7 +7657,7 @@ async function initClaudeCode({ root: root2, port: port2 = 7300, agent = "main",
7356
7657
  if (kept) said.push(kept);
7357
7658
  }
7358
7659
  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).");
7660
+ said.push("", FLOW_HINT, "", serveHint(port2), "Then start a new Claude Code session in this folder (approve the dcursed MCP server when asked).");
7360
7661
  return said;
7361
7662
  }
7362
7663
  async function initCursor({ root: root2, port: port2 = 7300, agent = "agent" }) {
@@ -7391,7 +7692,7 @@ alwaysApply: true
7391
7692
  ---
7392
7693
 
7393
7694
  ${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.");
7695
+ said.push("", FLOW_HINT, "", serveHint(port2), "Then enable the dcursed server in Cursor Settings \u2192 MCP, and start a new chat.");
7395
7696
  return said;
7396
7697
  }
7397
7698
  async function initAntigravity({ root: root2, port: port2 = 7300, agent = "agent" }) {
@@ -7420,7 +7721,7 @@ description: How to work with this repository's DiaCode plans
7420
7721
  ---
7421
7722
 
7422
7723
  ${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.");
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.");
7424
7725
  return said;
7425
7726
  }
7426
7727
  var HARNESS_INIT = (
@@ -7645,7 +7946,9 @@ async function hooksEntry(root2, files, harness, events, hooksOf) {
7645
7946
  return { finding: ok(`all ${events.length} hooks are set, in ${where}`), ports: [...new Set(ports)] };
7646
7947
  }
7647
7948
  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)`);
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}");
7649
7952
  }
7650
7953
  async function openCode(root2) {
7651
7954
  const configFile = await text(root2, "opencode.json") !== null ? "opencode.json" : await text(root2, "opencode.jsonc") !== null ? "opencode.jsonc" : "opencode.json";
@@ -7667,7 +7970,7 @@ async function openCode(root2) {
7667
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}"));
7668
7971
  else findings.push(ok(".dcursed/opencode-plugin.js is this version's plugin"));
7669
7972
  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}"));
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}"));
7671
7974
  return { harness: "opencode", label: "OpenCode", ports, findings };
7672
7975
  }
7673
7976
  async function claudeCode(root2) {
@@ -7836,7 +8139,7 @@ function formatReport(report) {
7836
8139
  if (f.fix) lines.push(` ${f.fix}`);
7837
8140
  }
7838
8141
  }
7839
- 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);
7840
8143
  return lines.join("\n").replace(/^\n/, "");
7841
8144
  }
7842
8145
  function redact(text2, root2) {