@gamaze/hicortex 0.22.3 → 0.23.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.
package/dist/mcp-stdio.js CHANGED
@@ -43,6 +43,27 @@
43
43
  * port: explicit error, never a spawn. A remote target that is down is
44
44
  * likewise an explicit error — we never spawn for remote URLs.
45
45
  *
46
+ * Startup retry (#501): a REMOTE target that is unreachable at launch is
47
+ * TRANSIENT, not fatal — the product case is a client (e.g. Claude Desktop
48
+ * auto-launched at login) starting before the VPN/DNS that carries the
49
+ * server URL is up (ENOTFOUND/EAI_AGAIN/ECONNREFUSED/timeouts). The bridge
50
+ * then keeps the stdio side ALIVE and answers `initialize` IMMEDIATELY
51
+ * (design B), retrying the upstream connect with backoff (1s→2s→4s… capped
52
+ * 10s) for a 60s window. Why answer immediately: MCP clients cancel a
53
+ * pending `initialize` at ~60s (TS SDK DEFAULT_REQUEST_TIMEOUT_MSEC;
54
+ * Claude Desktop observed cancelling at ~60s in the wild) — a delayed
55
+ * initialize would lose the session the retry window is meant to save, and
56
+ * the first tools/list request carries the same ~60s client budget, so the
57
+ * window deliberately stays at the BOTTOM of the 60–90s range the issue
58
+ * proposed (evidence + decision: issue #501 design-note comment). The
59
+ * daemon's initialize-result `instructions` are unknowable while it is down
60
+ * and are therefore omitted on this path (the pre-#383 shape); tools
61
+ * handlers await upstream readiness. NEVER retried: 401/403 (auth is not
62
+ * transient — existing HICORTEX_AUTH_TOKEN hint) and a reachable-but-not-
63
+ * healthy endpoint (foreign service). Local targets keep the autostart poll
64
+ * (which already waits 30s). Mid-session SSE reconnect after an established
65
+ * connection drops is OUT OF SCOPE (#501 follow-up).
66
+ *
46
67
  * STDIO DISCIPLINE: stdout carries ONLY the MCP protocol. Every diagnostic
47
68
  * goes to stderr; fatal errors are a one-liner on stderr + non-zero exit
48
69
  * (thrown to cli.ts's catch). Cancellation downstream→upstream rides the
@@ -59,6 +80,9 @@ exports.resolveBridgeToken = resolveBridgeToken;
59
80
  exports.probeHealthOnce = probeHealthOnce;
60
81
  exports.decideAutostart = decideAutostart;
61
82
  exports.ensureDaemonReady = ensureDaemonReady;
83
+ exports.classifyStartupFailure = classifyStartupFailure;
84
+ exports.nextRetryDelayMs = nextRetryDelayMs;
85
+ exports.defaultConnectUpstream = defaultConnectUpstream;
62
86
  exports.runMcpStdio = runMcpStdio;
63
87
  const node_child_process_1 = require("node:child_process");
64
88
  const node_fs_1 = require("node:fs");
@@ -83,6 +107,14 @@ const DEFAULT_BRIDGE_PORT = 8787;
83
107
  const HEALTH_PROBE_TIMEOUT_MS = 2000;
84
108
  const AUTOSTART_POLL_INTERVAL_MS = 250;
85
109
  const AUTOSTART_POLL_TOTAL_MS = 30_000;
110
+ // #501 startup-retry window. 60s — the bottom of the issue's 60–90s proposal,
111
+ // deliberately: the client's own request timeout (TS SDK default, and Claude
112
+ // Desktop's observed initialize cancel) is 60s, and under design B the FIRST
113
+ // tools/list inherits that same budget, so a longer window would only answer
114
+ // requests the client has already abandoned.
115
+ const REMOTE_RETRY_WINDOW_MS = 60_000;
116
+ const REMOTE_RETRY_BASE_DELAY_MS = 1_000;
117
+ const REMOTE_RETRY_MAX_DELAY_MS = 10_000;
86
118
  /** Loopback check for URL hostnames (Node's URL keeps the brackets on [::1]). */
87
119
  function isLoopbackHost(hostname) {
88
120
  return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1" || hostname === "[::1]";
@@ -160,6 +192,13 @@ async function probeHealthOnce(url, timeoutMs = HEALTH_PROBE_TIMEOUT_MS) {
160
192
  return { reachable: false, ok: false };
161
193
  }
162
194
  }
195
+ /** The clear unreachable message — shared by the fail-fast path and the #501
196
+ * retry-window expiry, so both ends of the window say the same thing. */
197
+ function remoteUnreachableMessage(target) {
198
+ return (`Cannot reach the Hicortex server at ${target.url}. Start it on the server machine ` +
199
+ `(check with \`hicortex status\`, start with \`npx @gamaze/hicortex server\`) or fix HICORTEX_SERVER_URL. ` +
200
+ `If it answers 401 once up, set HICORTEX_AUTH_TOKEN to the server's auth token.`);
201
+ }
163
202
  /**
164
203
  * Pure decision from one health probe: healthy → bridge; refused + loopback
165
204
  * → spawn a local daemon; refused + remote → fail with an actionable message
@@ -177,14 +216,8 @@ function decideAutostart(probe, target) {
177
216
  `then either free the port or point HICORTEX_SERVER_URL at the real Hicortex server.`,
178
217
  };
179
218
  }
180
- if (!target.local) {
181
- return {
182
- action: "fail",
183
- reason: `Cannot reach the Hicortex server at ${target.url}. Start it on the server machine ` +
184
- `(check with \`hicortex status\`, start with \`npx @gamaze/hicortex server\`) or fix HICORTEX_SERVER_URL. ` +
185
- `If it answers 401 once up, set HICORTEX_AUTH_TOKEN to the server's auth token.`,
186
- };
187
- }
219
+ if (!target.local)
220
+ return { action: "fail", reason: remoteUnreachableMessage(target) };
188
221
  return { action: "spawn" };
189
222
  }
190
223
  /**
@@ -234,49 +267,135 @@ async function ensureDaemonReady(target, options = {}) {
234
267
  `${Math.round(totalMs / 1000)}s of autostart. Try \`npx @gamaze/hicortex server\` in a terminal ` +
235
268
  `to see the daemon's startup error, then re-run this command.`);
236
269
  }
270
+ /** Node/undici errno codes a "network not up yet" boot race produces. */
271
+ const TRANSIENT_ERRNO_RE = /\b(?:ENOTFOUND|EAI_AGAIN|ECONNREFUSED|ECONNRESET|ETIMEDOUT|EHOSTUNREACH|ENETUNREACH|UND_ERR_CONNECT_TIMEOUT)\b/;
272
+ /** SseError carries the HTTP status on .code (SDK client/sse.js). */
273
+ function isAuthRejection(err) {
274
+ const code = err?.code;
275
+ return code === 401 || code === 403 || code === "401" || code === "403";
276
+ }
237
277
  /**
238
- * Run the stdio MCP bridge. Resolves only after the downstream transport
239
- * closes (the lifecycle handlers then exit the process); every setup failure
240
- * throws for cli.ts to report on stderr and exit 1.
278
+ * A network-level failure that a retry window can plausibly outlive: walk the
279
+ * error + its cause chain for a transient errno, a fetch/undici timeout name,
280
+ * or errno text embedded in the message (SseError has no `cause` — the SDK
281
+ * puts the underlying text straight into `SSE error: getaddrinfo ENOTFOUND …`).
241
282
  */
242
- async function runMcpStdio(options = {}) {
243
- const target = resolveBridgeTarget(options.serverUrl);
244
- const token = resolveBridgeToken(options.authToken);
245
- await ensureDaemonReady(target, options);
246
- // Upstream: the daemon's SSE MCP endpoint. requestInit headers ride BOTH
247
- // the GET /sse and the POST /messages (SDK 1.28 _commonHeaders/send).
283
+ function isTransientNetworkError(err) {
284
+ let current = err;
285
+ for (let depth = 0; depth < 5 && current instanceof Error; depth += 1) {
286
+ const code = current.code;
287
+ if (typeof code === "string" && TRANSIENT_ERRNO_RE.test(code))
288
+ return true;
289
+ if (current.name === "TimeoutError" || current.name === "AbortError")
290
+ return true;
291
+ if (TRANSIENT_ERRNO_RE.test(current.message))
292
+ return true;
293
+ current = current.cause;
294
+ }
295
+ return false;
296
+ }
297
+ /**
298
+ * Classify a startup failure of the upstream connect sequence. Only a REMOTE
299
+ * target's network-level failure is transient (#501); auth rejections and a
300
+ * reachable-but-unhealthy endpoint are fatal immediately, and local targets
301
+ * keep their own autostart-poll semantics.
302
+ */
303
+ function classifyStartupFailure(err, target) {
304
+ if (isAuthRejection(err))
305
+ return "auth";
306
+ const message = err instanceof Error ? err.message : String(err);
307
+ if (/not a healthy Hicortex/i.test(message))
308
+ return "foreign";
309
+ if (target.local)
310
+ return "fatal";
311
+ // decideAutostart's remote-unreachable reason is the probe-level shape of
312
+ // every refused/DNS-failed/timeout probe (probeHealthOnce collapses them).
313
+ if (message.startsWith("Cannot reach the Hicortex server"))
314
+ return "transient";
315
+ return isTransientNetworkError(err) ? "transient" : "fatal";
316
+ }
317
+ /** Backoff step N (0-based): base·2^N, capped — 1s, 2s, 4s, 8s, then the cap. */
318
+ function nextRetryDelayMs(attempt, baseMs, maxMs) {
319
+ return Math.min(baseMs * 2 ** attempt, maxMs);
320
+ }
321
+ /** One-line reason for the stderr retry log — never the full fail message. */
322
+ function summarizeStartupFailure(err) {
323
+ const message = err instanceof Error ? err.message : String(err);
324
+ const errno = TRANSIENT_ERRNO_RE.exec(message)?.[0];
325
+ if (errno)
326
+ return errno;
327
+ if (message.startsWith("Cannot reach the Hicortex server"))
328
+ return "unreachable";
329
+ return message.length > 80 ? `${message.slice(0, 77)}…` : message;
330
+ }
331
+ /** The friendly fatal form: auth rejections get the token hint, the rest pass
332
+ * through unchanged (their messages are already the actionable ones). */
333
+ function toStartupError(err, target) {
334
+ if (isAuthRejection(err)) {
335
+ const status = err.code;
336
+ return new Error(`The Hicortex server at ${target.url} rejected the connection (${status}). ` +
337
+ `Set HICORTEX_AUTH_TOKEN to the server's auth token — it is printed by \`hicortex status\` on the server box.`);
338
+ }
339
+ return err instanceof Error ? err : new Error(String(err));
340
+ }
341
+ /**
342
+ * Connect the upstream Client to the daemon's SSE MCP endpoint. requestInit
343
+ * headers ride BOTH the GET /sse and the POST /messages (SDK 1.28
344
+ * _commonHeaders/send). Raw errors propagate — classification happens at the
345
+ * call site. Exported for the ghost-reconnect unit test.
346
+ *
347
+ * On failure the transport is closed EXPLICITLY: the SDK's Client.connect
348
+ * closes only when the initialize REQUEST fails after a successful start —
349
+ * a failed transport.start() (refused/DNS) propagates out of Protocol.connect
350
+ * with no cleanup, and the still-open EventSource keeps eventsource's ~3s
351
+ * reconnect loop alive. Every retry attempt would leak one ghost that, once
352
+ * the server appears, opens a REAL authed SSE session on the daemon and is
353
+ * never closed (proven empirically on SDK 1.28.0 / eventsource 3.0.7, PR
354
+ * review round 1 — pinned by the ghost-reconnect unit test).
355
+ */
356
+ async function defaultConnectUpstream(target, token) {
248
357
  const upstream = new sse_js_1.SSEClientTransport(new URL(`${target.url}/sse`), token !== undefined ? { requestInit: { headers: { Authorization: `Bearer ${token}` } } } : {});
249
358
  const client = new index_js_2.Client({ name: "hicortex-mcp-bridge", version: VERSION });
250
359
  try {
251
360
  await client.connect(upstream);
252
361
  }
253
362
  catch (err) {
254
- // 401 from the daemon's auth middleware (remote connections; loopback is
255
- // exempt). SseError carries the HTTP status as .code.
256
- if (err.code === 401) {
257
- throw new Error(`The Hicortex server at ${target.url} rejected the connection (401). ` +
258
- `Set HICORTEX_AUTH_TOKEN to the server's auth token — it is printed by \`hicortex status\` on the server box.`);
259
- }
260
- throw err instanceof Error ? err : new Error(String(err));
363
+ await client.close().catch(() => { });
364
+ throw err;
261
365
  }
262
- // Downstream: a low-level Server over stdio advertising exactly what the
263
- // daemon offers (tools). Ping is auto-answered by the Protocol base.
264
- // #383: forward the DAEMON's initialize-result instructions verbatim — the
265
- // daemon owns the text and the memoryInstructions gate, so the two surfaces
266
- // cannot diverge and no config read is duplicated in the bridge (a
267
- // pre-#383 remote daemon simply has none to forward; undefined omits the
268
- // field from the bridge's own initialize result).
269
- const server = new index_js_1.Server({ name: "hicortex", version: VERSION }, { capabilities: { tools: {} }, instructions: client.getInstructions() });
366
+ return client;
367
+ }
368
+ /**
369
+ * The downstream Server: a low-level Server over stdio advertising exactly
370
+ * what the daemon offers (tools). Ping is auto-answered by the Protocol
371
+ * base. #383: `instructions` is the DAEMON's initialize-result text,
372
+ * forwarded verbatim — undefined (pre-#383 daemon, memoryInstructions off,
373
+ * or the #501 slow path where the daemon has not answered yet) omits the
374
+ * field. `awaitClient` yields the upstream Client a tools request should
375
+ * use — already-resolved on the fast path, a readiness promise on the slow
376
+ * path, so tools requests queue until the server exists.
377
+ */
378
+ function createBridgeServer(instructions, awaitClient) {
379
+ const server = new index_js_1.Server({ name: "hicortex", version: VERSION }, instructions !== undefined ? { capabilities: { tools: {} }, instructions } : { capabilities: { tools: {} } });
270
380
  // The proxy core — the SDK's documented proxy pattern. Forward the two
271
381
  // tools requests and pass extra.signal through so a downstream
272
382
  // notifications/cancelled aborts the upstream call (which emits the
273
383
  // correctly-id'd cancellation to the daemon). Nothing else is forwarded
274
384
  // request-wise: the daemon is tools-only and the base class answers ping.
275
- server.setRequestHandler(types_js_1.ListToolsRequestSchema, async (_request, extra) => (await client.listTools(undefined, { signal: extra.signal })));
276
- server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request, extra) => (await client.callTool(request.params, undefined, { signal: extra.signal })));
277
- // Upstream → downstream notifications, best-effort: the daemon's tool-list
278
- // changes or log messages reach the client; a closed far end must not kill
279
- // the bridge from inside a notification handler.
385
+ server.setRequestHandler(types_js_1.ListToolsRequestSchema, async (_request, extra) => {
386
+ const client = await awaitClient();
387
+ return (await client.listTools(undefined, { signal: extra.signal }));
388
+ });
389
+ server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request, extra) => {
390
+ const client = await awaitClient();
391
+ return (await client.callTool(request.params, undefined, { signal: extra.signal }));
392
+ });
393
+ return server;
394
+ }
395
+ /** Upstream → downstream notifications, best-effort: the daemon's tool-list
396
+ * changes or log messages reach the client; a closed far end must not kill
397
+ * the bridge from inside a notification handler. */
398
+ function forwardNotifications(client, server) {
280
399
  client.fallbackNotificationHandler = async (notification) => {
281
400
  try {
282
401
  await server.notification(notification);
@@ -285,29 +404,131 @@ async function runMcpStdio(options = {}) {
285
404
  // Best-effort by design.
286
405
  }
287
406
  };
288
- // Lifecycle: whichever side ends first tears down the other. The `exiting`
289
- // guard keeps our OWN client.close() (graceful path) from being read as an
290
- // upstream loss.
407
+ }
408
+ /**
409
+ * Lifecycle: whichever side ends first tears down the other. The `exiting`
410
+ * guard keeps our OWN client.close() (graceful path) from being read as an
411
+ * upstream loss. The upstream attaches late on the #501 slow path, hence
412
+ * attachUpstream() instead of a constructor argument.
413
+ */
414
+ function wireBridgeLifecycle(server) {
291
415
  let exiting = false;
416
+ let upstream;
292
417
  const shutdown = (code) => {
293
418
  if (exiting)
294
419
  return;
295
420
  exiting = true;
296
- void Promise.allSettled([server.close(), client.close()]).then(() => process.exit(code));
421
+ const closing = [server.close()];
422
+ if (upstream)
423
+ closing.push(upstream.close());
424
+ void Promise.allSettled(closing).then(() => process.exit(code));
297
425
  };
298
426
  // Downstream closed (the MCP client went away) → close upstream → exit 0.
299
427
  server.onclose = () => shutdown(0);
300
- // Upstream transport died → the bridge cannot serve anything → exit 1.
301
- client.onclose = () => {
302
- if (exiting)
303
- return;
304
- console.error("[hicortex] mcp: lost the connection to the Hicortex server");
305
- shutdown(1);
306
- };
307
428
  process.once("SIGINT", () => shutdown(0));
308
429
  process.once("SIGTERM", () => shutdown(0));
309
- const downstream = options.downstream ?? new stdio_js_1.StdioServerTransport();
310
- await server.connect(downstream);
311
- // Diagnostics NEVER touch stdout (the MCP wire) — stderr only.
430
+ return {
431
+ shutdown,
432
+ attachUpstream(client) {
433
+ upstream = client;
434
+ // Upstream transport died → the bridge cannot serve anything → exit 1.
435
+ client.onclose = () => {
436
+ if (exiting)
437
+ return;
438
+ console.error("[hicortex] mcp: lost the connection to the Hicortex server");
439
+ shutdown(1);
440
+ };
441
+ },
442
+ };
443
+ }
444
+ /**
445
+ * Run the stdio MCP bridge. Fast path (daemon reachable now): connect
446
+ * upstream first, then serve stdio with the daemon's forwarded instructions
447
+ * — exactly the pre-#501 sequence. Slow path (REMOTE target, transient
448
+ * network failure — the boot race): serve stdio IMMEDIATELY (design B,
449
+ * initialize answered at once) and retry the upstream connect with backoff
450
+ * for the retry window. Resolves once bridging is established; every setup
451
+ * failure throws for cli.ts to report on stderr and exit 1.
452
+ */
453
+ async function runMcpStdio(options = {}) {
454
+ const target = resolveBridgeTarget(options.serverUrl);
455
+ const token = resolveBridgeToken(options.authToken);
456
+ const connect = options.connectUpstream ?? defaultConnectUpstream;
457
+ // ---- Fast path: the daemon answers now. ----
458
+ let firstFailure;
459
+ let upstream;
460
+ try {
461
+ await ensureDaemonReady(target, options);
462
+ upstream = await connect(target, token);
463
+ }
464
+ catch (err) {
465
+ if (classifyStartupFailure(err, target) !== "transient")
466
+ throw toStartupError(err, target);
467
+ firstFailure = err;
468
+ }
469
+ if (upstream) {
470
+ const server = createBridgeServer(upstream.getInstructions(), async () => upstream);
471
+ const lifecycle = wireBridgeLifecycle(server);
472
+ lifecycle.attachUpstream(upstream);
473
+ forwardNotifications(upstream, server);
474
+ await server.connect(options.downstream ?? new stdio_js_1.StdioServerTransport());
475
+ // Diagnostics NEVER touch stdout (the MCP wire) — stderr only.
476
+ console.error(`[hicortex] mcp: bridging stdio <-> ${target.url}/sse (target: ${target.source})`);
477
+ return;
478
+ }
479
+ // ---- Slow path (#501): remote + transient — answer initialize now,
480
+ // retry the upstream in the background, keep stdio alive throughout. ----
481
+ const windowMs = options.retryWindowMs ?? REMOTE_RETRY_WINDOW_MS;
482
+ const baseDelayMs = options.retryBaseDelayMs ?? REMOTE_RETRY_BASE_DELAY_MS;
483
+ const maxDelayMs = options.retryMaxDelayMs ?? REMOTE_RETRY_MAX_DELAY_MS;
484
+ let resolveReady;
485
+ let rejectReady;
486
+ const upstreamReady = new Promise((resolve, reject) => {
487
+ resolveReady = resolve;
488
+ rejectReady = reject;
489
+ });
490
+ // Mark handled: if the window expires before any tools request arrived,
491
+ // rejecting an un-awaited promise would crash the process as an unhandled
492
+ // rejection.
493
+ upstreamReady.catch(() => { });
494
+ const server = createBridgeServer(undefined, () => upstreamReady);
495
+ const lifecycle = wireBridgeLifecycle(server);
496
+ await server.connect(options.downstream ?? new stdio_js_1.StdioServerTransport());
312
497
  console.error(`[hicortex] mcp: bridging stdio <-> ${target.url}/sse (target: ${target.source})`);
498
+ console.error(`[hicortex] mcp: Hicortex server at ${target.url} unreachable at startup ` +
499
+ `(${summarizeStartupFailure(firstFailure)}) — retrying for up to ${Math.round(windowMs / 1000)}s ` +
500
+ `while the network comes up; the connection stays open and tools wait for the server`);
501
+ const deadline = Date.now() + windowMs;
502
+ let attempt = 0;
503
+ let lastFailure = firstFailure;
504
+ for (;;) {
505
+ const remainingMs = deadline - Date.now();
506
+ if (remainingMs <= 0) {
507
+ rejectReady(new Error(remoteUnreachableMessage(target)));
508
+ throw new Error(remoteUnreachableMessage(target));
509
+ }
510
+ const delayMs = Math.min(nextRetryDelayMs(attempt, baseDelayMs, maxDelayMs), remainingMs);
511
+ console.error(`[hicortex] mcp: retrying ${target.url} in ${delayMs}ms ` +
512
+ `(attempt ${attempt + 1}, ${Math.ceil(remainingMs / 1000)}s of window left) after: ${summarizeStartupFailure(lastFailure)}`);
513
+ await sleep(delayMs);
514
+ attempt += 1;
515
+ try {
516
+ await ensureDaemonReady(target, { probeHealth: options.probeHealth });
517
+ const client = await connect(target, token);
518
+ // Established — from here the lifecycle is exactly the fast path's.
519
+ lifecycle.attachUpstream(client);
520
+ forwardNotifications(client, server);
521
+ resolveReady(client);
522
+ console.error(`[hicortex] mcp: server reachable after ${attempt} retry${attempt === 1 ? "" : "ies"} — serving tools`);
523
+ return;
524
+ }
525
+ catch (err) {
526
+ const kind = classifyStartupFailure(err, target);
527
+ if (kind === "auth")
528
+ throw toStartupError(err, target);
529
+ if (kind !== "transient")
530
+ throw err;
531
+ lastFailure = err;
532
+ }
533
+ }
313
534
  }
package/dist/nightly.js CHANGED
@@ -782,13 +782,11 @@ async function runNightly(options = {}) {
782
782
  // #408: weakPrimaryFloor is a release-managed calibration
783
783
  // constant now — no config threading; the Options field stays
784
784
  // as the eval/test seam.
785
- }, {
786
- // #405: no supersessionMaxCalls — the ONE run budget is the
787
- // only call cap. #408: minSimilarity defaults to the
788
- // calibration constant (seam only).
789
785
  },
790
786
  // #405: the ONE per-run LLM-call ceiling (default 5000;
791
787
  // consolidateMaxLlmCalls honored as a deprecated alias).
788
+ // (#206-B: the retired supersession stage's options slot sat
789
+ // here — removed with the stage; true-update detection is 3.8's.)
792
790
  (0, consolidate_js_1.resolveNightlyLlmCallBudget)(savedConfig),
793
791
  // #245: soft cap on the corpus (default 10000; 0 disables eviction).
794
792
  memorySoftCapResolved, {
@@ -17,6 +17,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
17
17
  exports.buildHookRequest = buildHookRequest;
18
18
  exports.runRecallHook = runRecallHook;
19
19
  const learnings_identity_js_1 = require("./learnings-identity.js");
20
+ const wrapper_prompt_js_1 = require("./wrapper-prompt.js");
20
21
  const node_path_1 = require("node:path");
21
22
  const FETCH_TIMEOUT_MS = 1000;
22
23
  /** Read all of stdin (CC pipes the hook payload JSON). */
@@ -44,6 +45,15 @@ function buildHookRequest(payload, cwd = process.cwd()) {
44
45
  const prompt = typeof payload.prompt === "string" ? payload.prompt : "";
45
46
  if (!prompt)
46
47
  return null;
48
+ // #489: a pure plumbing payload (task-notification without a report result,
49
+ // command envelope, caveat, stdout echo, bare system-reminder) produces NO
50
+ // request at all — no HTTP call, so the 1000 ms hook budget is spent on
51
+ // real prompts only. A wrapper CARRYING prose (agent-message hand-back,
52
+ // report <result>, user text around the wrapper) recalls on the full text
53
+ // (owner decision 4) — the shared classifier, same function the server
54
+ // guards with (wrapper-prompt.ts).
55
+ if ((0, wrapper_prompt_js_1.isPureWrapperPrompt)(prompt))
56
+ return null;
47
57
  // #203 scope: derive project from the session cwd so retrieval can apply a
48
58
  // soft project-affinity boost. basename(cwd) matches capture's
49
59
  // decodeProjectDirName for non-hyphenated dirs (the common case); a hyphen
@@ -93,6 +93,7 @@ exports.handleRecallIndex = handleRecallIndex;
93
93
  exports.handleMemoryGet = handleMemoryGet;
94
94
  exports.formatMemoryGetText = formatMemoryGetText;
95
95
  const storage = __importStar(require("./storage.js"));
96
+ const wrapper_prompt_js_1 = require("./wrapper-prompt.js");
96
97
  const type_labels_js_1 = require("./type-labels.js");
97
98
  const retrieval_js_1 = require("./retrieval.js");
98
99
  const CALIBRATION = __importStar(require("./calibration.js"));
@@ -321,6 +322,17 @@ async function handleRecallIndex(deps, body) {
321
322
  return { status: 200, body: { ok: true, reset: true } };
322
323
  }
323
324
  const prompt = typeof req.prompt === "string" ? req.prompt.trim() : "";
325
+ // #489 wrapper guard — the short-prompt gate's slot, BEFORE beginTurn and
326
+ // before any precision recording, so a pure plumbing payload (CC delivers
327
+ // task-notifications/command envelopes as user-role messages; any client
328
+ // could POST one) gets {block: null} with NO recall_pushes row, NO turn
329
+ // burn, NO shown_count bump, NO last_accessed refresh. The SAME shared
330
+ // classifier the hook client guards with (wrapper-prompt.ts) — defense in
331
+ // depth. A wrapper carrying real payload prose falls through and recalls on
332
+ // the full text, exactly today's behavior (owner decision 4).
333
+ if ((0, wrapper_prompt_js_1.isPureWrapperPrompt)(prompt)) {
334
+ return { status: 200, body: { block: null, skipped: "wrapper-prompt" } };
335
+ }
324
336
  const minPromptLength = deps.options?.minPromptLength ?? DEFAULT_MIN_PROMPT_LENGTH;
325
337
  if (prompt.length < minPromptLength) {
326
338
  return { status: 200, body: { block: null, skipped: "short-prompt" } };
@@ -2,7 +2,7 @@
2
2
  * Reconsolidation (#384, #392) — the store resolves its own corrections, and
3
3
  * THE unified resolution stage.
4
4
  *
5
- * Nightly consolidation stage (runs as Stage 3.8, after supersession, before
5
+ * Nightly consolidation stage (runs as Stage 3.8, after links, before
6
6
  * decay/prune) that detects memories which correct, retract, supersede, or
7
7
  * DUPLICATE older ones; REWRITES corrected facts in place (absorbing
8
8
  * transition-only trigger memories), MERGES confirmed duplicates via the
@@ -44,8 +44,9 @@
44
44
  * planDedup and the judged mergeMemoryIds) refuse to blend a conflicts-linked
45
45
  * pair, counted as conflict_skipped. The zone therefore runs AFTER the scan —
46
46
  * with the zone first, a >=0.92 conflict pair was blended
47
- * before the judge ever saw it (the planted-eval harm: canonical=older, the
48
- * newer truth erased); running it last means verdicts/marks/binds land first
47
+ * before the judge ever saw it (the planted-eval harm: an unjudged blend —
48
+ * whichever row lost the canonical pick, its wording was simply erased);
49
+ * running it last means verdicts/marks/binds land first
49
50
  * and the zone merges only what no verdict claimed — a conflicts bind set by
50
51
  * this run's scan guards the SAME run's zone.
51
52
  *
@@ -94,10 +95,14 @@ export declare const RECONSOLIDATION_STAGE_LABEL = "reconsolidation";
94
95
  /**
95
96
  * Default minimum COSINE similarity for a correction candidate pair —
96
97
  * RELEASE-MANAGED since #408 (calibration.ts CORRECTION_MIN_SIMILARITY;
97
- * provenance there). Lower than the supersession stage's 0.80 on purpose: a
98
- * retraction often rides inside an otherwise unrelated memory (the field
99
- * failure that opened this issue), so the neighborhood gate must be a touch
100
- * wider while the LLM verdict + confidence gate carry the precision load.
98
+ * provenance there). Deliberately wide: a retraction often rides inside an
99
+ * otherwise unrelated memory (the field failure that opened this issue), so
100
+ * the neighborhood gate must be a touch wider while the LLM verdict +
101
+ * confidence gate carry the precision load. Since #206-B (owner decision 6)
102
+ * this floor also subsumes the retired Stage 3.7 supersession scan's 0.80:
103
+ * 3.8 is the ONLY true-update detector, scanning every new memory — no
104
+ * shape gate, wider floor — with `corrects`/`supersedes` partitioning what
105
+ * 3.7's binary prompt called a supersession.
101
106
  */
102
107
  export declare const DEFAULT_CORRECTION_MIN_SIMILARITY = 0.75;
103
108
  /**
@@ -193,7 +198,7 @@ export interface ScoutShape {
193
198
  }
194
199
  /**
195
200
  * Build the constrained correction-shape prompt (classify-tier cost profile:
196
- * 1500-char truncation, supersession/verdict precedent). The wording asks for
201
+ * 1500-char truncation, verdict-prompt precedent). The wording asks for
197
202
  * the OLD claim's distinctive terms — the field-failure mechanism is that a
198
203
  * correction CONTAINS the words of what it corrects, even when the surrounding
199
204
  * topics (and therefore the embedding cosine) are unrelated. Guard-C extends
@@ -204,13 +209,14 @@ export declare function buildScoutShapePrompt(content: string): string;
204
209
  /**
205
210
  * Parse the scout shape reply. Null on unparseable JSON, a missing/non-boolean
206
211
  * `correction`, or a missing/out-of-range `confidence` — the caller counts
207
- * skipped_infra and moves on (parseSupersessionReply discipline: never
212
+ * skipped_infra and moves on (the retired supersession stage's parse
213
+ * discipline, kept: never
208
214
  * mis-detect on ambiguity). `references` is lenient (missing/non-string → "")
209
215
  * because an empty string simply yields no FTS hits — a harmless miss, not a
210
216
  * mis-judgment.
211
217
  */
212
218
  export declare function parseScoutShape(reply: string): ScoutShape | null;
213
- /** Build the constrained pair-verdict prompt (1500-char truncation, supersession precedent). */
219
+ /** Build the constrained pair-verdict prompt (1500-char truncation). */
214
220
  export declare function buildCorrectionVerdictPrompt(oldContent: string, newContent: string): string;
215
221
  export interface CorrectionVerdict {
216
222
  action: ResolutionAction;
@@ -219,7 +225,7 @@ export interface CorrectionVerdict {
219
225
  /**
220
226
  * Parse the pair verdict. Null on anything unparseable, unknown action, or an
221
227
  * out-of-range/missing confidence — the caller counts skipped_infra and moves
222
- * on (same discipline as parseSupersessionReply: never mis-judge on ambiguity).
228
+ * on (the same never-mis-judge-on-ambiguity discipline).
223
229
  */
224
230
  export declare function parseCorrectionVerdict(reply: string): CorrectionVerdict | null;
225
231
  export interface RewriteTriggerDisposition {