wezard 2.7.7 → 2.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CLAUDE.md +2 -2
  2. package/dist/daemon/approval.js +7 -6
  3. package/dist/daemon/approval.js.map +1 -1
  4. package/dist/daemon/chat-log.js +25 -6
  5. package/dist/daemon/chat-log.js.map +1 -1
  6. package/dist/daemon/chat-name.js +52 -5
  7. package/dist/daemon/chat-name.js.map +1 -1
  8. package/dist/daemon/handoff.js +30 -1
  9. package/dist/daemon/handoff.js.map +1 -1
  10. package/dist/daemon/inbound.js +1 -1
  11. package/dist/daemon/inbound.js.map +1 -1
  12. package/dist/daemon/index.js +150 -35
  13. package/dist/daemon/index.js.map +1 -1
  14. package/dist/daemon/message-events.js +75 -9
  15. package/dist/daemon/message-events.js.map +1 -1
  16. package/dist/daemon/mirror-bridge.js +555 -45
  17. package/dist/daemon/mirror-bridge.js.map +1 -1
  18. package/dist/daemon/peers.js +255 -4
  19. package/dist/daemon/peers.js.map +1 -1
  20. package/dist/daemon/picker-policy.js +8 -0
  21. package/dist/daemon/picker-policy.js.map +1 -1
  22. package/dist/daemon/route.js +274 -49
  23. package/dist/daemon/route.js.map +1 -1
  24. package/dist/daemon/spawn-tmux.js +72 -12
  25. package/dist/daemon/spawn-tmux.js.map +1 -1
  26. package/dist/daemon/steward-guard.js +8 -15
  27. package/dist/daemon/steward-guard.js.map +1 -1
  28. package/dist/daemon/tips.js +1 -1
  29. package/dist/daemon/tips.js.map +1 -1
  30. package/dist/daemon/wizard.js +15 -15
  31. package/dist/daemon/wizard.js.map +1 -1
  32. package/dist/mcp/server.js +37 -15
  33. package/dist/mcp/server.js.map +1 -1
  34. package/dist/shared/codex-hooks.js +60 -0
  35. package/dist/shared/codex-hooks.js.map +1 -1
  36. package/dist/shared/config.js +1 -1
  37. package/dist/shared/config.js.map +1 -1
  38. package/dist/shared/message-footer.js +16 -1
  39. package/dist/shared/message-footer.js.map +1 -1
  40. package/dist/shared/modal-pane.js +18 -2
  41. package/dist/shared/modal-pane.js.map +1 -1
  42. package/dist/shared/reminder.js +9 -5
  43. package/dist/shared/reminder.js.map +1 -1
  44. package/dist/shared/startup-notice.js +21 -0
  45. package/dist/shared/startup-notice.js.map +1 -0
  46. package/dist/shared/tool-hints.js +2 -2
  47. package/dist/shared/tool-hints.js.map +1 -1
  48. package/dist/shared/workspace-trust.js +54 -2
  49. package/dist/shared/workspace-trust.js.map +1 -1
  50. package/package.json +1 -1
@@ -1,7 +1,7 @@
1
1
  import { finalId, receiptCoverage, receiptQuiet } from "./message-events.js";
2
2
  import { parseEnvelope, renderTail } from "../shared/reminder.js";
3
3
  import { codexSessions, codexSessionForPane, recordCodexPaneSession } from "../shared/codex.js";
4
- import { codexHookLaunchArgs, codexHookCommand } from "../shared/codex-hooks.js";
4
+ import { codexHookLaunchArgs, codexHookCommand, inspectCodexHooks, trustCodexHookSet } from "../shared/codex-hooks.js";
5
5
  import { fileURLToPath } from "node:url";
6
6
  // Mirror-mode bridge.
7
7
  //
@@ -30,7 +30,7 @@ import { withImageClipboard, pasteVerifiedImage } from "./image-input.js";
30
30
  import { createKeyedScheduler } from "../shared/keyed-scheduler.js";
31
31
  import { withPaneInput } from "./pane-input.js";
32
32
  import { activeBackends, resolveCliBackend, backendForPath, projectDirFor, projectDirsFor, } from "../shared/cli-backends.js";
33
- import { isModalPane, isAskqSubmitPage, parseModalOptions, pickModalAnswer, pickAutoAllowAnswer, parseConfirmContext, modalFingerprint, looksLikePicker } from "../shared/modal-pane.js";
33
+ import { isModalPane, isCodexHookReviewPane, isAskqSubmitPage, parseModalOptions, pickModalAnswer, pickAutoAllowAnswer, parseConfirmContext, modalFingerprint, looksLikePicker } from "../shared/modal-pane.js";
34
34
  import { hasMirrorAskq, runMirrorAskqFlow, hasMirrorPlan, mootMirrorPlan, runMirrorPlanFlow, hasMirrorPicker, mootMirrorPicker, runMirrorPickerFlow } from "./approval.js";
35
35
  import { isAutoWindowActive } from "./session-cache.js";
36
36
  import { noticeSuffixFor } from "./notices.js";
@@ -38,7 +38,7 @@ import { dispatchPickerPolicy, pickerPolicy } from "./picker-policy.js";
38
38
  import { renameWindow, runTmux, spawnTmuxClaude } from "./spawn-tmux.js";
39
39
  import { selectEffort, selectModel } from "./model-select.js";
40
40
  import { parseEffort } from "../shared/effort.js";
41
- import { hasRegistry, liveSessionPids, markTranscript, probeOf, registrySnapshot, sessionOfPid, sessionOnPane, submittedSince, submittedEventSince, watchRegistry } from "./wezard-session.js";
41
+ import { hasRegistry, liveSessionPids, markTranscript, probeOf, readRegistry, registrySnapshot, sessionOfPid, sessionOnPane, submittedSince, submittedEventSince, watchRegistry } from "./wezard-session.js";
42
42
  import { waitForIdle } from "./graph.js";
43
43
  import { wizardStore } from "./wizard.js";
44
44
  import { startSubagentWatch } from "./subagent-tail.js";
@@ -2046,8 +2046,11 @@ const injectViaTmuxText = async (target, text, log, freshSpawn, witness = NO_WIT
2046
2046
  }
2047
2047
  // 补到头仍没证据: 可能只是渲染/落盘迟到, 也可能根本没提交。
2048
2048
  // 保留 uncertain 阻止重贴, 但不能让只看 ok 的调用方把它当成已送达。
2049
+ // 冷 TUI 的框布局未知时也可能已经提交;同样等原生事件见证,期间不再输入。
2050
+ if (requireEventEvidence && await lateEvidence(LATE_LAND_MS))
2051
+ return { ok: true };
2049
2052
  log.warn({ target, tailFp, freshSpawn, boxTrusted, witness: witness.status }, "mirror inject: submission unconfirmed, stopping input");
2050
- return { ok: false, uncertain: true, reason: "目标会话未确认收下消息,停止输入以避免误提交或重复投递" };
2053
+ return { ok: false, uncertain: true, reason: "暂时无法确认目标会话是否收到消息,已停止继续输入;为避免重复执行,不会自动重发" };
2051
2054
  };
2052
2055
  const injectViaSpawn = async (args) => {
2053
2056
  const { text, images = [], cfg, log, sessionId, jsonlPath } = args;
@@ -2503,7 +2506,7 @@ export const startMirror = (deps) => {
2503
2506
  return;
2504
2507
  s.flushTimer = setTimeout(() => void flushStream(s), FLUSH_MS);
2505
2508
  };
2506
- const finalizeStream = async (a, s, timedOut = false) => {
2509
+ const finalizeStream = async (a, s, timedOut = false, stillWanted) => {
2507
2510
  if (s.closed)
2508
2511
  return;
2509
2512
  s.closed = true;
@@ -2534,14 +2537,16 @@ export const startMirror = (deps) => {
2534
2537
  await s.pending?.catch(() => undefined);
2535
2538
  if (!eventOwned(s.eventId))
2536
2539
  return;
2537
- if (card) {
2538
- s.cardSent = true;
2539
- await client.replyStreamWithCard(s.frame, s.streamId, withLinkedTag(a, body, undefined, s.turnId), true, { templateCard: card });
2540
- }
2541
- else {
2542
- await client.replyStream(s.frame, s.streamId, withLinkedTag(a, body, undefined, s.turnId), true);
2540
+ if (stillWanted?.() !== false) {
2541
+ if (card) {
2542
+ s.cardSent = true;
2543
+ await client.replyStreamWithCard(s.frame, s.streamId, withLinkedTag(a, body, undefined, s.turnId), true, { templateCard: card });
2544
+ }
2545
+ else {
2546
+ await client.replyStream(s.frame, s.streamId, withLinkedTag(a, body, undefined, s.turnId), true);
2547
+ }
2548
+ log.info({ sessionId: a.sessionId, turnId: s.turnId, accLen: s.acc.length, tools: s.tools.length, withCard: !!card, timedOut }, "stream finalize");
2543
2549
  }
2544
- log.info({ sessionId: a.sessionId, turnId: s.turnId, accLen: s.acc.length, tools: s.tools.length, withCard: !!card, timedOut }, "stream finalize");
2545
2550
  }
2546
2551
  catch (e) {
2547
2552
  log.warn({ sessionId: a.sessionId, turnId: s.turnId, err: e.message }, "stream finalize failed");
@@ -2601,7 +2606,7 @@ export const startMirror = (deps) => {
2601
2606
  // 推到本轮的频道 (人从别的群叫它 → 回那个群)。私聊轮的正文 brief 下在上游
2602
2607
  // turnSilent 已被拦下; 非 brief 的逐条推送在这里兜一道 —— 只放 `[mirror]` /
2603
2608
  // `[wezard]` 系统提示 (它们回 home)。
2604
- const sendStandalone = (a, content) => {
2609
+ const sendStandalone = (a, content, stillWanted) => {
2605
2610
  const eventId = a.activeEventId;
2606
2611
  if (!hasVisibleBody(content) || !eventOwned(eventId))
2607
2612
  return;
@@ -2614,7 +2619,7 @@ export const startMirror = (deps) => {
2614
2619
  a.standalonePending = a.standalonePending
2615
2620
  .then(async () => {
2616
2621
  for (const c of chunks) {
2617
- if (!eventOwned(eventId))
2622
+ if (!eventOwned(eventId) || stillWanted?.() === false)
2618
2623
  return;
2619
2624
  try {
2620
2625
  const ack = await client.sendMessage(chatId, { msgtype: "markdown", markdown: { content: c } });
@@ -5265,21 +5270,23 @@ export const startMirror = (deps) => {
5265
5270
  // 已在跑的管家不动 (换模型会让缓存整份重读); 死 pane 重生见 respawnSpec。
5266
5271
  const backendChanged = Boolean(boundPath && effCli && backendForPath(expandHome(boundPath)).name !== effCli);
5267
5272
  const { model: effModel, effort: effEffort } = newStewardSpec(cfg, target, effCli, opts, backendChanged ? undefined : prev?.effort ?? deps.store.get(target)?.effort);
5268
- if (prev?.tmuxPane) {
5273
+ if (prev?.tmuxPane && !opts?.preservePrevious) {
5269
5274
  // Best-effort kill; ignore errors (pane may already be dead).
5270
5275
  void runTmux(["kill-pane", "-t", prev.tmuxPane]);
5271
5276
  }
5272
- if (prev)
5277
+ if (prev && !opts?.preservePrevious)
5273
5278
  detach(prev, "/new respawn");
5274
5279
  // sid 由这里先定, 出生到 attach 之间挂在 inFlightSids 上 (见那里)。
5275
- const freshSid = randomUUID();
5280
+ const freshSid = opts?.sessionId ?? randomUUID();
5276
5281
  inFlightSids.add(freshSid);
5277
5282
  const r = await spawnTmuxClaude({
5278
5283
  cfg,
5279
5284
  log: log.child({ sub: "new-session", target }),
5280
5285
  sessionId: freshSid,
5286
+ handoffId: opts?.handoffId,
5281
5287
  windowName: windowLabel(target, windowName),
5282
5288
  cwdOverride: eff,
5289
+ chatKey: target,
5283
5290
  cli: effCli,
5284
5291
  model: effModel,
5285
5292
  effort: effEffort,
@@ -5433,6 +5440,7 @@ export const startMirror = (deps) => {
5433
5440
  forkSession: true,
5434
5441
  windowName: windowLabel(args.target, args.windowName),
5435
5442
  cwdOverride: parent.runningCwd,
5443
+ chatKey: args.target,
5436
5444
  cli: parentCli,
5437
5445
  model,
5438
5446
  effort,
@@ -5550,7 +5558,7 @@ export const startMirror = (deps) => {
5550
5558
  return { runningCwd: chat.running || expandedDefaultCwd, pendingCwd: pending, defaultCwd: expandedDefaultCwd };
5551
5559
  };
5552
5560
  // Write `pendingCwd` to the BASE principal so the switch applies chat-wide —
5553
- // the next /new in any tagged/untagged session picks it up. `set_workspace`
5561
+ // the next /new or self-handoff in any tagged/untagged session picks it up. `set_workspace`
5554
5562
  // from a tagged session still writes to the shared slot, not the tagged
5555
5563
  // session's own record, matching "sessions share the chat's cwd".
5556
5564
  const setPendingCwd = (target, cwd) => {
@@ -5999,8 +6007,339 @@ export const startMirror = (deps) => {
5999
6007
  // One pool for the picker sentinel's pane probes: slow panes do not stall
6000
6008
  // other panes, and scans on the same pane never overlap.
6001
6009
  const maintenance = createKeyedScheduler(4);
6010
+ let hookReviewStopping = false;
6011
+ const hookReviews = new Map();
6012
+ const hookReviewBySession = new Map();
6013
+ const hookCardFailures = new Map();
6014
+ const hookDetails = (hooks) => {
6015
+ const allEnabled = hooks.every((hook) => hook.enabled);
6016
+ const items = hooks.map((hook, index) => [
6017
+ `${index + 1}. Codex hook`,
6018
+ `source: ${hook.sourcePath}`,
6019
+ `event: ${hook.eventName}`,
6020
+ `matcher: ${hook.matcher}`,
6021
+ `key: ${hook.key}`,
6022
+ `enabled: ${hook.enabled}`,
6023
+ `trust: ${hook.trustStatus}`,
6024
+ `hash: ${hook.currentHash}`,
6025
+ `command: ${hook.command}`,
6026
+ ].join("\n")).join("\n\n");
6027
+ return `Codex 待审 hooks 清单(${allEnabled ? "以下 hooks 均已启用" : "逐项审查"}):\n\n${items}`;
6028
+ };
6029
+ const renderHookReviewCard = (id, hooks, status = "选择操作") => ({
6030
+ card_type: "vote_interaction",
6031
+ source: { desc: "Codex hook 信任审查" },
6032
+ main_title: { title: `${hooks.length} 个 Codex hooks 需要审查` },
6033
+ task_id: id,
6034
+ checkbox: { question_key: "action", mode: 0, option_list: [
6035
+ { id: "review", text: "查看 hooks" },
6036
+ { id: "trust", text: "精确授信并继续" },
6037
+ { id: "skip", text: "不授信并继续" },
6038
+ ] },
6039
+ submit_button: { text: status, key: `codex-hook-review:${id}:submit` },
6040
+ });
6041
+ const renderHookReviewProgress = (id, status) => ({
6042
+ card_type: "vote_interaction", source: { desc: "Codex hook 信任审查" },
6043
+ main_title: { title: status }, task_id: id,
6044
+ checkbox: { question_key: "status", mode: 0, option_list: [{ id: "pending", text: "请稍候" }] },
6045
+ submit_button: { text: "处理中…", key: `codex-hook-review:${id}:pending` },
6046
+ });
6047
+ const sendHookDetails = async (review) => {
6048
+ const content = hookDetails(review.hooks);
6049
+ const chatId = replyChatId(review.a);
6050
+ const chunks = splitMarkdown(withLinkedTag(review.a, content), Math.max(200, cfg.wrc.mirror.chunkBytes - TAG_HEADER_BUDGET));
6051
+ for (const chunk of chunks) {
6052
+ if (!review.valid())
6053
+ return;
6054
+ await client.sendMessage(chatId, { msgtype: "markdown", markdown: { content: chunk } });
6055
+ }
6056
+ };
6057
+ const sendHookResult = async (review, text) => {
6058
+ for (let attempt = 0; attempt <= 5; attempt++) {
6059
+ if (!review.canNotify())
6060
+ return false;
6061
+ try {
6062
+ await client.sendMessage(replyChatId(review.a), { msgtype: "markdown", markdown: { content: withLinkedTag(review.a, text) } });
6063
+ return true;
6064
+ }
6065
+ catch (error) {
6066
+ log.warn({ err: errText(error), id: review.id, attempt }, "Codex hook result delivery failed; retrying");
6067
+ if (attempt < 5)
6068
+ await sleep(Math.min(60_000, 2_000 * 2 ** attempt));
6069
+ }
6070
+ }
6071
+ if (review.canNotify() && review.frame) {
6072
+ try {
6073
+ await client.updateTemplateCard(review.frame, renderHookReviewProgress(review.id, "结果消息发送失败,请查看本机 CLI"));
6074
+ }
6075
+ catch (fallbackError) {
6076
+ log.error({ err: errText(fallbackError), id: review.id }, "Codex hook result and fallback card delivery failed");
6077
+ }
6078
+ }
6079
+ return false;
6080
+ };
6081
+ const codexPid = async (pane) => {
6082
+ const root = await panePidOf(pane);
6083
+ const ps = await psSnap();
6084
+ const pids = new Set([...ps.commands].filter(([, command]) => basename(command) === "codex").map(([pid]) => pid));
6085
+ return root ? registeredPidUnder(root, pids, ps.kids) : undefined;
6086
+ };
6087
+ const chooseCodexHookOption = async (review, v, index, live) => {
6088
+ if (!isCodexHookReviewPane(v.screen) || modalFingerprint(v.screen) !== review.fingerprint)
6089
+ return false;
6090
+ const options = parseModalOptions(v.screen);
6091
+ const target = options.find((option) => option.index === index);
6092
+ if ((index === 2 && target?.label !== "Trust all and continue")
6093
+ || (index === 3 && !/^Continue without trusting\b/u.test(target?.label ?? "")))
6094
+ return false;
6095
+ let selected = options.find((option) => option.selected)?.index;
6096
+ if (!target || selected === undefined)
6097
+ return false;
6098
+ for (let n = 0; selected !== index && n < options.length; n++) {
6099
+ if (!(await live()))
6100
+ return false;
6101
+ await runTmux(["send-keys", "-t", review.pane, selected < index ? "Down" : "Up"]);
6102
+ await sleep(MODAL_ARROW_SETTLE_MS);
6103
+ const next = await detectModalPicker(review.pane);
6104
+ if (!(await live()) || !isCodexHookReviewPane(next.screen) || modalFingerprint(next.screen) !== review.fingerprint)
6105
+ return false;
6106
+ selected = parseModalOptions(next.screen).find((option) => option.selected)?.index;
6107
+ if (selected === undefined)
6108
+ return false;
6109
+ }
6110
+ const current = await detectModalPicker(review.pane);
6111
+ if (!(await live()) || !isCodexHookReviewPane(current.screen) || modalFingerprint(current.screen) !== review.fingerprint
6112
+ || parseModalOptions(current.screen).find((option) => option.selected)?.index !== index)
6113
+ return false;
6114
+ if (!(await runTmux(["send-keys", "-t", review.pane, "Enter"])).ok)
6115
+ return false;
6116
+ for (let end = Date.now() + 3000; Date.now() < end; await sleep(100)) {
6117
+ const after = await detectModalPicker(review.pane);
6118
+ if (!(await live()))
6119
+ return false;
6120
+ if (!isCodexHookReviewPane(after.screen))
6121
+ return Boolean(after.screen.trim());
6122
+ }
6123
+ return false;
6124
+ };
6125
+ client.on("event.template_card_event", async (frame) => {
6126
+ const ev = frame.body?.event;
6127
+ const key = ev?.template_card_event?.event_key ?? ev?.event_key ?? "";
6128
+ const match = /^codex-hook-review:([^:]+):submit$/u.exec(key);
6129
+ const review = match ? hookReviews.get(match[1]) : undefined;
6130
+ if (!review || !review.valid())
6131
+ return;
6132
+ const selected = ev?.template_card_event?.selected_items;
6133
+ const first = Array.isArray(selected) ? selected[0] : selected?.selected_item?.[0];
6134
+ const optionIds = first?.option_ids;
6135
+ const action = (Array.isArray(optionIds) ? optionIds : optionIds?.option_id ?? [])[0];
6136
+ if (action === "review") {
6137
+ try {
6138
+ await client.updateTemplateCard(frame, renderHookReviewCard(review.id, review.hooks));
6139
+ }
6140
+ catch (error) {
6141
+ log.warn({ err: errText(error), id: review.id }, "Codex hook review card reset failed");
6142
+ }
6143
+ try {
6144
+ await sendHookDetails(review);
6145
+ }
6146
+ catch (error) {
6147
+ log.warn({ err: errText(error), pane: review.pane }, "Codex hook detail delivery failed");
6148
+ await sendHookResult(review, "完整 hook 清单发送失败;请稍后重试查看,未执行任何授权。");
6149
+ }
6150
+ return;
6151
+ }
6152
+ if (action !== "trust" && action !== "skip")
6153
+ return;
6154
+ if (review.busy)
6155
+ return;
6156
+ review.busy = true;
6157
+ review.frame = frame;
6158
+ try {
6159
+ await client.updateTemplateCard(frame, renderHookReviewProgress(review.id, "正在处理 Codex hooks"));
6160
+ }
6161
+ catch (error) {
6162
+ log.warn({ err: errText(error), id: review.id }, "Codex hook processing card update failed");
6163
+ }
6164
+ if (!review.valid()) {
6165
+ review.busy = false;
6166
+ return;
6167
+ }
6168
+ let status = "授权未完成;确认卡已失效";
6169
+ let terminal = false;
6170
+ try {
6171
+ const result = await withPaneInput(review.pane, async (live) => {
6172
+ const valid = async () => {
6173
+ if (!review.valid() || !live() || await panePidOf(review.pane) !== review.rootPid)
6174
+ return false;
6175
+ const currentSession = codexSessionForPane(review.pane, cfg.daemon.stateDir)?.sessionId;
6176
+ if (currentSession && currentSession !== review.sid)
6177
+ return false;
6178
+ return await codexPid(review.pane) === review.pid;
6179
+ };
6180
+ if (!(await valid()))
6181
+ return "pane 身份已变化,未执行操作";
6182
+ let before = await detectModalPicker(review.pane);
6183
+ if (!isCodexHookReviewPane(before.screen) || modalFingerprint(before.screen) !== review.fingerprint)
6184
+ return "弹窗已变化或已由本地处理,未执行操作";
6185
+ const backend = backendForPath(review.a.jsonlPath);
6186
+ const homeDir = expandHome(backend.homeDir);
6187
+ const current = await inspectCodexHooks(backend.bin, review.a.runningCwd, [], homeDir);
6188
+ if (!(await valid()))
6189
+ return "daemon 已停止或 pane 身份改变;未执行操作";
6190
+ const currentByKey = new Map(current.map((hook) => [hook.key, hook]));
6191
+ if (review.hooks.some((hook) => {
6192
+ const now = currentByKey.get(hook.key);
6193
+ return !now || !now.enabled || now.sourcePath !== hook.sourcePath || now.currentHash !== hook.currentHash
6194
+ || now.eventName !== hook.eventName || now.command !== hook.command || now.matcher !== hook.matcher;
6195
+ }))
6196
+ return "Codex hooks changed since review; 卡片已失效,未继续";
6197
+ const pending = current.filter((hook) => hook.enabled && hook.trustStatus !== "trusted");
6198
+ const reviewedKeys = new Set(review.hooks.map((hook) => hook.key));
6199
+ if (pending.some((hook) => !reviewedKeys.has(hook.key)))
6200
+ return "出现未展示的待审 hook;卡片已失效,未继续";
6201
+ // “Trust all” can authorize hooks outside this card. Exact hashes have
6202
+ // been persisted and verified above; continue via the native skip path.
6203
+ const option = 3;
6204
+ if (action === "trust") {
6205
+ if (pending.length) {
6206
+ await trustCodexHookSet(backend.bin, review.a.runningCwd, homeDir, pending.map(({ key, currentHash, sourcePath }) => ({ key, currentHash, sourcePath })), valid);
6207
+ }
6208
+ if (!(await valid()))
6209
+ return "hash 已写入,但 pane 身份改变;请在 CLI 核对继续状态";
6210
+ const verified = await inspectCodexHooks(backend.bin, review.a.runningCwd, [], homeDir);
6211
+ if (!(await valid()))
6212
+ return "daemon 已停止或 pane 身份改变;未继续操作";
6213
+ if (review.hooks.some((hook) => {
6214
+ const now = verified.find((item) => item.key === hook.key);
6215
+ return !now || !now.enabled || now.sourcePath !== hook.sourcePath || now.currentHash !== hook.currentHash
6216
+ || now.eventName !== hook.eventName || now.command !== hook.command || now.matcher !== hook.matcher;
6217
+ }) || verified.some((hook) => hook.enabled && hook.trustStatus !== "trusted"
6218
+ && !review.hooks.some((item) => item.key === hook.key))) {
6219
+ return "hash 验证后 hook 集发生变化;弹窗已失效,未继续";
6220
+ }
6221
+ const afterTrust = await detectModalPicker(review.pane);
6222
+ if (!afterTrust.modal)
6223
+ return "审查清单中的 hook 已精确授信;弹窗已消失,未代为继续";
6224
+ if (!isCodexHookReviewPane(afterTrust.screen) || modalFingerprint(afterTrust.screen) !== review.fingerprint) {
6225
+ return "hash 已验证,但弹窗已变化;请在 CLI 核对继续状态";
6226
+ }
6227
+ before = afterTrust;
6228
+ }
6229
+ const liveGuard = valid;
6230
+ const pressed = await chooseCodexHookOption(review, before, option, liveGuard);
6231
+ if (!pressed)
6232
+ return action === "trust"
6233
+ ? "hash 已按审查清单写入并验证;CLI 确认未完成,请在本地继续"
6234
+ : "未信任任何 hook;CLI 确认未完成,请在本地继续";
6235
+ return action === "trust"
6236
+ ? "审查清单中的 hook 已精确授信;本次启动选择了不信任继续,hooks 本次不会运行"
6237
+ : "未信任 hook,Codex 已继续;hooks 本次不会运行";
6238
+ }, { guard: review.valid });
6239
+ status = result;
6240
+ terminal = /Codex 已继续|本次启动选择了不信任继续/u.test(result);
6241
+ }
6242
+ catch (error) {
6243
+ status = `授权未完成:${errText(error)}`;
6244
+ log.warn({ err: errText(error), pane: review.pane }, "Codex hook trust action failed");
6245
+ }
6246
+ review.resultPending = true;
6247
+ await sendHookResult(review, status);
6248
+ review.resultPending = false;
6249
+ review.busy = false;
6250
+ if (terminal || /弹窗已变化|pane 身份已变化|卡片已失效|未展示的待审 hook|hook 集发生变化/u.test(status)) {
6251
+ review.active = false;
6252
+ hookReviews.delete(review.id);
6253
+ hookReviewBySession.delete(review.sid);
6254
+ review.valid = () => false;
6255
+ }
6256
+ });
6002
6257
  const maintenanceValid = (a, pane, sid, gen, signal) => !signal.aborted && byTarget.get(a.target) === a && a.tmuxPane === pane && a.sessionId === sid
6003
6258
  && (a.injectGen ?? 0) === gen && !a.migrationWatcher;
6259
+ const codexHookReviewOne = async (a, pane, sid, gen, signal) => {
6260
+ const v = await detectModalPicker(pane);
6261
+ if (!isCodexHookReviewPane(v.screen)) {
6262
+ const stale = hookReviewBySession.get(sid);
6263
+ if (stale) {
6264
+ const previous = hookReviews.get(stale);
6265
+ if (previous?.busy || previous?.resultPending)
6266
+ return;
6267
+ if (previous)
6268
+ previous.active = false;
6269
+ hookReviewBySession.delete(sid);
6270
+ hookReviews.delete(stale);
6271
+ }
6272
+ a.pickerSentinelFp = undefined;
6273
+ return;
6274
+ }
6275
+ if (hookReviewBySession.has(sid))
6276
+ return;
6277
+ const fingerprint = modalFingerprint(v.screen);
6278
+ const failure = hookCardFailures.get(sid);
6279
+ if (failure?.fingerprint === fingerprint && Date.now() < failure.retryAt)
6280
+ return;
6281
+ if (failure && failure.fingerprint !== fingerprint)
6282
+ hookCardFailures.delete(sid);
6283
+ const rootPid = await panePidOf(pane);
6284
+ const pid = await codexPid(pane);
6285
+ const currentSession = codexSessionForPane(pane, cfg.daemon.stateDir)?.sessionId;
6286
+ if (!rootPid || !pid || (currentSession && currentSession !== sid)
6287
+ || byTarget.get(a.target) !== a || a.tmuxPane !== pane || a.sessionId !== sid || (a.injectGen ?? 0) !== gen)
6288
+ return;
6289
+ const backend = backendForPath(a.jsonlPath);
6290
+ let hooks;
6291
+ try {
6292
+ hooks = await inspectCodexHooks(backend.bin, a.runningCwd, [], expandHome(backend.homeDir));
6293
+ }
6294
+ catch (error) {
6295
+ log.warn({ err: errText(error), target: a.target }, "Codex hook review enumeration failed");
6296
+ return;
6297
+ }
6298
+ const pending = hooks.filter((hook) => hook.enabled && hook.trustStatus !== "trusted");
6299
+ const summary = /(?:^|\n)\s*(\d+)\s+hooks?\s+(?:is|are)\s+new or changed\./iu.exec(v.screen);
6300
+ if (!summary || Number(summary[1]) !== pending.length || !pending.length || pending.some((hook) => !hook.key || !hook.eventName || !hook.sourcePath
6301
+ || !hook.currentHash || !/^sha256:[0-9a-f]{64}$/iu.test(hook.currentHash) || !hook.command)) {
6302
+ log.info({ target: a.target, screenCount: summary?.[1], count: pending.length }, "Codex hook review not forwarded: incomplete or empty review set");
6303
+ return;
6304
+ }
6305
+ const id = randomUUID();
6306
+ const review = {
6307
+ id, a, pane, sid, gen, pid, rootPid, fingerprint, screen: v.screen,
6308
+ hooks: pending, busy: false, active: true, signal,
6309
+ valid: () => review.active && !hookReviewStopping && !maintenance.signal.aborted && !signal.aborted
6310
+ && byTarget.get(a.target) === a && a.tmuxPane === pane && a.sessionId === sid
6311
+ && (a.injectGen ?? 0) === gen && !a.migrationWatcher,
6312
+ canNotify: () => !hookReviewStopping && !maintenance.signal.aborted && !signal.aborted,
6313
+ };
6314
+ try {
6315
+ const chatId = replyChatId(a);
6316
+ const chunks = splitMarkdown(withLinkedTag(a, hookDetails(pending)), Math.max(200, cfg.wrc.mirror.chunkBytes - TAG_HEADER_BUDGET));
6317
+ for (const content of chunks) {
6318
+ if (!review.valid())
6319
+ return;
6320
+ await client.sendMessage(chatId, { msgtype: "markdown", markdown: { content } });
6321
+ }
6322
+ if (!review.valid())
6323
+ return;
6324
+ hookReviews.set(id, review);
6325
+ hookReviewBySession.set(sid, id);
6326
+ await client.sendMessage(chatId, { msgtype: "template_card", template_card: renderHookReviewCard(id, pending) });
6327
+ hookCardFailures.delete(sid);
6328
+ a.pickerSentinelFp = v.screen;
6329
+ log.info({ target: a.target, sessionId: sid, id, count: pending.length }, "Codex hook review card sent");
6330
+ }
6331
+ catch (error) {
6332
+ review.active = false;
6333
+ hookReviews.delete(id);
6334
+ hookReviewBySession.delete(sid);
6335
+ const previous = hookCardFailures.get(sid);
6336
+ const attempts = previous?.fingerprint === fingerprint ? previous.attempts + 1 : 1;
6337
+ const retryMs = Math.min(5 * 60_000, 5_000 * 2 ** (attempts - 1));
6338
+ hookCardFailures.set(sid, { fingerprint, attempts, retryAt: Date.now() + retryMs });
6339
+ a.pickerSentinelFp = v.screen;
6340
+ log.warn({ err: errText(error), target: a.target, attempts, retryMs }, "Codex hook review card send failed; retry backed off");
6341
+ }
6342
+ };
6004
6343
  // ── 原生权限 picker 哨兵 ──────────────────────────────────────────────
6005
6344
  // CodeBuddy 对一部分调用先弹自家权限 picker、PreToolUse hook 在人点掉之后才
6006
6345
  // 触发 / 根本不触发 (与 AskUserQuestion 的「本地面板先行」同源; 实测命中: 子代理
@@ -6013,7 +6352,7 @@ export const startMirror = (deps) => {
6013
6352
  // 对应选项; 本地先按掉则 moot 作废卡。代按/发卡都发 chat 回执留痕。
6014
6353
  // WEZARD_PICKER_SENTINEL=0 整体关闭。
6015
6354
  const pickerOne = async (a, pane, sid, gen, signal) => {
6016
- const guard = () => maintenanceValid(a, pane, sid, gen, signal) && cfg.approval.enabled
6355
+ const guard = () => maintenanceValid(a, pane, sid, gen, signal) && (cliOf(a) === "codex" || cfg.approval.enabled)
6017
6356
  && process.env.WEZARD_PICKER_SENTINEL !== "0";
6018
6357
  if (!guard())
6019
6358
  return;
@@ -6021,12 +6360,14 @@ export const startMirror = (deps) => {
6021
6360
  const valid = () => guard() && live();
6022
6361
  if (!a.tmuxPane || a.migrationWatcher)
6023
6362
  return;
6024
- // Codex PermissionRequest has its own independent native gate. Screen
6025
- // options, tool windows and skipAll never authorize its sandbox.
6026
- if (cliOf(a) === "codex")
6027
- return;
6028
6363
  if (!(await tmuxPaneAlive(pane)) || !valid())
6029
6364
  return;
6365
+ // Hook trust is a distinct startup gate: enumerate and display its exact
6366
+ // hash set; ordinary tool approval rules have no authority over it.
6367
+ if (cliOf(a) === "codex") {
6368
+ await codexHookReviewOne(a, pane, sid, gen, signal);
6369
+ return;
6370
+ }
6030
6371
  const v = await detectModalPicker(pane);
6031
6372
  if (!valid())
6032
6373
  return;
@@ -6053,7 +6394,9 @@ export const startMirror = (deps) => {
6053
6394
  a.pickerSentinelFp = v.screen;
6054
6395
  const pick = pickAutoAllowAnswer(parseModalOptions(v.screen));
6055
6396
  if (!pick) {
6056
- log.info({ target: a.target, title: v.title }, "picker sentinel: modal on pane but not a trustworthy permission picker — leaving it");
6397
+ // tail 与上面「未判成 modal」分支同款: 远端 (devcloud) 选项文案变体排查靠它,
6398
+ // 不必再守着屏抓 capture。
6399
+ log.info({ target: a.target, title: v.title, tail: v.screen.split("\n").slice(-8).join("\\n").slice(-600) }, "picker sentinel: modal on pane but not a trustworthy permission picker — leaving it");
6057
6400
  return;
6058
6401
  }
6059
6402
  const ctx = parseConfirmContext(v.screen);
@@ -6123,10 +6466,10 @@ export const startMirror = (deps) => {
6123
6466
  }, { guard });
6124
6467
  };
6125
6468
  const pickerTick = () => {
6126
- if (!cfg.approval.enabled || process.env.WEZARD_PICKER_SENTINEL === "0")
6469
+ if (process.env.WEZARD_PICKER_SENTINEL === "0")
6127
6470
  return;
6128
6471
  for (const a of byTarget.values()) {
6129
- if (!a.tmuxPane || cliOf(a) === "codex")
6472
+ if (!a.tmuxPane || (cliOf(a) !== "codex" && !cfg.approval.enabled))
6130
6473
  continue;
6131
6474
  const pane = a.tmuxPane, sid = a.sessionId, gen = a.injectGen ?? 0;
6132
6475
  void maintenance.schedule(`picker:${a.target}`, pane, (signal) => pickerOne(a, pane, sid, gen, signal))
@@ -6240,14 +6583,17 @@ export const startMirror = (deps) => {
6240
6583
  if (!a || !clear.nextSid || !clear.panePid || a.tmuxPane !== clear.pane || a.sessionId !== clear.nextSid || await panePidOf(clear.pane) !== clear.panePid)
6241
6584
  return false;
6242
6585
  const backend = backendForPath(a.jsonlPath);
6243
- if (backend.name === "claude") {
6586
+ if (backend.name === "claude" || backend.name === "claude-internal") {
6244
6587
  const actual = sessionOnPane(backend.homeDir, clear.pane);
6245
6588
  return actual?.pid === clear.pid && actual.sessionId === clear.nextSid;
6246
6589
  }
6247
- if (backend.name !== "codex" || codexSessionForPane(clear.pane)?.sessionId !== clear.nextSid)
6590
+ if (backend.name === "codex" && codexSessionForPane(clear.pane)?.sessionId !== clear.nextSid)
6248
6591
  return false;
6249
6592
  const ps = await psSnap();
6250
- const pids = new Set([...ps.commands].filter(([, command]) => basename(command) === "codex").map(([pid]) => pid));
6593
+ if (backend.name === "codebuddy")
6594
+ return registeredPidUnder(clear.panePid, liveSessionPids(backend.homeDir), ps.kids) === clear.pid;
6595
+ const executable = backend.name === "codex" ? "codex" : basename(backend.bin);
6596
+ const pids = new Set([...ps.commands].filter(([, command]) => basename(command) === executable).map(([pid]) => pid));
6251
6597
  return registeredPidUnder(clear.panePid, pids, ps.kids) === clear.pid;
6252
6598
  };
6253
6599
  const verifyClearInput = async (target, clear, phase, allowed) => {
@@ -6269,28 +6615,162 @@ export const startMirror = (deps) => {
6269
6615
  if (!a?.tmuxPane)
6270
6616
  return { ok: false, reason: "handoff requires the original live pane; no respawn" };
6271
6617
  const backend = backendForPath(a.jsonlPath);
6272
- // 只开放本机真实探针验证过的后端; 不能因家族相近就假定 slash/注册表语义相同。
6273
- if (!["claude", "codex"].includes(backend.name))
6274
- return { ok: false, reason: `${backend.name} native /clear completion is not verified; pane unchanged` };
6275
- if (a.pendingCwd && a.pendingCwd !== a.runningCwd)
6276
- return { ok: false, reason: "pending workspace switch requires an explicit /new; /clear keeps the original process cwd" };
6277
6618
  const pane = a.tmuxPane;
6278
6619
  const valid = () => guard() && byTarget.get(target) === a && a.tmuxPane === pane;
6279
6620
  try {
6280
6621
  return await withPaneInput(pane, async (live) => {
6281
6622
  const codex = backend.name === "codex";
6282
6623
  const nativePid = async () => {
6283
- if (!codex)
6284
- return sessionOnPane(backend.homeDir, pane)?.pid;
6285
6624
  const root = await panePidOf(pane);
6625
+ if (!root)
6626
+ return undefined;
6627
+ if (backend.name === "claude" || backend.name === "claude-internal")
6628
+ return sessionOnPane(backend.homeDir, pane)?.pid;
6286
6629
  const ps = await psSnap();
6287
- return registeredPidUnder(root, new Set([...ps.commands].filter(([, command]) => basename(command) === "codex").map(([pid]) => pid)), ps.kids);
6630
+ if (backend.name === "codebuddy")
6631
+ return registeredPidUnder(root, liveSessionPids(backend.homeDir), ps.kids);
6632
+ const executable = codex ? "codex" : basename(backend.bin);
6633
+ return registeredPidUnder(root, new Set([...ps.commands].filter(([, command]) => basename(command) === executable).map(([pid]) => pid)), ps.kids);
6288
6634
  };
6289
6635
  const pid = await nativePid();
6290
6636
  const panePid = await panePidOf(pane);
6291
6637
  if (!pid || !panePid || !(await tmuxPaneAlive(pane)))
6292
6638
  return { ok: false, reason: "original CLI process identity is unavailable" };
6293
6639
  const original = sessionOnPane(backend.homeDir, pane);
6640
+ const queuedCwd = chatCwdFallback(target).pending || a.pendingCwd;
6641
+ const pendingCwd = queuedCwd || attempt?.workspaceCwd || "";
6642
+ const workspaceStillNeedsHandoff = pendingCwd && (expandHome(pendingCwd) !== expandHome(a.runningCwd) || (!!attempt && a.sessionId !== attempt.sid));
6643
+ if (workspaceStillNeedsHandoff) {
6644
+ const prior = attempt ?? { pane, pid, panePid, sid: a.sessionId, at: Date.now(), workspaceCwd: pendingCwd };
6645
+ const actualCwd = (binding) => expandHome(binding.runningCwd.trim());
6646
+ const processEvidence = async (binding) => {
6647
+ if (!binding.tmuxPane || !binding.sessionId || actualCwd(binding) !== expandHome(pendingCwd))
6648
+ return undefined;
6649
+ const nextPanePid = await panePidOf(binding.tmuxPane);
6650
+ if (!nextPanePid)
6651
+ return undefined;
6652
+ const nextBackend = backendForPath(binding.jsonlPath);
6653
+ let nextPid;
6654
+ if (nextBackend.name === "claude" || nextBackend.name === "claude-internal") {
6655
+ const session = sessionOnPane(nextBackend.homeDir, binding.tmuxPane);
6656
+ if (session?.sessionId === binding.sessionId)
6657
+ nextPid = session.pid;
6658
+ }
6659
+ if (nextBackend.name !== "claude" && nextBackend.name !== "claude-internal") {
6660
+ const ps = await psSnap();
6661
+ const executable = nextBackend.name === "codex" ? "codex" : basename(nextBackend.bin);
6662
+ const processIds = nextBackend.name === "codebuddy"
6663
+ ? liveSessionPids(nextBackend.homeDir)
6664
+ : new Set([...ps.commands].filter(([, command]) => basename(command) === executable).map(([childPid]) => childPid));
6665
+ nextPid = registeredPidUnder(nextPanePid, processIds, ps.kids);
6666
+ if (nextBackend.name === "codex" && codexSessionForPane(binding.tmuxPane)?.sessionId !== binding.sessionId)
6667
+ nextPid = undefined;
6668
+ }
6669
+ return nextPid ? { ...prior, pane: binding.tmuxPane, pid: nextPid, panePid: nextPanePid, nextSid: binding.sessionId } : undefined;
6670
+ };
6671
+ // A queued workspace switch must replace the CLI process, not clear its
6672
+ // context in place. Persist the old process identity before spawning so
6673
+ // a daemon reload can distinguish an unapplied switch from a completed one.
6674
+ if (attempt?.nextSid) {
6675
+ return await verifyClearContext(target, attempt)
6676
+ ? { ok: true }
6677
+ : { ok: false, reason: "new workspace handoff process/session changed; refusing brief replay" };
6678
+ }
6679
+ const current = byTarget.get(target);
6680
+ if (!current)
6681
+ return { ok: false, reason: "workspace handoff attachment disappeared" };
6682
+ if (current.sessionId !== prior.sid) {
6683
+ const recovered = await processEvidence(current);
6684
+ if (!recovered)
6685
+ return { ok: false, reason: "workspace handoff changed session without a verifiable pending-cwd process" };
6686
+ submitted(recovered);
6687
+ if (prior.pane !== recovered.pane)
6688
+ await runTmux(["kill-pane", "-t", prior.pane]);
6689
+ return { ok: true };
6690
+ }
6691
+ if (current.tmuxPane !== prior.pane || pid !== prior.pid || panePid !== prior.panePid) {
6692
+ return { ok: false, reason: "original pane/CLI process changed before workspace handoff" };
6693
+ }
6694
+ let durable = attempt ?? prior;
6695
+ if (!attempt || !attempt.workspaceCwd || !attempt.spawnSid) {
6696
+ const actualSid = codex ? codexSessionForPane(pane)?.sessionId : original?.sessionId;
6697
+ if ((backend.name === "claude" || backend.name === "claude-internal" || codex) && actualSid !== prior.sid)
6698
+ return { ok: false, reason: "original session changed before workspace handoff" };
6699
+ durable = { ...prior, workspaceCwd: pendingCwd, spawnSid: attempt?.spawnSid ?? prior.spawnSid ?? randomUUID() };
6700
+ submitted(durable);
6701
+ }
6702
+ const spawnSid = durable.spawnSid ?? randomUUID();
6703
+ if (!durable.spawnSid) {
6704
+ durable = { ...durable, spawnSid };
6705
+ submitted(durable);
6706
+ }
6707
+ if (!live() || !valid() || !guard())
6708
+ return { ok: false, reason: "workspace handoff permission withdrawn before respawn" };
6709
+ // A daemon may have died after tmux launched the stable session but
6710
+ // before attach() persisted it. Recover that pane by its durable SID.
6711
+ const backendForSpawn = resolveCliBackend(cfg.wrc);
6712
+ const orphan = backendForSpawn.name === "claude" || backendForSpawn.name === "claude-internal"
6713
+ ? readRegistry(backendForSpawn.homeDir).find((s) => s.sessionId === spawnSid && s.pane && s.pid > 0)
6714
+ : undefined;
6715
+ const codexOrphan = backendForSpawn.name === "codex" ? await (async () => {
6716
+ const panes = await runTmux(["list-panes", "-a", "-F", "#{pane_id}"]);
6717
+ if (!panes.ok)
6718
+ return undefined;
6719
+ for (const candidate of panes.stdout.split("\n").map((s) => s.trim()).filter(Boolean)) {
6720
+ const [tag, session] = await Promise.all([
6721
+ runTmux(["show-options", "-p", "-t", candidate, "-v", "@wezard_handoff_id"]),
6722
+ Promise.resolve(codexSessionForPane(candidate)),
6723
+ ]);
6724
+ if (tag.ok && tag.stdout.trim() === spawnSid && session?.sessionId)
6725
+ return session;
6726
+ }
6727
+ return undefined;
6728
+ })() : undefined;
6729
+ const recovery = orphan ? { pane: orphan.pane, sessionId: orphan.sessionId,
6730
+ jsonlPath: join(projectDirFor(a.jsonlPath, expandHome(pendingCwd)), `${orphan.sessionId}.jsonl`) } : codexOrphan;
6731
+ let launchedCwd = "";
6732
+ if (recovery && await tmuxPaneAlive(recovery.pane)) {
6733
+ const session = await runTmux(["display-message", "-p", "-t", recovery.pane, "#{session_name}"]);
6734
+ const attached = attach({ sessionId: recovery.sessionId, jsonlPath: recovery.jsonlPath, target, tmuxPane: recovery.pane,
6735
+ tmuxSession: session.ok ? session.stdout.trim() : "", cwd: pendingCwd, model: "", effort: "", pendingCwd: "" });
6736
+ if (!attached.ok)
6737
+ return { ok: false, reason: `recovered workspace pane could not bind: ${attached.reason}` };
6738
+ launchedCwd = pendingCwd;
6739
+ }
6740
+ else {
6741
+ let spawned;
6742
+ for (let retry = 0; retry < 3; retry++) {
6743
+ spawned = await newSession(target, displayName(target) || target, undefined, {
6744
+ cwd: pendingCwd, guard, preservePrevious: true, sessionId: spawnSid, handoffId: spawnSid,
6745
+ });
6746
+ if (spawned.ok || !guard())
6747
+ break;
6748
+ if (retry < 2)
6749
+ await sleep(500 * (retry + 1));
6750
+ }
6751
+ if (!spawned?.ok)
6752
+ return { ok: false, reason: `new workspace CLI failed to start: ${spawned?.reason ?? "unknown"}` };
6753
+ launchedCwd = spawned.cwd ?? "";
6754
+ }
6755
+ const next = byTarget.get(target);
6756
+ const evidence = next && launchedCwd && expandHome(launchedCwd) === expandHome(pendingCwd)
6757
+ ? await processEvidence(next)
6758
+ : undefined;
6759
+ if (!evidence)
6760
+ return { ok: false, reason: "new CLI did not confirm the requested workspace and session" };
6761
+ submitted(evidence);
6762
+ if (prior.pane !== evidence.pane) {
6763
+ // attach() replaced the target binding; kill the former pane only
6764
+ // after the replacement process and binding have both been verified.
6765
+ await runTmux(["kill-pane", "-t", prior.pane]);
6766
+ }
6767
+ log.info({ target, oldSessionId: prior.sid, sessionId: evidence.nextSid, cwd: launchedCwd }, "handoff: pending workspace applied in fresh CLI process");
6768
+ return { ok: true };
6769
+ }
6770
+ // Native /clear is separately restricted to backends with verified
6771
+ // completion; pending workspace switches use fresh-process evidence above.
6772
+ if (!["claude", "codex"].includes(backend.name))
6773
+ return { ok: false, reason: `${backend.name} native /clear completion is not verified; pane unchanged` };
6294
6774
  let transaction = attempt ?? { pane, pid, panePid, sid: a.sessionId, at: Date.now() };
6295
6775
  if (transaction.pane !== pane || transaction.pid !== pid || (transaction.panePid && transaction.panePid !== panePid))
6296
6776
  return { ok: false, reason: "original pane/CLI process changed; refusing /clear" };
@@ -6633,9 +7113,9 @@ export const startMirror = (deps) => {
6633
7113
  // Same resume-fork hazard as dispatch: snapshot before spawn, re-bind
6634
7114
  // onto the forked jsonl once it appears (EOF offset — fork is seeded).
6635
7115
  const resumeBaseline = listJsonls(dirname(a.jsonlPath));
6636
- const r = await spawnTmuxClaude({ cfg, log: log.child({ sub: "respawn-init", sessionId: sid }), resumeSessionId: sid, windowName: displayName(target) || target, cwdOverride: a.runningCwd, cli: backendForPath(a.jsonlPath).name, ...respawnSpec(a), systemPrompt: charterFor(target, { cwd: a.runningCwd, cli: backendForPath(a.jsonlPath).name }) });
7116
+ const r = await spawnTmuxClaude({ cfg, log: log.child({ sub: "respawn-init", sessionId: sid }), resumeSessionId: sid, windowName: displayName(target) || target, cwdOverride: a.runningCwd, chatKey: target, cli: backendForPath(a.jsonlPath).name, ...respawnSpec(a), systemPrompt: charterFor(target, { cwd: a.runningCwd, cli: backendForPath(a.jsonlPath).name }) });
6637
7117
  if (!r.ok || !r.tmuxPane)
6638
- return { ok: false, retryable: true, reason: `respawn failed: ${r.reason ?? "unknown"}` };
7118
+ return { ok: false, retryable: r.retryable !== false, reason: `respawn failed: ${r.reason ?? "unknown"}` };
6639
7119
  if (!permitted() || a.tmuxPane !== probedPane) {
6640
7120
  // This pane was born for an unsubmitted injection. Never kill the old
6641
7121
  // executor or bind the withdrawn birth. A failed cleanup is explicitly
@@ -6702,6 +7182,8 @@ export const startMirror = (deps) => {
6702
7182
  interruptPane: async (target, opts) => {
6703
7183
  if (opts?.guard && !opts.guard())
6704
7184
  return { ok: false, reason: "interrupt authority changed" };
7185
+ if (opts?.teardown)
7186
+ deps.events?.cancel((e) => e.target === target);
6705
7187
  const a = byTarget.get(target);
6706
7188
  if (!a)
6707
7189
  return { ok: false, reason: "no mirror attached for target" };
@@ -7020,9 +7502,15 @@ export const startMirror = (deps) => {
7020
7502
  onSpawn,
7021
7503
  onContextCut,
7022
7504
  shutdown: () => {
7505
+ hookReviewStopping = true;
7023
7506
  clearInterval(paneDriftTimer);
7024
7507
  clearInterval(pickerTimer);
7025
7508
  maintenance.stop();
7509
+ for (const review of hookReviews.values())
7510
+ review.active = false;
7511
+ hookReviews.clear();
7512
+ hookReviewBySession.clear();
7513
+ hookCardFailures.clear();
7026
7514
  for (const a of bySessionId.values()) {
7027
7515
  if (a.outbound?.kind === "deferred")
7028
7516
  clearTimeout(a.outbound.timer);
@@ -7242,7 +7730,14 @@ export const startMirror = (deps) => {
7242
7730
  const resumeBaseline = !armMigration ? listJsonls(dirname(a.jsonlPath)) : undefined;
7243
7731
  // Respawn in the binding's runningCwd (pendingCwd doesn't apply to a
7244
7732
  // mid-turn reincarnation — only /new and /clear-with-pending swap cwd).
7245
- const r = await spawnTmuxClaude({ cfg, log: log.child({ sub: "respawn", sessionId: sid }), resumeSessionId: sid, windowName: displayName(a.target) || a.target, cwdOverride: a.runningCwd, cli: backendForPath(a.jsonlPath).name, ...respawnSpec(a), systemPrompt: charterFor(a.target, { cwd: a.runningCwd, cli: backendForPath(a.jsonlPath).name }) });
7733
+ const r = await spawnTmuxClaude({ cfg, log: log.child({ sub: "respawn", sessionId: sid }), resumeSessionId: sid, windowName: displayName(a.target) || a.target, cwdOverride: a.runningCwd, chatKey: a.target, cli: backendForPath(a.jsonlPath).name, ...respawnSpec(a), systemPrompt: charterFor(a.target, { cwd: a.runningCwd, cli: backendForPath(a.jsonlPath).name }) });
7734
+ if (byTarget.get(a.target) !== a || a.sessionId !== sid || (a.injectGen ?? 0) !== myGen || (guard && !guard())) {
7735
+ // A stop or replacement during startup revokes this birth before binding.
7736
+ if (r.tmuxPane)
7737
+ await runTmux(["kill-pane", "-t", r.tmuxPane]);
7738
+ onSubmitted?.({ ok: false, retryable: false, reason: "respawn permission withdrawn; binding withheld" });
7739
+ return;
7740
+ }
7246
7741
  if (r.ok && r.tmuxPane && r.tmuxSession) {
7247
7742
  a.tmuxPane = r.tmuxPane;
7248
7743
  a.tmuxSession = r.tmuxSession;
@@ -7275,7 +7770,7 @@ export const startMirror = (deps) => {
7275
7770
  // store still reflects "user wanted tmux" — next turn retries.
7276
7771
  log.error({ reason: r.reason }, "mirror: tmux respawn failed");
7277
7772
  if (eventId) {
7278
- onSubmitted?.({ ok: false, retryable: true, reason: `respawn failed: ${r.reason ?? "unknown"}` });
7773
+ onSubmitted?.({ ok: false, retryable: r.retryable !== false, reason: `respawn failed: ${r.reason ?? "unknown"}` });
7279
7774
  if (s)
7280
7775
  await finalizeStream(a, s);
7281
7776
  if (a.outbound?.kind === "deferred")
@@ -7318,12 +7813,23 @@ export const startMirror = (deps) => {
7318
7813
  // 不许退化成 spawn-mode (`--resume -p`) 的无窗口注入。忙闲交给 CLI 自己的输入队列:
7319
7814
  // 贴进运行中的一轮会被记成 queued 轮, 等它在 transcript 露面再接上这条 event。
7320
7815
  // slash 命令要等闲, 那一道在上面 (dispatch 开头) 已经拦过了。
7321
- const r = await inject({
7816
+ let r = await inject({
7322
7817
  text: effText, images: effImages, cfg, log: log.child({ principal, sessionId: sid }),
7323
7818
  sessionId: sid, eventId, jsonlPath: a.jsonlPath, tmuxTarget: a.tmuxPane, freshSpawn,
7324
7819
  requireIdle: eventId ? () => true : undefined,
7325
7820
  guard: (phase, identity) => byTarget.get(a.target) === a && a.tmuxPane === injectPane && (a.injectGen ?? 0) === myGen && (!guard || guard(phase, identity)),
7326
7821
  });
7822
+ // 注入失败可以迟于转录消费;只认这一笔在原绑定转录里的标记,不用别轮产出猜 ACK。
7823
+ const submissionConfirmed = () => {
7824
+ const event = eventId ? deps.events?.get(eventId) : undefined;
7825
+ return !!event && !event.canceled
7826
+ && (event.exposure === "consumed" || event.execution === "complete"
7827
+ || !!event.transcript && submittedEventSince([{ path: event.transcript, offset: 0 }], event.id, event.at));
7828
+ };
7829
+ if (!r.ok && r.uncertain && submissionConfirmed()) {
7830
+ log.info({ target: a.target, eventId, reason: r.reason }, "mirror inject: late failure superseded by event submission evidence");
7831
+ r = { ok: true };
7832
+ }
7327
7833
  onSubmitted?.(r);
7328
7834
  if (!r.ok) {
7329
7835
  // retryable = 一个字都没进输入框, 消息事件层会稍后重投 —— 不是失败, 别报 ✗
@@ -7336,10 +7842,14 @@ export const startMirror = (deps) => {
7336
7842
  a.outbound = undefined;
7337
7843
  return;
7338
7844
  }
7339
- const note = `[mirror] ✗ ${r.reason ?? "failed"}`;
7845
+ const note = r.uncertain
7846
+ ? "[mirror] ⚠ 暂时无法确认目标会话是否收到消息,已停止继续输入;为避免重复执行,不会自动重发"
7847
+ : `[mirror] ✗ ${r.reason ?? "failed"}`;
7848
+ // 提示也会排发送队列;真正发出前再认一次同事件证据,撤销过期告警。
7849
+ const stillWanted = () => !r.uncertain || !submissionConfirmed();
7340
7850
  if (s) {
7341
7851
  s.acc = s.acc ? `${s.acc}\n\n${note}` : note;
7342
- await finalizeStream(a, s);
7852
+ await finalizeStream(a, s, false, stillWanted);
7343
7853
  }
7344
7854
  else if (armMigration) {
7345
7855
  // /clear path has no live stream — surface failure as a one-shot
@@ -7356,7 +7866,7 @@ export const startMirror = (deps) => {
7356
7866
  if (a.outbound?.kind === "deferred")
7357
7867
  clearTimeout(a.outbound.timer);
7358
7868
  a.outbound = undefined;
7359
- sendStandalone(a, note);
7869
+ sendStandalone(a, note, stillWanted);
7360
7870
  }
7361
7871
  return;
7362
7872
  }