wezard 2.8.1 → 2.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CLAUDE.md CHANGED
@@ -56,8 +56,8 @@ Three processes, all coordinating via 127.0.0.1:17890 and `~/.wezard/`:
56
56
  - `mirror-bridge.ts` tails `<projectsDir>/<encoded(cwd)>/<sid>.jsonl` and pushes new `assistant` content to a chat — but only for turns the chat itself started: a turn opened by a human's CLI keystroke is recorded to the turn store (rolepage) and kept out of the chat (`wrc.mirror.chatOriginOnly`, brief mode only); approval/askq cards and `[mirror]` notices bypass that gate. Inbound injection is either `claude --resume <sid> -p` (writes a turn into the same jsonl) or `tmux paste-buffer` against a live TTY (only path that makes WeCom messages visible in the user's CLI window). `recentInjects` ring buffer suppresses the WeCom→CLI echo when tailing (which is why an injected line's text is stamped as the turn's `userQuery` at inject time — the tail never sees it). **Every turn has a channel** (`TurnDetailRecord.channel`): the base of the public chat it was spoken in and where its reply goes — a human can `.name` a wizard homed in another chat and the reply (text and cards) returns to the chat that asked, not the wizard's home; `""` = a private wizard↔wizard turn whose reply is pushed nowhere and lives only on the rolepage.
57
57
  - `claim.ts` is a single-shot bootstrap: an exact-match magic phrase from any sender bypasses `allowFrom`, writes that principal as `defaultChat`, and appends to `allowFrom`. This is the **only** legitimate ingress for first-time setup.
58
58
  - `peers.ts` is the read side of multi-agent awareness — "who else is working in this chat, and are they busy". A wizard's HOME chat is its target key's base principal (`baseOfKey`): the untagged default plus every slot `chat:xxx#slot`. Pure parsing only — bounded transcript-tail reads (`tailTurns` / `lastAssistantText` / `summarizeTail`, shared with `session-scan.ts`) and pane classification (`paneIsBusy`). **What a wizard reads about another comes from the transcript, never from a pane capture**: text turns only (`talkTurns`), and "where is it stuck" is `openToolUses` (a tool call left hanging on an idle session = parked on an approval card). The pane is consulted for exactly one thing, `busy`. Read-side tools (`wizard_roster` / `peek_peer` / `read_chat`) answer in plain text rendered daemon-side, not json; `read_chat` (`chat-log.ts`) is computed from session transcripts alone, not the turn store: a log = every recently-active session's ask + final answer per round, merged by timestamp, then narrowed on the rolepage's axis `role` → `chat` → `target` and cut by `since` / `until` / `limit`. Which channel a line belongs to and who said it is read back from the envelope riding on that user line (`parseEnvelope`, `shared/reminder.ts`): every wezard `<system-reminder>` carries its facts as opening-tag attributes (`wezard=envelope|hint|lead|after|mention|roster|pending`, `kind` / `from` / `chat` / `scope`, the injection event id as `msg`) and its prose only for the model; which attrs each kind may write is the `REMINDER_KINDS` registry (each attr is either read back by code or an id the model copies into `re`/`for`/`drop`), and `renderTail` lays one injection's tail out in a fixed order, envelope first — rewording the prose never breaks parsing; old attribute-less wordings keep parsing via its `LEGACY` table. The rolepage collapses each reminder into a tag named by its kind (`<envelope · .x>`, `<回执 · .x · need>`, `<roster>` …) that expands to raw on click; no envelope = a human speaking in the session's home chat. A clone's transcript starts with its parent's forked history, so its rounds older than `bornAt` are dropped. Identity (name / job / memory / lineage) lives in `wizard.ts`, not here. **Busy detection matches the TUI spinner footer** (`… (12m 31s · …)` on current versions, `esc to interrupt` on older ones) in the last 8 non-blank rows — transcript mtime is useless here, it goes quiet during long tool calls.
59
- - `wizard.ts` is the identity layer over those sessions: a target key plus a **globally unique name** — the wizard's only address, written `.name` everywhere a human or model sees it (a chat's default session takes the chat's name, a slot takes its slot id; collisions get `-N` via `pickName`; `settleName` claims lazily, `settleAll` migrates at boot, default sessions first). The slot id inside the key is NOT the name: a rename never rekeys a session. Plus a one-line job description, a long-term `memory` list, and a `parent` link that makes a session a CLONE of another. The registry is a write-through json (`~/.wezard/wizards.json`, `wrc.mirror.wizardsFile`) bound process-wide via `bindWizardStore` so the IM side can read it too; everything else in the module is a pure renderer. **Identity travels as a system prompt, never as a message**: `renderCharter` builds the wizard's charter (who it is, its workspace, its clones, its memory, the chat's and the workspace's shared memory (`wizard-memory.ts`: `~/.wezard/memory/{chats,workspaces}/*.md`, human-editable, appended by `wizard_remember({scope})`), the tool roster, the orchestration playbook, the public-vs-private etiquette) and `spawn-tmux` presses it in with `--append-system-prompt "$(cat <file>)"` — so it survives `/clear`, costs no turn, and never shows in chat. Every spawn path (`/new`, a dead-pane respawn, a clone) pulls it from `MirrorBridge.setCharterProvider`, installed in `index.ts`. Since a running wizard never sees a new charter, `config_set` renders every chartered wizard's charter before and after the change and tells the affected ones (and the caller) to `handoff` — generic over whatever config the charter reads. Backends with no such flag spawn without a charter rather than with a rejected flag.
60
- - **Cloning is a context fork**: `MirrorBridge.cloneSession` spawns `--resume <parent sid> --fork-session`, so the child starts holding everything the parent had read while the parent is untouched — that is what makes "load the shared material once, then fan out" work. Two invariants: `--fork-session` is mandatory (without it a second pane appends to the parent's jsonl and two chats cross-wire), and the forked transcript only appears when that pane takes its FIRST message — so the clone's opening line is the trigger, and the attach waits for the fork; if it never appears the pane is killed rather than bound to the parent's sid.
59
+ - `wizard.ts` is the identity layer over those sessions: a target key plus a **globally unique name** — the wizard's only address, written `.name` everywhere a human or model sees it (a chat's default session takes the chat's name, a slot takes its slot id; collisions get `-N` via `pickName`; `settleName` claims lazily, `settleAll` migrates at boot, default sessions first). The slot id inside the key is NOT the name: a rename never rekeys a session. Plus a one-line job description, a long-term `memory` list, and a `parent` link that makes a session a CLONE of another. The registry is a write-through json (`~/.wezard/wizards.json`, `wrc.mirror.wizardsFile`) bound process-wide via `bindWizardStore` so the IM side can read it too; everything else in the module is a pure renderer. **Identity travels as the first message's preamble, not the system prompt**: `renderCharter` builds the wizard's charter (who it is, its workspace, its clones, its memory, the chat's and the workspace's shared memory (`wizard-memory.ts`: `~/.wezard/memory/{chats,workspaces}/*.md`, human-editable, appended by `wizard_remember({scope})`), the tool roster, the orchestration playbook, the public-vs-private etiquette). `spawn-tmux` only parks it at `charters/<sid>.md` (claude/codebuddy no longer get `--append-system-prompt` — it cost ~1.4s per cold start); the attachment's `charterPending` prepends it as `<system-reminder wezard="charter">` to the pane's first non-slash injection and clears it once that injection is confirmed. It is re-armed on every moment a session has not read it: `/new`, a spare-pool claim, a dead-pane respawn, `/clear` and compaction (`onContextCut` → `armCharter`); a clone's opening line carries the child's charter, superseding the parent's inherited one. Read sides (`stripMeta`, `cleanUserText`, rolepage) strip/collapse the `charter` reminder, so it never becomes a chat ask or a bubble. Codex keeps it in `developer_instructions`. Every spawn path (`/new`, a dead-pane respawn, a clone) pulls it from `MirrorBridge.setCharterProvider`, installed in `index.ts`. Since a running wizard never sees a new charter, `config_set` renders every chartered wizard's charter before and after the change and tells the affected ones (and the caller) to `handoff` — generic over whatever config the charter reads. Backends with no such flag spawn without a charter rather than with a rejected flag.
60
+ - **Cloning is a context fork**: `MirrorBridge.cloneSession` spawns `--resume <parent sid> --fork-session`, so the child starts holding everything the parent had read while the parent is untouched — that is what makes "load the shared material once, then fan out" work. Two invariants: `--fork-session` is mandatory (without it a second pane appends to the parent's jsonl and two chats cross-wire), and the attach waits for the forked transcript (codebuddy 2.167 writes it at process start — a byte copy of the parent plus a `session-meta` row, no API call; older CLIs only on the first message); if it never appears the pane is killed rather than bound to the parent's sid.
61
61
  - **Chats are public channels, wizard↔wizard is private by default.** `send_peer` injects with `channel:""` and posts no bubble; `public:true` (the model decides) posts `emoji .a → .b` into the sender's current channel and the reply follows there. No spawn/relay/job bubbles remain — only `notify`. A `tell_peer` carrying a `job` is always private (`public` is ignored), so a fan-out's whole process stays on the rolepage; the human sees only the initiator's own closing reply, routed back along the chain that asked it. A chat with `chatPolicy.<chat>.topOnly` (top-level-only mode) on — **the default since 2026-10-15: only an explicit `false` turns it off** — goes further (daemon-enforced in `tellPeerAs` / `/notify`): every wizard↔wizard line there is private regardless of `public`, and a wizard whose turn is working for a peer (a private peer task, or a receipt whose row serves a peer task) may not `notify` it (the steward is exempt in its own chat) — the charter tells top-level wizards to explain the result in their own words. The same switch also arms the steward hand-brake (`approval.ts` / `steward-guard.ts`) on that chat's default session: the untagged session may not edit files or open subagents, and caps its own look-commands per turn at `stewardBudget` (reading code — Read/Grep/Glob and read-only shell commands — passes free).
62
62
  - **`tell_peer` delivery policy** (`priority`) only matters when the target is busy: `normal` (default) waits for its turn to end before pasting — two senders pasting into one busy box get read as one turn; `urgent` presses Esc first (the same interrupt as `stop_wizard`, without the teardown that would drop others' queued lines); `now` pastes into the running turn (interject, answer its question; the default for `re`).
63
63
  - `daemon/router.ts` makes `tell_peer` asynchronous: **one row per event** — `<event, owner, receiver>` in the journal `~/.wezard/routes.jsonl` (one op per line, folded at boot; `owner` = who owes the answer, `receiver` = where the conclusion goes, `receiver.event` = the parent row this round serves). The old machines are gone (T10): `receipts.ts`, `receiver-stack.ts`, `answer-transfer.ts`, the frame/stack parent chain and its `k` attribute, the `t…` turn ids, and the bubble answer handover. No transcript watcher locates an answer any more: the message-events layer reports each injected round's result and `router.onFinal(owner, serves, verdict)` folds it into ops (`mark` for `need`/`error`, `answer` for a conclusion); the sweeper synthesizes `timeout` (`deadline`, default 1h) / `silent` / `dead` failures the same way, delivered rather than dropped because "no answer" is also an answer. Delivery always lands the `answer` op first and then hands off: a wizard receiver gets a durable inbox entry `rcpt:<event>:<rev>` (idempotent by content revision), a chat receiver is a bubble the final gate releases. `re` continues **the same event** (`route:<event>:r<legs>`, same job and channel); the hard brake is the job budget. Ownership moves with `move` (transfer = tail call), and a receiver that no longer exists escalates along the receiver edges up to the first live wizard or to the chat root (Dead Letter); the receipt envelope's body says who was skipped / that it arrived late (no attrs — nothing reads them back). Everything the roster / peek / `list_jobs` print as 「在等 / 欠着」 is derived from the table (`owedBy` / `awaitedBy`), never stored twice. `stop_wizard` / `close_job` cascade `canceled` down the subtree before killing. Run only the affected direction: charter/prompt `node scripts/receipt-regress/run.mjs --group charter`; dispatch `--group dispatch`; router state `--group receipt-core`; daemon/runtime boundaries `--group runtime`. The default command runs the offline charter, dispatch, and receipt-core groups; `--full` adds runtime cases but excludes reloads. A reload case must be named alone with `RR_ALLOW_RELOAD=1` (for example, `reload-answered-hand` or `after-reload`); reload cases cannot be combined with a group or `--full`.
@@ -1,10 +1,26 @@
1
1
  // Local control HTTP — talks to hooks, slash commands, MCP server.
2
2
  // Bound to 127.0.0.1; trust = "anyone with loopback access".
3
3
  // Endpoints intentionally tiny & sync-friendly.
4
+ import { existsSync, readFileSync } from "node:fs";
4
5
  import { createServer } from "node:http";
5
- import { URL } from "node:url";
6
+ import { dirname, join } from "node:path";
7
+ import { URL, fileURLToPath } from "node:url";
6
8
  import { expandHome } from "../shared/paths.js";
7
9
  import { drainForReload, listPending } from "./pending.js";
10
+ /** 外部调用方的能力判据 (/status): 按名字查有没有, 别靠盘上目录之类的副作用猜。 */
11
+ const CAPABILITIES = ["dispatch.taskFile"];
12
+ // 加载时读一次: 报的是正在跑的这份代码的版本, 不是盘上刚 pull 下来的。源码跑 daemon/ → ../,
13
+ // 编译后与 npm 安装 dist/daemon/ → ../../ (同 web-assets 的双候选)。
14
+ const HERE = dirname(fileURLToPath(import.meta.url));
15
+ const VERSION = (() => {
16
+ const p = [join(HERE, "..", "package.json"), join(HERE, "..", "..", "package.json")].find(existsSync);
17
+ try {
18
+ return p ? String(JSON.parse(readFileSync(p, "utf8")).version ?? "") : "";
19
+ }
20
+ catch {
21
+ return "";
22
+ }
23
+ })();
8
24
  const json = (res, status, body) => {
9
25
  res.statusCode = status;
10
26
  res.setHeader("content-type", "application/json");
@@ -31,6 +47,8 @@ const routes = {
31
47
  const bots = ws.bots();
32
48
  json(res, 200, {
33
49
  ok: true,
50
+ version: VERSION,
51
+ capabilities: CAPABILITIES,
34
52
  wsConnected: ws.client.isConnected,
35
53
  ws: ws.status(),
36
54
  backend: cfg.wrc.defaultCli,
@@ -1 +1 @@
1
- {"version":3,"file":"http.js","sourceRoot":"","sources":["../../daemon/http.ts"],"names":[],"mappings":"AAAA,mEAAmE;AACnE,6DAA6D;AAC7D,gDAAgD;AAChD,OAAO,EAAE,YAAY,EAA6C,MAAM,WAAW,CAAC;AACpF,OAAO,EAAE,GAAG,EAAE,MAAM,UAAU,CAAC;AAG/B,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB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AAO,EAAE,CAAC,CAAC;QAC7F,CAAC;IACH,CAAC,CAAC,CAAC;IAEH,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,EAAE;QAC3D,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,IAAI,EAAE,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,EAAE,gBAAgB,CAAC,CAAC;IAC3F,CAAC,CAAC,CAAC;IAEH,OAAO;QACL,KAAK,EAAE,GAAG,EAAE,CACV,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE;YAC5B,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC;QAChC,CAAC,CAAC;QACJ,QAAQ,EAAE,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,OAAO,CAAC;KACtD,CAAC;AACJ,CAAC,CAAC;AAGF,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC"}
@@ -29,7 +29,7 @@ import { loadMirrorStore } from "./mirror-store.js";
29
29
  import { cancelOps, deadlineOf, eventRef, finalKind, isEventRef, makeOutcome, openRouter, ops, pickPair } from "./router.js";
30
30
  import { createMessageEvents, messageId, finalId, reportSource, receiptCoverage, receiptFacts } from "./message-events.js";
31
31
  import { startMirror, installMirrorEventListener } from "./mirror-bridge.js";
32
- import { backendFor, bindStartupNotice, runTmux, setTmuxTimeoutReporter, spawnTmuxClaude } from "./spawn-tmux.js";
32
+ import { backendFor, bindStartupNotice, prewarmShell, runTmux, setTmuxTimeoutReporter, spawnTmuxClaude } from "./spawn-tmux.js";
33
33
  import { bindCardChannel, installApprovalEventListener, makeApproveHandler, requestConfirm } from "./approval.js";
34
34
  import { initDetailPersistence, makeDetailHandler, chatHandlers, configureRemoteForward, chatUrlFor, buildChatUrl, getDetail, setWorldFactsProvider, currentHumanQueryOf, recordPost, recordCharter, backfillCharter } from "./detail.js";
35
35
  import { EMPTY_FACTS } from "../shared/world.js";
@@ -59,6 +59,7 @@ import { checkDirection } from "./direction.js";
59
59
  import { loadJobStore, dutyLine, awaitingAccept, stalledRoots, shelvedRoots, nudgeDue, dayClamp, childrenOf as jobChildren, jobEpisode, rejectReason, ACCEPTS, JOB_MEMBER_MAX, JOB_DEPTH_MAX, depthOf, ancestorsOf as jobAncestors, treeOrder, jobStage } from "./jobs.js";
60
60
  import { cacheTouchMs, cacheTtlSec, clipMiddle, contextMaterials, firstStamp, parseClosing, stripClosingMark, stripForChat, lastContextTokens, lastExchange, lastModel, openingTurn, talkTurns, turnsSince, renderPeerEnvelope, renderReceiptEnvelope, renderTaskEnvelope } from "./peers.js";
61
61
  import { expandHome } from "../shared/paths.js";
62
+ import { expandTask, TemplateError } from "../shared/task-template.js";
62
63
  import { loadJsonMap } from "../shared/json-map-store.js";
63
64
  import { createWorkflowNodes } from "./workflow-nodes.js";
64
65
  import { loadWorkflowPlans, createWorkflowPlanRunner } from "./workflow-plans.js";
@@ -593,7 +594,8 @@ const main = async () => {
593
594
  return;
594
595
  }
595
596
  const spawnLog = log.child({ mod: "mirror", sub: "spawn-init", target });
596
- const r = await spawnTmuxClaude({ cfg, log: spawnLog, windowName: target, chatKey: target, systemPrompt: charterFor(target, { cli: backendFor(cfg).name }) });
597
+ const charter = charterFor(target, { cli: backendFor(cfg).name });
598
+ const r = await spawnTmuxClaude({ cfg, log: spawnLog, windowName: target, chatKey: target, systemPrompt: charter });
597
599
  if (!r.ok) {
598
600
  json(res, 500, { ok: false, reason: r.reason });
599
601
  return;
@@ -605,6 +607,9 @@ const main = async () => {
605
607
  return;
606
608
  }
607
609
  const att = m.attach({ sessionId: r.sessionId, jsonlPath: r.jsonlPath, target, tmuxPane: r.tmuxPane, tmuxSession: r.tmuxSession });
610
+ // spawn 不再带宪章 (省冷启动), 身份改挂到这个 pane 的首条注入上。
611
+ if (att.ok)
612
+ m.armCharter(target, charter);
608
613
  json(res, att.ok ? 200 : 500, att.ok ? { ok: true, sessionId: r.sessionId, tmuxSession: r.tmuxSession, tmuxPane: r.tmuxPane, target } : { ok: false, reason: att.reason });
609
614
  });
610
615
  // A missing agent identity is an error, never an invitation to impersonate defaultChat.
@@ -2349,9 +2354,28 @@ const main = async () => {
2349
2354
  return undefined;
2350
2355
  };
2351
2356
  const transferNote = (f, target) => `这一笔 (${f}) 已整件交给 ${displayName(target)}: 它的结论 (含 NEED / 失败) 直接回你服务的上游, 不回你 —— 本轮静默收口, 别再为这件派活或对人说话`;
2357
+ /** taskFile 模板的解析基点: 调用方工作区 —— session 的 runningCwd (冷会话落
2358
+ * defaultCwd, 见 mirror-bridge 的 getCwd), 都为空才退 daemon 进程 cwd。模板
2359
+ * 路径相对它解析, realpath 后必须仍在它子树内 (防 ../ 与软链逃出工作区)。 */
2360
+ const callerBaseOf = (self) => m.getCwd(self).runningCwd || m.getCwd(self).defaultCwd || process.cwd();
2352
2361
  const tellPeerAsInner = async (self, body, extra = "", planned, actor) => {
2353
2362
  const authority = actor?.authority ?? (!planned ? controlSnapshot(self) : undefined);
2354
- const text = (body.text ?? "").toString();
2363
+ const tb = body;
2364
+ let text = (tb.text ?? "").toString();
2365
+ let templateRef = tb.templateRef;
2366
+ // 模板展开同样在一切副作用之前 (路由行要到下面的 openDispatchRow 才开): text 空
2367
+ // 而 taskFile 给了 → 入口展开, 失败 400; text 非空时 taskFile 忽略 —— dispatch
2368
+ // 入口已展开过的正文原样走, 不重复读文件。
2369
+ if (!text.trim() && (tb.taskFile ?? "") !== "") {
2370
+ try {
2371
+ const expanded = await expandTask({ taskFile: tb.taskFile, params: tb.params ?? {} }, { baseDir: callerBaseOf(self) });
2372
+ text = expanded.text;
2373
+ templateRef = expanded.templateRef;
2374
+ }
2375
+ catch (e) {
2376
+ return { status: 400, body: { ok: false, reason: e instanceof TemplateError ? e.message : `template expansion failed: ${errText(e)}` } };
2377
+ }
2378
+ }
2355
2379
  if (!text.trim()) {
2356
2380
  return { status: 400, body: { ok: false, reason: "text required" } };
2357
2381
  }
@@ -2614,6 +2638,7 @@ const main = async () => {
2614
2638
  ...(wantReceipt ? { tell } : {}), job: jobId, kind, attemptId, after: afters,
2615
2639
  role: roleParam(body.role), free: freed,
2616
2640
  ...(plan.op === "transfer" ? { transferred: true } : {}),
2641
+ ...(templateRef ? { templateRef } : {}),
2617
2642
  } } }, plan.op === "transfer");
2618
2643
  }
2619
2644
  catch (error) {
@@ -3333,6 +3358,10 @@ const main = async () => {
3333
3358
  };
3334
3359
  m.onContextCut((t, cut) => {
3335
3360
  pendingCuts.set(t, cut);
3361
+ // 宪章跟着消息走 (不再在系统提示里), /clear 与压缩都会把它从上下文里抹掉 ——
3362
+ // 现渲染一份挂到下一次注入上, 让身份跨过这次截断。reload 后没有附着表也照挂:
3363
+ // armCharter 只对活着的附着生效, 冷记录等重生时再挂。
3364
+ m.armCharter(t);
3336
3365
  // 之前挂过的提示随对话一起没了: 去重窗口清零, 下一次该给的规矩照给。
3337
3366
  notices.forget(t);
3338
3367
  const now = wizards.get(t)?.memory ?? [];
@@ -3636,6 +3665,9 @@ const main = async () => {
3636
3665
  // 派活收成一步 (见 route.decide): 查候选 → 过成本门控 → 转给已有的或按档白板 spawn →
3637
3666
  // tell_peer 投出去, 回决定与理由。默认决定由守护进程算; 管家不同意就 `to` 点名、
3638
3667
  // `force` 越过冷门控、`spawn:true` 硬要新的 —— 推翻要显式说。
3668
+ /** dispatch 回包的 reason: 投成了是选人理由; 投递 / 起 wizard 失败时 reason 必须是真实错误,
3669
+ * 选人理由降到 why —— 否则「你要了新的」会盖掉 bearAs / tell 的失败原因。 */
3670
+ const dispatchReason = (ok, real, why) => ok ? { reason: why } : { reason: String(real ?? "delivery failed (no reason)"), why };
3639
3671
  http.register("POST /dispatch", async (req, res) => {
3640
3672
  const { self, body } = await readPeerBody(req);
3641
3673
  if (!self) {
@@ -3643,8 +3675,26 @@ const main = async () => {
3643
3675
  return;
3644
3676
  }
3645
3677
  const b = body;
3646
- const task = (b.task ?? "").toString().trim();
3647
- if (!task) {
3678
+ // 模板展开 (§6/§8) 必须发生在一切副作用之前 —— 选人、开根单、bearAs 全在后面:
3679
+ // 失败 400, 不留孤儿 wizard、不开路由行。taskFile 单独成立 (task 不必陪跑);
3680
+ // 选人/选档/description 用的摘要从展开文本 (或 params.header) 派生, 投递的是全文。
3681
+ let task = (b.task ?? "").toString().trim();
3682
+ let text = task;
3683
+ let templateRef;
3684
+ if ((b.taskFile ?? "") !== "") {
3685
+ let expanded;
3686
+ try {
3687
+ expanded = await expandTask({ taskFile: b.taskFile, params: b.params ?? {} }, { baseDir: callerBaseOf(self) });
3688
+ }
3689
+ catch (e) {
3690
+ json(res, 400, { ok: false, reason: e instanceof TemplateError ? e.message : `template expansion failed: ${errText(e)}` });
3691
+ return;
3692
+ }
3693
+ text = expanded.text;
3694
+ task = clipLine((b.params?.header ?? "").toString().trim() || expanded.text, 120);
3695
+ templateRef = expanded.templateRef;
3696
+ }
3697
+ if (!text.trim()) {
3648
3698
  json(res, 400, { ok: false, reason: "task is required" });
3649
3699
  return;
3650
3700
  }
@@ -3718,6 +3768,7 @@ const main = async () => {
3718
3768
  let rootId = "";
3719
3769
  const tell = (name, text, extra = "") => tellPeerAs(self, {
3720
3770
  name, text, public: b.public !== false, force,
3771
+ ...(templateRef ? { templateRef } : {}),
3721
3772
  ...(plan.op !== "self" ? { return: plan.op } : {}),
3722
3773
  // lead 的活远超默认的 1h: 不给 deadline 就按 12h (回执的上限)。
3723
3774
  ...(b.deadline !== undefined ? { deadline: b.deadline } : lead ? { deadline: 43200 } : {}),
@@ -3760,7 +3811,7 @@ const main = async () => {
3760
3811
  }
3761
3812
  // 已有 wizard 当 lead: 宪章是出生时定的 (里面没有 lead 一节), 规矩加打法挂在信封后面带过去;
3762
3813
  // 已是 lead 的宪章里已有层级规矩, 只带打法。投成了才记 lead, 它下次重生宪章里就有。
3763
- const t = await tell(name, task, lead ? renderReminder({ wezard: "lead" }, wizards.get(r.target)?.lead ? renderLeadPlaybook() : renderLead()) : "");
3814
+ const t = await tell(name, text, lead ? renderReminder({ wezard: "lead" }, wizards.get(r.target)?.lead ? renderLeadPlaybook() : renderLead()) : "");
3764
3815
  if (lead && t.status === 200)
3765
3816
  wizards.upsert(r.target, { lead: true });
3766
3817
  if (rootId && t.status === 200)
@@ -3768,7 +3819,7 @@ const main = async () => {
3768
3819
  // 自动选中的被冷门控 (decide 用名册的活动时刻, 门控用 transcript 的, 口径差一点) 或方向闸 (它归别人管 / 是借来的专家) 退回: 改走 spawn; 点名的不改。
3769
3820
  if (!(!to && (t.body.gated === "cold" || t.body.gated === "direction" || t.body.gated === "reuse"))) {
3770
3821
  settleRoot(t.status === 200);
3771
- json(res, t.status, withRoot({ ...t.body, decision: "existing", reason: d.why, ...(shown.length ? { candidates: shown } : {}) }));
3822
+ json(res, t.status, withRoot({ ...t.body, decision: "existing", ...dispatchReason(t.status === 200, t.body.reason, d.why), ...(shown.length ? { candidates: shown } : {}) }));
3772
3823
  return;
3773
3824
  }
3774
3825
  diagnostics.deliveryFallback = String(t.body.reason);
@@ -3782,7 +3833,7 @@ const main = async () => {
3782
3833
  const born = await bearAs(self, { inherit: false, name, description, tier, ...(lead ? { lead: true } : {}) }, undefined, dispatchOrigin?.authority);
3783
3834
  if (born.status !== 200) {
3784
3835
  settleRoot(false);
3785
- json(res, born.status, { ...born.body, diagnostics, decision: "spawn", reason: d.why });
3836
+ json(res, born.status, { ...born.body, diagnostics, decision: "spawn", ...dispatchReason(false, born.body.reason, d.why) });
3786
3837
  return;
3787
3838
  }
3788
3839
  if (!controlValid(self, dispatchOrigin.authority)) {
@@ -3791,7 +3842,7 @@ const main = async () => {
3791
3842
  return;
3792
3843
  }
3793
3844
  // 宪章里只有层级规矩, 打法随信封带 (宪章每轮都在上下文里, 打法只这一件活用得上)。
3794
- const t = await tell(String(born.body.name), task, lead ? renderReminder({ wezard: "lead" }, renderLeadPlaybook()) : "");
3845
+ const t = await tell(String(born.body.name), text, lead ? renderReminder({ wezard: "lead" }, renderLeadPlaybook()) : "");
3795
3846
  settleRoot(t.status === 200);
3796
3847
  // 为这张根单生出来的 (tell 记的是 spawned:false, 再 attach 一次补上; lead 角色也在这里记)。
3797
3848
  if (rootId && t.status === 200)
@@ -3799,7 +3850,7 @@ const main = async () => {
3799
3850
  json(res, t.status, withRoot({
3800
3851
  ...t.body,
3801
3852
  decision: "spawn",
3802
- reason: d.why,
3853
+ ...dispatchReason(t.status === 200, t.body.reason, d.why),
3803
3854
  tier,
3804
3855
  ...(born.body.model ? { model: born.body.model } : {}),
3805
3856
  ...(born.body.effort ? { effort: born.body.effort } : {}),
@@ -3875,6 +3926,11 @@ const main = async () => {
3875
3926
  const authority = planned ? undefined : capturedAuthority ?? controlSnapshot(self);
3876
3927
  if (authority && !controlValid(self, authority))
3877
3928
  return { status: 409, body: { ok: false, reason: "this turn no longer owns control; cannot spawn more work" } };
3929
+ // 出生投递 (下方 acceptPeerDispatch) 不经 tellPeerAsInner 的模板展开入口 ——
3930
+ // 第一期不接 taskFile; MCP 层已拦, 这里兜直连 HTTP / 旧 MCP 进程: 显式 400,
3931
+ // 不让调用方以为模板生效了而实际投出去的是空正文。
3932
+ if (body.taskFile !== undefined)
3933
+ return { status: 400, body: { ok: false, reason: "taskFile not supported on spawn_wizard; use dispatch" } };
3878
3934
  // Legacy bootstrap can dispatch before attaching its member. An empty job
3879
3935
  // is not available for plan ownership while that birth is still in flight.
3880
3936
  const birthJob = (body.job ?? "").trim();
@@ -5272,6 +5328,10 @@ const main = async () => {
5272
5328
  }
5273
5329
  setTimeout(() => void sweep().catch((e) => log.warn({ err: e.message }, "pane cap sweep failed")), 15_000).unref();
5274
5330
  }
5331
+ // 暖 shell: 默认 workspace 先养一条空壳, 开机后第一次 spawn 就能直接领 (省掉整段 rc)。
5332
+ // 延后到启动那一波过去: 活着几十个会话时 boot 正在恢复一大片 pane, 一条空壳不必去抢
5333
+ // 第一波 fork (macOS 无 swap, 瞬时 ENOMEM 就是这么来的)。
5334
+ setTimeout(() => void prewarmShell(cfg, cfg.wrc.cwd, log.child({ mod: "mirror", sub: "warm" })), 20_000).unref();
5275
5335
  let shuttingDown = false;
5276
5336
  const shutdown = async (signal) => {
5277
5337
  if (shuttingDown)