@staix/agent-hub 0.34.1 → 0.36.0

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 (213) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +53 -7
  3. package/docs/adding-an-ai-tool.md +2 -2
  4. package/docs/addons/claude-mem.md +4 -4
  5. package/docs/addons/open-code-review.md +1 -1
  6. package/docs/agent-notes/README.md +66 -0
  7. package/docs/agent-notes/adapters.md +14 -7
  8. package/docs/agent-notes/budget.md +1 -1
  9. package/docs/agent-notes/bus.md +2 -1
  10. package/docs/agent-notes/daemon.md +9 -7
  11. package/docs/agent-notes/local-worker.md +1 -1
  12. package/docs/agent-notes/models.md +5 -2
  13. package/docs/agent-notes/tasks.md +9 -2
  14. package/docs/agent-notes/tests.md +6 -0
  15. package/docs/design/adapters.md +182 -2
  16. package/docs/design/agent-hub-architecture.md +64 -2
  17. package/docs/design/agent-hub.md +6 -0
  18. package/docs/design/bus.md +26 -0
  19. package/docs/design/execution-reference.md +306 -0
  20. package/docs/design/guidance-experiments.md +438 -0
  21. package/docs/design/model-routes.md +628 -0
  22. package/docs/design/supervision.md +121 -0
  23. package/docs/design/task-board.md +121 -0
  24. package/docs/dogfood.md +45 -13
  25. package/docs/events.md +38 -20
  26. package/docs/memory.md +21 -7
  27. package/docs/operations.md +824 -40
  28. package/docs/profiles.md +2 -2
  29. package/docs/quickstart.md +117 -4
  30. package/docs/research.md +73 -13
  31. package/docs/roles.md +1 -1
  32. package/docs/sdlc.md +117 -11
  33. package/docs/security.md +153 -15
  34. package/docs/smoke.md +14 -0
  35. package/docs/specs/2026-09-19-agent-hub-design.md +13 -7
  36. package/docs/verification/2026-10-25-qwen-dual-output-t0.md +22 -0
  37. package/docs/verification/2026-11-07-compat-python-startup-1248.md +51 -0
  38. package/docs/verification/2026-11-07-compat-receipt-harness-1248.md +105 -0
  39. package/docs/verification/2026-11-07-compat-receipt-producers-1248.md +96 -0
  40. package/docs/verification/2026-11-07-compat-workflow-1248.md +94 -0
  41. package/docs/verification/2026-11-07-daemon-startup-1232.md +169 -0
  42. package/docs/verification/2026-11-07-jcode-receipt-reconstruction-1248.md +118 -0
  43. package/docs/verification/2026-11-07-kimi-delayed-usage.md +34 -0
  44. package/docs/verification/2026-11-07-kimi-review-watch-1284.md +115 -0
  45. package/docs/verification/2026-11-08-agy-1.5.3.md +96 -0
  46. package/docs/verification/2026-11-08-agy-acp-t0.md +56 -0
  47. package/docs/verification/2026-11-08-hub-visual-1058.md +161 -0
  48. package/docs/verification/2026-11-08-jcode-0991-model-setter-1317.md +143 -0
  49. package/docs/verification/2026-11-08-kimi-252-model-setter-1317.md +137 -0
  50. package/docs/verification/2026-11-08-kimi-tui-completion-1282.md +45 -0
  51. package/docs/verification/2026-11-08-kimi-wire-yield-1283.md +31 -0
  52. package/docs/verification/2026-11-08-live-model-override-1317.md +250 -0
  53. package/docs/verification/2026-11-08-qwen-0269-acp.md +138 -0
  54. package/docs/verification/2026-11-08-qwen-0269-model-setter-1317.md +91 -0
  55. package/docs/verification/2026-11-09-0.35.0.md +129 -0
  56. package/docs/verification/2026-11-09-headless-records-1320.md +157 -0
  57. package/docs/verification/2026-11-09-qwen-0270-acp.md +181 -0
  58. package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +46 -0
  59. package/docs/verification/2026-11-10-0.36.0.md +59 -0
  60. package/docs/verification/2026-11-10-claude-implementer-2.1.322.md +59 -0
  61. package/docs/verification/2026-11-10-qwen-0270-dual-output.md +367 -0
  62. package/docs/verification/2026-11-10-qwen-0271-dual-output.md +101 -0
  63. package/docs/verification/claude-permission-transport-native.py +10 -3
  64. package/docs/verification/claude-shell-wrapper-native.py +8 -8
  65. package/docs/verified.json +245 -15
  66. package/package.json +3 -3
  67. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  68. package/plugins/agent-hub/kimi-hook.js +21230 -0
  69. package/plugins/agent-hub/kimi-review-policy-worker.js +217 -0
  70. package/plugins/agent-hub/server.js +4359 -1071
  71. package/scripts/check-docs.mjs +12 -1
  72. package/src/adapters/acp-model-policy.ts +56 -0
  73. package/src/adapters/acp.ts +175 -5
  74. package/src/adapters/agy/entry.ts +8 -5
  75. package/src/adapters/agy/hooks.ts +65 -15
  76. package/src/adapters/channel-peer.ts +33 -1
  77. package/src/adapters/claude-channel.ts +7 -4
  78. package/src/adapters/claude-implementer.ts +16 -3
  79. package/src/adapters/codex-appserver.ts +118 -8
  80. package/src/adapters/codex-review-isolation.ts +3 -1
  81. package/src/adapters/compat.ts +18 -13
  82. package/src/adapters/definitions/builtin-metadata.ts +8 -1
  83. package/src/adapters/definitions/native-cli-entry-kimi.ts +76 -7
  84. package/src/adapters/definitions/native-cli-preview-common.ts +2 -2
  85. package/src/adapters/definitions/native-cli-preview-kimi.ts +9 -2
  86. package/src/adapters/definitions/reviewer-variants.ts +3 -1
  87. package/src/adapters/kimi-review-policy-worker.js +2 -0
  88. package/src/adapters/kimi-review-policy-worker.ts +85 -0
  89. package/src/adapters/kimi-review-policy.ts +68 -0
  90. package/src/adapters/kimi-review.ts +41 -41
  91. package/src/adapters/kimi-tui-facts.ts +153 -0
  92. package/src/adapters/kimi-wire-usage.ts +33 -8
  93. package/src/adapters/local-worker.ts +60 -21
  94. package/src/adapters/model-token.ts +3 -0
  95. package/src/adapters/pi.ts +27 -5
  96. package/src/adapters/qwen-dual.ts +324 -44
  97. package/src/adapters/registry-types.ts +34 -3
  98. package/src/adapters/registry.ts +1 -0
  99. package/src/adapters/reviewer-policy-watch.ts +86 -0
  100. package/src/adapters/reviewer-print.ts +80 -18
  101. package/src/cli/agents.ts +1 -1
  102. package/src/cli/facts-hook.ts +4 -2
  103. package/src/cli/guidance.ts +67 -0
  104. package/src/cli/help.ts +13 -5
  105. package/src/cli/identity.ts +13 -3
  106. package/src/cli/init-prompt.ts +15 -2
  107. package/src/cli/init-required-checks.ts +122 -0
  108. package/src/cli/init-settings.ts +10 -4
  109. package/src/cli/init.ts +39 -3
  110. package/src/cli/kimi-facts-hook.ts +11 -0
  111. package/src/cli/kimi-plugin.ts +157 -0
  112. package/src/cli/lineage.ts +78 -0
  113. package/src/cli/main.ts +159 -19
  114. package/src/cli/model.ts +52 -0
  115. package/src/cli/output.ts +23 -1
  116. package/src/cli/reset.ts +1 -1
  117. package/src/cli/setup-research.ts +10 -0
  118. package/src/cli/status-lines.ts +8 -4
  119. package/src/hub/autonomy-defaults.ts +20 -9
  120. package/src/hub/board.ts +346 -4
  121. package/src/hub/budget.ts +1 -1
  122. package/src/hub/build-entry.ts +11 -0
  123. package/src/hub/bus.ts +52 -2
  124. package/src/hub/ci-watch.ts +4 -4
  125. package/src/hub/code-facts.ts +10 -3
  126. package/src/hub/completions.ts +3 -1
  127. package/src/hub/config-apply.ts +3 -1
  128. package/src/hub/config-trust.ts +1 -0
  129. package/src/hub/control-client.ts +1 -1
  130. package/src/hub/daemon.ts +1387 -121
  131. package/src/hub/deliverable-files.ts +38 -5
  132. package/src/hub/delivery-hints.ts +4 -2
  133. package/src/hub/delivery-journal.ts +50 -2
  134. package/src/hub/delivery-public.ts +51 -0
  135. package/src/hub/dogfood-profile.ts +9 -5
  136. package/src/hub/envelope.ts +1 -1
  137. package/src/hub/events.ts +28 -18
  138. package/src/hub/execution-lineage-owner.ts +272 -0
  139. package/src/hub/execution-lineage.ts +164 -0
  140. package/src/hub/execution-links.ts +85 -0
  141. package/src/hub/execution-reference.ts +36 -0
  142. package/src/hub/guidance-variants.ts +398 -0
  143. package/src/hub/handoff.ts +1 -0
  144. package/src/hub/hub-tools.ts +62 -2
  145. package/src/hub/instances.ts +4 -3
  146. package/src/hub/kimi-events.ts +46 -0
  147. package/src/hub/kimi-usage.ts +132 -29
  148. package/src/hub/lifecycle.ts +31 -15
  149. package/src/hub/limits.ts +13 -4
  150. package/src/hub/manager.ts +58 -3
  151. package/src/hub/memory-policy.ts +4 -3
  152. package/src/hub/memory-sync-attestation.ts +54 -0
  153. package/src/hub/memory-sync-state.ts +20 -5
  154. package/src/hub/model-overrides.ts +115 -0
  155. package/src/hub/native-hook-launch.ts +12 -3
  156. package/src/hub/operational-view.ts +2 -2
  157. package/src/hub/peers.ts +28 -1
  158. package/src/hub/permission-mode.ts +1 -1
  159. package/src/hub/person-figures.ts +88 -0
  160. package/src/hub/planning.ts +1 -1
  161. package/src/hub/progress.ts +24 -7
  162. package/src/hub/report.ts +38 -4
  163. package/src/hub/research-dataset.ts +158 -0
  164. package/src/hub/research-memory.ts +68 -0
  165. package/src/hub/research-quality.ts +118 -0
  166. package/src/hub/research-record.ts +279 -0
  167. package/src/hub/research.ts +126 -27
  168. package/src/hub/restart.ts +27 -0
  169. package/src/hub/roles.ts +26 -0
  170. package/src/hub/routing.ts +4 -1
  171. package/src/hub/sdlc-merge.ts +39 -1
  172. package/src/hub/sdlc-release.ts +1 -1
  173. package/src/hub/sdlc.ts +62 -11
  174. package/src/hub/settings.ts +5 -0
  175. package/src/hub/startup-event-seeds.ts +51 -0
  176. package/src/hub/startup-readiness.ts +65 -0
  177. package/src/hub/startup-timing.ts +38 -0
  178. package/src/hub/supervision-proposals.ts +405 -0
  179. package/src/hub/supervision-rules.ts +388 -0
  180. package/src/hub/supervision.ts +2 -0
  181. package/src/hub/task-approval.ts +2 -2
  182. package/src/hub/task-repository.ts +5 -0
  183. package/src/hub/tasks.ts +632 -59
  184. package/src/hub/ui.ts +9 -5
  185. package/src/hub/visual-assets.ts +50 -0
  186. package/src/hub/visual.ts +257 -0
  187. package/src/memory/brief.ts +169 -14
  188. package/src/memory/capture.ts +4 -3
  189. package/src/memory/recall.ts +46 -5
  190. package/src/memory/record-provenance.ts +82 -0
  191. package/src/memory/records.ts +116 -0
  192. package/src/models/relay.ts +9 -2
  193. package/src/models/route/adec.ts +190 -0
  194. package/src/models/route/config.ts +64 -3
  195. package/src/models/route/decision-evidence.ts +83 -0
  196. package/src/models/route/decision.ts +215 -0
  197. package/src/models/route/relay-selector.ts +8 -7
  198. package/src/models/route/runtime.ts +35 -22
  199. package/src/models/route/stage-diagnostics.ts +22 -0
  200. package/src/models/route/stage-evidence.ts +55 -0
  201. package/src/models/route/stage-fallback.ts +58 -0
  202. package/src/models/route/stage-input.ts +155 -0
  203. package/src/models/route/stage.ts +5 -147
  204. package/src/ui/guidance-panel.ts +156 -0
  205. package/src/ui/guidance-view.ts +43 -0
  206. package/src/ui/index.html +134 -6
  207. package/src/ui/lineage-view.ts +34 -0
  208. package/src/ui/plugin.ts +136 -11
  209. package/templates/AGENTS.block.md +1 -1
  210. package/templates/config.json +1 -1
  211. package/templates/profiles/general.json +1 -1
  212. package/templates/profiles/research.json +1 -1
  213. package/templates/profiles/writing.json +1 -1
@@ -15,7 +15,7 @@ import type { PermissionRequest } from "./acp.ts";
15
15
  * `submit` and `confirmation_response` lines to the input file and tails the event file.
16
16
  *
17
17
  * Two limits, by design (spec: "Qwen dual-output TUI amendment"):
18
- * 1. A hub deny cancels Qwen's whole turn and Qwen emits nothing for it: after sending `allowed: false` this adapter ends the turn itself.
18
+ * 1. A hub deny has a known disposition but supplies no native completion signal: keep later inputs fenced until a new personal turn completes or a verified fresh generation starts.
19
19
  * 2. The input protocol cannot stop a turn and SIGINT does not either: the watchdog never cancels. It marks the turn stalled, and the
20
20
  * person presses Esc in the Qwen terminal. The hub never types into the terminal and never signals the process to stop a turn.
21
21
  */
@@ -37,6 +37,10 @@ export interface QwenDualOptions {
37
37
  pollMs?: number;
38
38
  /** How often the owner process is checked (ms). */
39
39
  ownerMs?: number;
40
+ /** Absolute wait after a deny, never an idle inference. Expiry retains the durable input fence. */
41
+ denyQuiescenceMs?: number;
42
+ /** Host-only fault seam. Never supplied by native event data or configuration. */
43
+ writeInput?: (fd: number, bytes: Buffer) => number;
40
44
  preamble?: string;
41
45
  /** The hub's own tools by exact `mcp__<server>__<tool>` name, never by prefix. */
42
46
  autoApprove?: (toolName: string) => boolean;
@@ -58,15 +62,22 @@ export interface QwenDualOptions {
58
62
  const SUBMIT_CAP = 256 * 1024;
59
63
  const READ_CAP = 1024 * 1024;
60
64
  const ANSWERED_CAP = 256;
65
+ export const QWEN_DENY_QUIESCENCE_MS = 30_000;
66
+ export const QWEN_DENY_QUIESCENCE_NOTE = "Qwen gave no signal that the denied turn ended; queued messages remain unsubmitted. Type a new prompt or press Esc in the Qwen terminal, then complete a personal turn; or end that terminal and run ahub qwen --mode tui";
67
+ export const QWEN_DENY_STORAGE_NOTE = "the hub could not persist Qwen's input fence state; queued messages remain unsubmitted. Check the Qwen state directory's storage and permissions before completing a new personal turn or restarting Qwen with ahub qwen --mode tui";
68
+ export const QWEN_INPUT_UNCERTAIN_NOTE = "Qwen's input file has an incomplete or unconfirmed record; queued messages remain unsubmitted. Inspect and end Qwen in its terminal, then run ahub qwen --mode tui to start a verified fresh generation";
61
69
  /** What the console, status and dashboard say while a turn is stalled. */
62
70
  export const QWEN_STALLED_NOTE = "stalled: Qwen has said nothing for a while; the hub cannot stop a Qwen turn, press Esc in the Qwen terminal";
63
71
  /** Shown while the hub cannot read the event file: the Qwen TUI itself keeps working, so this is never idle. */
64
72
  export const QWEN_DETACHED_NOTE = "detached: the hub cannot read Qwen's event file; Qwen keeps working in its terminal and the hub reattaches when the file is readable again";
65
73
  const DIR = "qwen-dual";
66
74
 
67
- type StateFile = { v: 1; sessionId?: string; offset: number; generation: number; ownerPid?: number; ownerSignature?: string };
75
+ type StateFile = { v: 1; sessionId?: string; offset: number; generation: number; ownerPid?: number; ownerSignature?: string; denyPending?: true };
68
76
  interface Turn { envs: Envelope[]; deliveryId?: string; text: string; started: boolean; accepted: boolean }
69
77
  type Json = Record<string, any>;
78
+ class QwenInputUncertain extends Error {
79
+ constructor() { super(QWEN_INPUT_UNCERTAIN_NOTE); }
80
+ }
70
81
 
71
82
  /** Whether a Qwen tool request names the hub's state dir: the input file is a prompt channel, so a write or command that reaches it is refused. */
72
83
  export function qwenDualNamesStateDir(input: unknown, stateDir: string): boolean {
@@ -135,6 +146,23 @@ export class QwenDualPeer extends BasePeer {
135
146
  private pollFailures = 0;
136
147
  /** Inside an event line longer than READ_CAP: its rest is dropped through the next newline. */
137
148
  private discarding = false;
149
+ private denyTimer?: ReturnType<typeof setTimeout>;
150
+ private denyCursor = 0;
151
+ private eventCursor = 0;
152
+ private eventStart = 0;
153
+ private freshFenceOwner?: string;
154
+ private personalProof?: { generation: number; session: string; owner: string; assistant: boolean };
155
+ private readCompletion?: { kind: "personal" | "fresh"; generation: number; session: string; owner: string; source: string; personal?: object };
156
+ private freshCompletionAllowed = false;
157
+ private freshRead?: { generation: number; source: string; session?: string; activity: boolean };
158
+ private freshEventIdentity?: string;
159
+ private polling = false;
160
+ private fenceFile?: string;
161
+ private denyStorageFailure = false;
162
+ private inputBlocked = false;
163
+ private freshInputPending = false;
164
+ private freshBaselineAbsent = false;
165
+ private freshEventReady = false;
138
166
 
139
167
  constructor(id: PeerId, private readonly opts: QwenDualOptions) {
140
168
  super(id, opts.watchdogMs);
@@ -149,7 +177,9 @@ export class QwenDualPeer extends BasePeer {
149
177
  get adopted(): boolean { return this.adopting; }
150
178
  private adopting = false;
151
179
  get stalled(): boolean { return this.stalled_; }
152
- get statusNotice(): { code: "qwen-stalled" | "qwen-detached"; message: string } | undefined {
180
+ get statusNotice(): { code: "qwen-stalled" | "qwen-detached" | "qwen-deny-quiescence"; message: string } | undefined {
181
+ if (this.inputBlocked || this.freshInputPending) return { code: "qwen-deny-quiescence", message: QWEN_INPUT_UNCERTAIN_NOTE };
182
+ if (this.state_.denyPending) return { code: "qwen-deny-quiescence", message: this.denyStorageFailure ? QWEN_DENY_STORAGE_NOTE : QWEN_DENY_QUIESCENCE_NOTE };
153
183
  if (this.detached) return { code: "qwen-detached", message: QWEN_DETACHED_NOTE };
154
184
  return this.stalled_ ? { code: "qwen-stalled", message: QWEN_STALLED_NOTE } : undefined;
155
185
  }
@@ -185,18 +215,22 @@ export class QwenDualPeer extends BasePeer {
185
215
  if (!info.isFile() || info.size > 4096) return;
186
216
  const buffer = Buffer.alloc(info.size); readSync(fd, buffer, 0, info.size, 0);
187
217
  const raw = JSON.parse(buffer.toString("utf8")) as Partial<StateFile>;
218
+ if (Object.hasOwn(raw, "denyPending")) this.state_.denyPending = true;
188
219
  if (raw.v !== 1 || !Number.isSafeInteger(raw.offset) || raw.offset! < 0 || !Number.isSafeInteger(raw.generation)) return;
189
220
  this.state_ = { v: 1, offset: raw.offset!, generation: raw.generation!,
190
221
  ...(qwenSessionId(raw.sessionId) ? { sessionId: raw.sessionId } : {}),
191
- ...(Number.isSafeInteger(raw.ownerPid) && typeof raw.ownerSignature === "string" ? { ownerPid: raw.ownerPid, ownerSignature: raw.ownerSignature } : {}) };
222
+ ...(Number.isSafeInteger(raw.ownerPid) && typeof raw.ownerSignature === "string" ? { ownerPid: raw.ownerPid, ownerSignature: raw.ownerSignature } : {}),
223
+ // Unknown/malformed fence metadata never grants readiness. Only the literal true is written by this host.
224
+ ...(Object.hasOwn(raw, "denyPending") ? { denyPending: true as const } : {}) };
192
225
  } catch { /* no usable record: a fresh launch */ }
193
226
  finally { if (fd !== undefined) try { closeSync(fd); } catch { /* nothing to close */ } }
194
227
  }
195
228
 
196
- private saveState(): void {
229
+ private saveState(): boolean {
197
230
  const temp = `${this.stateFile}.${process.pid}.tmp`;
198
- try { writeFileSync(temp, `${JSON.stringify(this.state_)}\n`, { mode: 0o600 }); renameSync(temp, this.stateFile); }
199
- catch { this.opts.log?.(`[${this.id}] could not record its Qwen read position`); }
231
+ try { writeFileSync(temp, `${JSON.stringify(this.state_)}\n`, { mode: 0o600 }); renameSync(temp, this.stateFile); return true; }
232
+ catch { try { this.opts.log?.(`[${this.id}] could not record its Qwen read position`); } catch { /* advisory failure never changes the checked write result */ } }
233
+ return false;
200
234
  }
201
235
 
202
236
  private ownerAlive(): boolean {
@@ -209,8 +243,10 @@ export class QwenDualPeer extends BasePeer {
209
243
  mkdirSync(this.dir, { recursive: true, mode: 0o700 });
210
244
  const dir = lstatSync(this.dir);
211
245
  if (!dir.isDirectory() || dir.isSymbolicLink() || (typeof process.getuid === "function" && dir.uid !== process.getuid()) || (dir.mode & 0o077) !== 0) throw new Error("Qwen dual-output directory is not private to the person running the hub");
246
+ this._launch = undefined;
212
247
  this.loadState();
213
248
  for (const path of [this.inputFile, this.eventFile]) this.ensureFile(path, true);
249
+ this.checkInputTail();
214
250
  this.stopping = false; this.exited = false;
215
251
  if (this.ownerAlive()) {
216
252
  // The hub restarted while the person's Qwen kept running: read on from the saved offset. No event is processed twice and no launch happens.
@@ -221,27 +257,80 @@ export class QwenDualPeer extends BasePeer {
221
257
  // ponytail: a Qwen turn that was running when the hub went away is not known here, so the adopted peer reads idle until the next event says otherwise.
222
258
  // Upgrade: record the open hub turn in state.json and settle it on adoption.
223
259
  this.sessionSeen = this.state_.sessionId !== undefined; this.primed = true;
260
+ if (this.state_.denyPending || this.freshInputPending) { this.denyCursor = size; }
224
261
  this.saveState();
225
262
  } else {
226
263
  // A fresh or resumed launch. Qwen opens an existing event file without truncating or appending, so it would overwrite it from byte 0: start from empty files.
227
264
  this.adopting = false;
228
- this.resume = this.opts.sessionId !== undefined || this.state_.sessionId !== undefined;
229
- const resumeId = this.opts.sessionId ?? this.state_.sessionId;
230
- const previous = lstatSync(this.eventFile);
231
- if (previous.size > 0) { try { renameSync(this.eventFile, join(this.dir, "events.prev.jsonl")); } catch { /* a stale copy is only evidence */ } this.ensureFile(this.eventFile, true); }
232
- closeSync(openSync(this.inputFile, constants.O_WRONLY | constants.O_NOFOLLOW | constants.O_TRUNC)); // Qwen starts reading at the file's current end, so earlier submits are never replayed; empty is the clearest record
233
- this.state_ = { v: 1, offset: 0, generation: this.state_.generation + 1, ...(resumeId ? { sessionId: resumeId } : {}) };
234
- this.sessionSeen = false;
235
- this.saveState();
236
- this.writeLaunch(resumeId);
265
+ const fenced = this.state_.denyPending || this.inputBlocked || this.freshInputPending;
266
+ if (fenced) {
267
+ const rows = (this.opts.table ?? processTable)();
268
+ const flag = `--input-file ${this.inputFile}`;
269
+ this.freshBaselineAbsent = rows !== undefined && !rows.some(row => row.pid !== process.pid && row.command.includes(flag));
270
+ }
271
+ if (fenced && !this.freshBaselineAbsent) {
272
+ // No file rotation/truncation or launcher may overlap an unverified existing native owner.
273
+ this.sessionSeen = this.state_.sessionId !== undefined; this.primed = true;
274
+ this.denyCursor = lstatSync(this.eventFile).size;
275
+ this.setState("offline");
276
+ try { this.opts.onNotice?.(`${this.id}: the hub could not verify that the old Qwen terminal is absent; inspect and end that terminal before running ahub qwen --mode tui again`); } catch { /* already offline */ }
277
+ } else {
278
+ this.resume = this.opts.sessionId !== undefined || this.state_.sessionId !== undefined;
279
+ const resumeId = this.opts.sessionId ?? this.state_.sessionId;
280
+ const denyPending = this.state_.denyPending;
281
+ if (denyPending || this.inputBlocked) this.freshFenceOwner = this.ownerIdentity();
282
+ this.freshInputPending = this.inputBlocked;
283
+ this.freshEventReady = this.prepareFreshEvents(!!fenced);
284
+ if (fenced && !this.freshEventReady) {
285
+ this.freshInputPending = true; this.denyCursor = this.state_.offset;
286
+ this.setState("offline");
287
+ try { this.opts.onNotice?.(`${this.id}: a fresh empty Qwen event file could not be prepared; inspect the Qwen state directory and events.prev.jsonl before running ahub qwen --mode tui again`); } catch { /* already offline */ }
288
+ } else {
289
+ closeSync(openSync(this.inputFile, constants.O_WRONLY | constants.O_NOFOLLOW | constants.O_TRUNC)); // Qwen starts reading at the file's current end, so earlier submits are never replayed; empty is the clearest record
290
+ this.inputBlocked = false;
291
+ this.state_ = { v: 1, offset: 0, generation: this.state_.generation + 1, ...(resumeId ? { sessionId: resumeId } : {}), ...(denyPending ? { denyPending } : {}) };
292
+ this.sessionSeen = false;
293
+ if (fenced) {
294
+ this.discardReadProof();
295
+ this.fenceFile = this.freshEventIdentity; this.denyCursor = 0; this.eventCursor = 0; this.eventStart = 0;
296
+ this.detached = false; this.discarding = false; this.pollFailures = 0;
297
+ this.freshRead = { generation: this.state_.generation, source: this.freshEventIdentity!, activity: false };
298
+ }
299
+ this.saveState();
300
+ this.writeLaunch(resumeId);
301
+ }
302
+ }
237
303
  }
238
304
  this.poller = setInterval(() => this.poll(), this.opts.pollMs ?? 100); this.poller.unref?.();
239
305
  if (!this.monitor) { this.monitor = setInterval(() => this.checkOwner(), this.opts.ownerMs ?? 1_000); this.monitor.unref?.(); }
240
306
  this.poll();
241
- if (this.adopting && !this.detached && this.sessionSeen) this.setState("idle");
307
+ if (this.adopting && !this.detached && this.sessionSeen && !this.state_.denyPending && !this.inputBlocked && !this.freshInputPending) this.setState("idle");
242
308
  // A TUI that has not announced itself yet is not attached: the hub treats the peer as offline until session_start.
243
309
  }
244
310
 
311
+ private prepareFreshEvents(fenced: boolean): boolean {
312
+ if (!fenced) {
313
+ const previous = lstatSync(this.eventFile);
314
+ if (previous.size > 0) { try { renameSync(this.eventFile, join(this.dir, "events.prev.jsonl")); } catch { /* preserve the legacy nonfenced rotation ceiling */ } this.ensureFile(this.eventFile, true); }
315
+ return true;
316
+ }
317
+ this.freshEventIdentity = undefined;
318
+ let fd: number | undefined;
319
+ let ready = false;
320
+ try {
321
+ const previous = lstatSync(this.eventFile);
322
+ if (previous.size > 0) renameSync(this.eventFile, join(this.dir, "events.prev.jsonl"));
323
+ this.ensureFile(this.eventFile, true);
324
+ fd = openSync(this.eventFile, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
325
+ const info = fstatSync(fd);
326
+ ready = info.isFile() && info.size === 0;
327
+ if (ready) this.freshEventIdentity = `${info.dev}:${info.ino}`;
328
+ } catch { /* no verified empty source */ }
329
+ finally { if (fd !== undefined) try { closeSync(fd); } catch { ready = false; } }
330
+ if (!ready) this.freshEventIdentity = undefined;
331
+ return ready;
332
+ }
333
+
245
334
  private writeLaunch(resumeId: string | undefined): void {
246
335
  const [bin, ...rest] = this.opts.cmd.filter(word => word !== "--acp");
247
336
  if (!bin) throw new Error("qwen_cmd must name an executable");
@@ -274,12 +363,19 @@ export class QwenDualPeer extends BasePeer {
274
363
 
275
364
  private checkOwner(): void {
276
365
  if (this.stopping || this.exited) return;
277
- if (this.state_.ownerPid === undefined) { if (this.sessionSeen) this.discoverOwner(); return; }
278
- if (this.ownerAlive()) return;
366
+ if (this.state_.ownerPid === undefined) {
367
+ if (this.sessionSeen) this.discoverOwner();
368
+ this.verifyFreshInput();
369
+ return;
370
+ }
371
+ if (this.ownerAlive()) {
372
+ this.verifyFreshInput();
373
+ return;
374
+ }
279
375
  if (this.state === "offline" && !this.sessionSeen) return;
280
376
  this.exited = true;
281
377
  this.opts.log?.(`[${this.id}] the Qwen TUI exited`);
282
- this.failTurn("the Qwen terminal ended before the turn settled; inspect it before retrying");
378
+ this.failTurn("the Qwen terminal ended before the turn settled; inspect it before retrying", true);
283
379
  this.abortApprovals();
284
380
  delete this.state_.ownerPid; delete this.state_.ownerSignature; this.saveState();
285
381
  this.setState("offline");
@@ -288,19 +384,64 @@ export class QwenDualPeer extends BasePeer {
288
384
 
289
385
  // ---- delivery ----------------------------------------------------------------------------------------------------
290
386
 
387
+ private inputHasCompleteTail(fd: number): boolean {
388
+ const info = fstatSync(fd);
389
+ if (!info.isFile()) return false;
390
+ if (info.size === 0) return true;
391
+ const last = Buffer.alloc(1);
392
+ return readSync(fd, last, 0, last.length, info.size - last.length) === last.length && last[0] === 10;
393
+ }
394
+
395
+ private freshRecoveryCurrent(): boolean {
396
+ const launch = this.freshRead;
397
+ return this.freshEventReady && this.freshBaselineAbsent && this.freshFenceOwner !== undefined
398
+ && !!launch && launch.generation === this.state_.generation && launch.session === this.state_.sessionId
399
+ && this.sessionSeen && this.ownerIdentity() !== this.freshFenceOwner;
400
+ }
401
+
402
+ private verifyFreshInput(): void {
403
+ if (!(this.state_.denyPending || this.freshInputPending) || !this.freshCompletionAllowed || !this.freshRecoveryCurrent() || !this.ownerAlive()) return;
404
+ this.readCompletion = { kind: "fresh", generation: this.state_.generation, session: this.state_.sessionId!, owner: this.ownerIdentity(), source: this.freshRead!.source };
405
+ }
406
+
407
+ private checkInputTail(): void {
408
+ let fd: number | undefined;
409
+ try {
410
+ fd = openSync(this.inputFile, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
411
+ if (!this.inputHasCompleteTail(fd)) this.blockInput();
412
+ } catch { this.blockInput(); }
413
+ finally { if (fd !== undefined) try { closeSync(fd); } catch { this.blockInput(); } }
414
+ }
415
+
416
+ private blockInput(): void {
417
+ const newlyBlocked = !this.inputBlocked;
418
+ this.inputBlocked = true; this.discardReadProof();
419
+ this.failTurn(QWEN_INPUT_UNCERTAIN_NOTE, true);
420
+ this.setState("offline");
421
+ if (newlyBlocked) try { this.opts.onNotice?.(`${this.id}: ${QWEN_INPUT_UNCERTAIN_NOTE}`); } catch { /* already fenced */ }
422
+ }
423
+
291
424
  private appendInput(record: Json): void {
292
- const line = `${JSON.stringify(record)}\n`;
293
- if (Buffer.byteLength(line) > SUBMIT_CAP) throw new Error("Qwen submit exceeds its size bound");
294
- const fd = openSync(this.inputFile, constants.O_WRONLY | constants.O_APPEND | constants.O_NOFOLLOW);
425
+ const bytes = Buffer.from(`${JSON.stringify(record)}\n`, "utf8");
426
+ if (bytes.length > SUBMIT_CAP) throw new Error("Qwen submit exceeds its size bound");
427
+ if (this.inputBlocked || this.freshInputPending) throw new QwenInputUncertain();
428
+ const fd = openSync(this.inputFile, constants.O_RDWR | constants.O_APPEND | constants.O_NOFOLLOW | constants.O_NONBLOCK);
429
+ let writerAttempted = false;
295
430
  try {
296
431
  const info = fstatSync(fd);
297
432
  if (!info.isFile() || (info.mode & 0o077) !== 0 || (typeof process.getuid === "function" && info.uid !== process.getuid())) throw new Error("Qwen input file is not private");
298
- writeSync(fd, line);
299
- } finally { closeSync(fd); }
433
+ if (!this.inputHasCompleteTail(fd)) throw new QwenInputUncertain();
434
+ // ponytail: a torn prefix ending in newline is not detected by this tail guard. If observed, add a durable write-intent record before every input write.
435
+ writerAttempted = true;
436
+ try { if ((this.opts.writeInput ?? writeSync)(fd, bytes) !== bytes.length) throw new QwenInputUncertain(); }
437
+ catch { throw new QwenInputUncertain(); } // no retry or remainder: the writer may already have appended a prefix
438
+ } finally {
439
+ try { closeSync(fd); } catch (error) { if (writerAttempted) throw new QwenInputUncertain(); throw error; }
440
+ }
300
441
  }
301
442
 
302
443
  async deliver(envs: Envelope[], deliveryId?: string): Promise<void> {
303
- if (this.state !== "idle" || this.stopping || this.detached) {
444
+ if (this.state !== "idle" || this.stopping || this.detached || this.state_.denyPending || this.inputBlocked) {
304
445
  if (deliveryId) this.delivery({ id: deliveryId, state: "failed_safe", reason: `${this.id} is ${this.state}` });
305
446
  throw new Error(`${this.id} is ${this.state}`);
306
447
  }
@@ -312,6 +453,7 @@ export class QwenDualPeer extends BasePeer {
312
453
  this.setState("busy"); // synchronously: the bus must not drain the next envelope into this turn
313
454
  try { this.appendInput({ type: "submit", text }); }
314
455
  catch (error) {
456
+ if (error instanceof QwenInputUncertain) { this.blockInput(); throw error; }
315
457
  this.turn = undefined;
316
458
  if (deliveryId) this.delivery({ id: deliveryId, state: "failed_safe", reason: "Qwen input file could not be written" });
317
459
  this.setState("idle");
@@ -323,7 +465,7 @@ export class QwenDualPeer extends BasePeer {
323
465
  // ---- watchdog: report, never cancel -----------------------------------------------------------------------------------
324
466
 
325
467
  protected override onWatchdog(): void {
326
- if (this.state !== "busy" || this.stalled_) return;
468
+ if (this.state !== "busy" || this.stalled_ || this.state_.denyPending) return;
327
469
  if (this.pending.size > 0) { this.touch(); return; } // a person deciding is not Qwen going silent
328
470
  this.stalled_ = true;
329
471
  this.opts.log?.(`[${this.id}] turn stalled; the hub cannot stop it (press Esc in the Qwen terminal)`);
@@ -343,21 +485,29 @@ export class QwenDualPeer extends BasePeer {
343
485
  if (this.detached) return;
344
486
  this.detached = true;
345
487
  this.opts.log?.(`[${this.id}] event file ${reason}: detached`);
346
- this.failTurn("the Qwen event file became unreadable before the turn settled; inspect the Qwen terminal before retrying");
488
+ this.discardReadProof();
489
+ this.failTurn("the Qwen event file became unreadable before the turn settled; inspect the Qwen terminal before retrying", true);
347
490
  this.abortApprovals();
348
491
  if (this.state !== "offline") this.setState("offline"); // detached is never idle: nothing can be delivered to a TUI nobody can read
349
492
  }
350
493
 
351
494
  private poll(): void {
352
- if (this.stopping) return;
495
+ if (this.stopping || this.polling) return;
496
+ this.polling = true;
353
497
  let fd: number | undefined;
354
498
  try {
499
+ this.checkInputTail();
355
500
  fd = openSync(this.eventFile, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
356
501
  const info = fstatSync(fd);
357
502
  if (!info.isFile()) throw new Error("not a regular file");
358
- if (this.detached) { this.detached = false; this.pollFailures = 0; this.opts.log?.(`[${this.id}] event file readable again: reattached`); if (this.sessionSeen && this.state === "offline" && !this.exited) this.setState("idle"); }
503
+ if (this.state_.denyPending || this.freshInputPending) {
504
+ const identity = `${info.dev}:${info.ino}`;
505
+ if (this.detached || this.fenceFile !== undefined && identity !== this.fenceFile) { this.discardReadProof(); this.denyCursor = info.size; }
506
+ this.fenceFile = identity;
507
+ }
508
+ if (this.detached) { this.detached = false; this.pollFailures = 0; this.opts.log?.(`[${this.id}] event file readable again: reattached`); if (this.sessionSeen && this.state === "offline" && !this.exited && !this.state_.denyPending && !this.inputBlocked && !this.freshInputPending) this.setState("idle"); }
359
509
  let offset = this.state_.offset;
360
- if (info.size < offset) { offset = 0; this.discarding = false; this.state_.generation++; this.opts.log?.(`[${this.id}] event file was replaced; reading from its start`); }
510
+ if (info.size < offset) { offset = 0; this.discarding = false; this.state_.generation++; this.discardReadProof(); this.denyCursor = info.size; this.opts.log?.(`[${this.id}] event file was replaced; reading from its start`); }
361
511
  while (offset < info.size) {
362
512
  const want = Math.min(info.size - offset, READ_CAP), buffer = Buffer.alloc(want);
363
513
  const got = readSync(fd, buffer, 0, want, offset);
@@ -373,29 +523,52 @@ export class QwenDualPeer extends BasePeer {
373
523
  const end = buffer.subarray(0, got).lastIndexOf(10) + 1;
374
524
  if (end === 0) {
375
525
  if (got < READ_CAP) break; // a partial line waits for its newline
526
+ this.discardReadProof();
376
527
  this.opts.log?.(`[${this.id}] dropped an event line over ${READ_CAP} bytes`);
377
528
  this.discarding = true; offset += got; this.state_.offset = offset; continue;
378
529
  }
530
+ const start = offset;
379
531
  offset += end;
380
532
  this.state_.offset = offset;
381
- for (const line of buffer.subarray(0, end).toString("utf8").split("\n")) if (line.trim()) this.parse(line);
533
+ for (let cursor = 0; cursor < end;) {
534
+ const newline = buffer.indexOf(10, cursor);
535
+ const rawLine = buffer.subarray(cursor, newline);
536
+ const line = rawLine.toString("utf8");
537
+ this.eventStart = start + cursor;
538
+ cursor = newline + 1;
539
+ this.eventCursor = start + cursor;
540
+ if (!Buffer.from(line).equals(rawLine)) { this.discardReadProof(); continue; }
541
+ if (line.trim()) this.parse(line);
542
+ }
382
543
  if (this.stopping) break;
383
544
  }
545
+ this.finishFencedRead(fd);
384
546
  this.saveState();
385
547
  } catch (error) {
386
548
  this.pollFailures++;
387
549
  if (!this.detached) this.detach(`could not be read (${(error as NodeJS.ErrnoException).code ?? "error"})`);
388
- } finally { if (fd !== undefined) try { closeSync(fd); } catch { /* nothing to close */ } }
550
+ } finally {
551
+ if (fd !== undefined) try { closeSync(fd); } catch { /* nothing to close */ }
552
+ this.polling = false;
553
+ }
389
554
  }
390
555
 
391
556
  private parse(line: string): void {
392
557
  let event: Json;
393
- try { event = JSON.parse(line) as Json; } catch { this.opts.log?.(`[${this.id}] skipped an unreadable event line`); return; }
394
- if (!event || typeof event !== "object" || typeof event.type !== "string") return;
395
- try { this.handle(event); } catch (error) { this.opts.log?.(`[${this.id}] event handling failed: ${sanitize((error as Error).message)}`); }
558
+ try { event = JSON.parse(line) as Json; } catch { this.discardReadProof(); this.opts.log?.(`[${this.id}] skipped an unreadable event line`); return; }
559
+ if (!event || typeof event !== "object" || typeof event.type !== "string") { this.discardReadProof(); return; }
560
+ try { this.handle(event); } catch (error) { this.discardReadProof(); this.opts.log?.(`[${this.id}] event handling failed: ${sanitize((error as Error).message)}`); }
396
561
  }
397
562
 
398
563
  private handle(event: Json): void {
564
+ if (this.inputBlocked) return;
565
+ const fenced = this.state_.denyPending || this.freshInputPending;
566
+ if (fenced && this.eventStart < this.denyCursor) { this.discardReadProof(); return; }
567
+ if (fenced && event.type !== "system") {
568
+ this.readCompletion = undefined; this.freshCompletionAllowed = false;
569
+ if (this.freshRead) this.freshRead.activity = true;
570
+ this.observeDenied(event); return;
571
+ }
399
572
  this.alive();
400
573
  switch (event.type) {
401
574
  case "system": return this.onSystem(event);
@@ -410,22 +583,32 @@ export class QwenDualPeer extends BasePeer {
410
583
  }
411
584
 
412
585
  private onSystem(event: Json): void {
413
- if (event.subtype !== "session_start") return;
586
+ const fenced = this.state_.denyPending || this.freshInputPending;
587
+ if (fenced) { this.personalProof = undefined; this.readCompletion = undefined; this.freshCompletionAllowed = false; }
588
+ if (event.subtype !== "session_start") { if (fenced && this.freshRead) this.freshRead.activity = true; return; }
414
589
  const data = event.data ?? {};
415
590
  const id = event.session_id ?? data.session_id;
416
- if (!qwenSessionId(id)) return;
591
+ if (!qwenSessionId(id)) { if (fenced && this.freshRead) this.freshRead.activity = true; return; }
417
592
  // The TUI states its own contract: a version, protocol or event set the hub did not verify is refused, however it was launched.
418
593
  const verdict = assessVersion("qwen-dual", data.version);
419
594
  const supported: unknown = data.supported_events;
420
595
  if (!verdict.ok || data.protocol_version !== 2 || !Array.isArray(supported) || !["user", "assistant", "stream_event", "control_request", "control_response"].every(name => supported.includes(name))) {
596
+ if (fenced && this.freshRead) this.freshRead.activity = true;
421
597
  this.opts.log?.(`[${this.id}] the Qwen TUI's dual-output contract is not verified; not attached`);
422
598
  try { this.opts.onNotice?.(`${this.id}: this Qwen's dual-output contract is not verified (${verdict.ok ? "protocol or event set" : verdict.reason}); the hub did not attach it`); } catch { /* notice only */ }
423
599
  return;
424
600
  }
425
- this.state_.sessionId = id; this.sessionSeen = true; this.saveState();
601
+ if (this.state_.denyPending && this.freshFenceOwner === undefined && id !== this.state_.sessionId) { this.discardReadProof(); return; }
602
+ this.state_.sessionId = id; this.sessionSeen = true;
603
+ if (fenced && this.freshRead) {
604
+ if (this.freshRead.session === undefined) { this.freshRead.session = id; this.freshCompletionAllowed = !this.freshRead.activity; }
605
+ else this.freshRead.activity = true; // a replay never re-arms an invalidated fresh-header candidate
606
+ }
607
+ this.saveState();
426
608
  // Bind the owner now, not on the next tick: a hub that stops in between would record no owner and relaunch over a Qwen that is still running.
427
609
  this.discoverOwner();
428
- if (!this.stopping && !this.detached && this.state === "offline") this.setState("idle");
610
+ this.verifyFreshInput();
611
+ if (!this.stopping && !this.detached && this.state === "offline" && !this.state_.denyPending && !this.freshInputPending) this.setState("idle");
429
612
  }
430
613
 
431
614
  /**
@@ -516,6 +699,90 @@ export class QwenDualPeer extends BasePeer {
516
699
 
517
700
  // ---- approvals ------------------------------------------------------------------------------------------------------------
518
701
 
702
+ private ownerIdentity(): string { return `${this.state_.ownerPid}:${this.state_.ownerSignature}`; }
703
+
704
+ /** A deny has no completion ACK. Only a subsequent personal turn, or a verified new launch, can reopen input. */
705
+ private observeDenied(event: Json): void {
706
+ if (this.stopping || this.exited || this.detached || this.eventCursor <= this.denyCursor) return;
707
+ const session = this.state_.sessionId;
708
+ if (!session || event.session_id !== session || !this.ownerAlive()) { this.discardReadProof(); return; }
709
+ if (event.type === "user") {
710
+ if (this.isNotificationEvent(event) || this.promptText(event) === undefined) { this.discardReadProof(); return; }
711
+ this.personalProof = { generation: this.state_.generation, session, owner: this.ownerIdentity(), assistant: false };
712
+ return;
713
+ }
714
+ const proof = this.personalProof;
715
+ if (!proof || proof.generation !== this.state_.generation || proof.session !== session || proof.owner !== this.ownerIdentity()) return;
716
+ if (event.type === "assistant") {
717
+ const message = event.message;
718
+ proof.assistant = message?.stop_reason === "end_turn" && Array.isArray(message.content) && !message.content.some((block: Json) => block?.type === "tool_use");
719
+ } else if (event.type === "stream_event" && event.event?.type === "message_stop") {
720
+ if (proof.assistant && this.fenceFile !== undefined) this.readCompletion = { kind: "personal", generation: proof.generation, session: proof.session, owner: proof.owner, source: this.fenceFile, personal: proof };
721
+ proof.assistant = false;
722
+ } else proof.assistant = false;
723
+ }
724
+
725
+ private discardReadProof(): void {
726
+ this.personalProof = undefined; this.readCompletion = undefined; this.freshCompletionAllowed = false;
727
+ if (this.freshRead) this.freshRead.activity = true;
728
+ }
729
+
730
+ private finishFencedRead(fd: number): void {
731
+ const candidate = this.readCompletion;
732
+ if (!(this.state_.denyPending || this.freshInputPending) || !candidate || this.discarding) return;
733
+ if (!this.ownerAlive()) { this.discardReadProof(); return; }
734
+ if (this.readCompletion !== candidate || this.stopping || this.exited || this.detached || this.inputBlocked
735
+ || candidate.generation !== this.state_.generation || candidate.session !== this.state_.sessionId || candidate.owner !== this.ownerIdentity()
736
+ || candidate.kind === "personal" && candidate.personal !== this.personalProof
737
+ || candidate.kind === "fresh" && !this.freshCompletionAllowed
738
+ || this.freshInputPending && !this.freshRecoveryCurrent()) { this.discardReadProof(); return; }
739
+ const current = fstatSync(fd), named = lstatSync(this.eventFile);
740
+ if (!current.isFile() || !named.isFile() || named.isSymbolicLink() || current.dev !== named.dev || current.ino !== named.ino
741
+ || `${current.dev}:${current.ino}` !== candidate.source
742
+ || this.freshInputPending && candidate.source !== this.freshRead?.source
743
+ || current.size !== this.state_.offset || named.size !== current.size) { this.discardReadProof(); return; }
744
+ // ponytail: this proves only the observed frontier; atomic exclusion of future person input needs a serialized native idle ACK.
745
+ this.readCompletion = undefined; this.freshInputPending = false;
746
+ this.clearDenyFence();
747
+ }
748
+
749
+ private clearDenyFence(): void {
750
+ if (this.inputBlocked || this.freshInputPending) return;
751
+ // A refusal before the deny append leaves an unsettled original turn. Recovery is not evidence of its outcome.
752
+ if (this.turn) this.failTurn("the approval outcome was not confirmed before Qwen recovered; inspect the terminal and held delivery before retrying", true);
753
+ delete this.state_.denyPending;
754
+ if (!this.saveState()) {
755
+ this.state_.denyPending = true; this.discardReadProof(); this.denyStorageFailure = true;
756
+ this.setState("offline");
757
+ try { this.opts.onNotice?.(`${this.id}: ${QWEN_DENY_STORAGE_NOTE}`); } catch { /* advisory only, the fence is already restored */ }
758
+ return;
759
+ }
760
+ if (this.denyTimer) clearTimeout(this.denyTimer);
761
+ this.denyTimer = undefined; this.discardReadProof(); this.freshFenceOwner = undefined;
762
+ this.denyStorageFailure = false; this.stalled_ = false; this.lastAssistant = undefined;
763
+ this.opts.onStalled?.(false);
764
+ if (!this.stopping && !this.detached && !this.exited) this.setState("idle");
765
+ }
766
+
767
+ private fenceDeny(): boolean {
768
+ let fd: number | undefined;
769
+ try {
770
+ fd = openSync(this.eventFile, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
771
+ const info = fstatSync(fd);
772
+ if (!info.isFile()) throw new Error("not a regular file");
773
+ this.denyCursor = info.size; this.fenceFile = `${info.dev}:${info.ino}`;
774
+ this.state_.denyPending = true;
775
+ if (!this.saveState()) throw new Error("could not persist fence");
776
+ this.discardReadProof(); this.lastAssistant = undefined;
777
+ return true;
778
+ } catch {
779
+ // No deny is appended without its restart fence. Keep any saved marker conservative as well.
780
+ this.state_.denyPending = true; this.denyStorageFailure = true; this.setState("offline");
781
+ try { this.opts.onNotice?.(`${this.id}: the hub could not persist the deny input fence; answer the pending prompt in the Qwen terminal and inspect its state before restarting the hub`); } catch { /* notice only */ }
782
+ return false;
783
+ } finally { if (fd !== undefined) closeSync(fd); }
784
+ }
785
+
519
786
  private abortApprovals(): void {
520
787
  for (const { controller } of this.pending.values()) controller.abort();
521
788
  this.pending.clear();
@@ -556,20 +823,31 @@ export class QwenDualPeer extends BasePeer {
556
823
  }
557
824
 
558
825
  private answer(requestId: string, allowed: boolean, turn: Turn, why?: string): void {
826
+ if (this.turn !== turn || this.stopping || this.state_.denyPending || this.answered.has(requestId)) return;
827
+ if (!allowed && !this.fenceDeny()) return;
559
828
  try { this.appendInput({ type: "confirmation_response", request_id: requestId, allowed }); }
560
- catch {
829
+ catch (error) {
830
+ if (error instanceof QwenInputUncertain) { this.blockInput(); return; }
561
831
  // Qwen never received it: it is still blocked on the approval. Settling the turn (a deny) or reporting it answered would be a claim the hub cannot back, so the turn stays busy
562
832
  // (the watchdog reports it if nothing moves) and the person is told to answer in the Qwen terminal, where the prompt is still open.
563
- this.opts.log?.(`[${this.id}] could not write an approval answer`);
833
+ if (!allowed) { delete this.state_.denyPending; if (!this.saveState()) { this.state_.denyPending = true; this.denyStorageFailure = true; this.setState("offline"); } }
834
+ try { this.opts.log?.(`[${this.id}] could not write an approval answer`); } catch { /* advisory only */ }
564
835
  try { this.opts.onNotice?.(`${this.id}: the hub could not write its approval answer (the input file is unwritable); answer the prompt in the Qwen terminal`); } catch { /* notice only */ }
565
836
  return;
566
837
  }
567
838
  this.answered.add(requestId); while (this.answered.size > ANSWERED_CAP) this.answered.delete(this.answered.values().next().value as string);
568
839
  if (allowed || this.turn !== turn) return;
569
- // Limit 1: a deny cancels Qwen's whole turn and Qwen emits nothing for it. The turn ends here, with no answer shared.
840
+ // Known delivery disposition is independent of native readiness. Never expose an idle gap to Bus.onState.
570
841
  this.owner = undefined;
571
842
  this.abortApprovals();
572
- this.failTurn(why ?? "a hub deny cancelled the Qwen turn (Qwen emits nothing for it); the turn ended without an answer", false, true);
843
+ this.failTurn(why ?? "a hub deny cancelled the Qwen turn without an answer; input remains fenced until a personal turn completes or a new Qwen generation starts", true, true);
844
+ this.clearWatchdog();
845
+ this.denyTimer = setTimeout(() => {
846
+ if (!this.state_.denyPending || this.stopping) return;
847
+ this.setState("offline");
848
+ try { this.opts.onNotice?.(`${this.id}: ${this.denyStorageFailure ? QWEN_DENY_STORAGE_NOTE : QWEN_DENY_QUIESCENCE_NOTE}`); } catch { /* notice only */ }
849
+ }, this.opts.denyQuiescenceMs ?? QWEN_DENY_QUIESCENCE_MS);
850
+ this.denyTimer.unref?.();
573
851
  }
574
852
 
575
853
  private onControlResponse(event: Json): void {
@@ -590,6 +868,8 @@ export class QwenDualPeer extends BasePeer {
590
868
  async stop(reason?: string): Promise<void> {
591
869
  if (reason !== undefined) this.requestedStopReason = reason;
592
870
  this.stopping = true;
871
+ if (this.denyTimer) clearTimeout(this.denyTimer); this.denyTimer = undefined;
872
+ this.discardReadProof();
593
873
  if (this.poller) clearInterval(this.poller); this.poller = undefined;
594
874
  if (this.monitor) clearInterval(this.monitor); this.monitor = undefined;
595
875
  this.abortApprovals();