@dzhechkov/harness-core 0.8.32 → 0.8.34

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 (63) hide show
  1. package/.dz-manifest.json +107 -47
  2. package/README.md +108 -0
  3. package/dist/agentdb-index.d.ts +17 -6
  4. package/dist/agentdb-index.d.ts.map +1 -1
  5. package/dist/agentdb-index.js +61 -17
  6. package/dist/agentdb-index.js.map +1 -1
  7. package/dist/apply-leg.d.ts +68 -5
  8. package/dist/apply-leg.d.ts.map +1 -1
  9. package/dist/apply-leg.js +466 -37
  10. package/dist/apply-leg.js.map +1 -1
  11. package/dist/embed-socket-path.d.ts +65 -0
  12. package/dist/embed-socket-path.d.ts.map +1 -0
  13. package/dist/embed-socket-path.js +100 -0
  14. package/dist/embed-socket-path.js.map +1 -0
  15. package/dist/index.d.ts +11 -4
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +9 -3
  18. package/dist/index.js.map +1 -1
  19. package/dist/operations.d.ts.map +1 -1
  20. package/dist/operations.js +105 -3
  21. package/dist/operations.js.map +1 -1
  22. package/dist/packed-install-smoke.d.ts +108 -0
  23. package/dist/packed-install-smoke.d.ts.map +1 -0
  24. package/dist/packed-install-smoke.js +172 -0
  25. package/dist/packed-install-smoke.js.map +1 -0
  26. package/dist/publish-sibling-drift.d.ts +139 -0
  27. package/dist/publish-sibling-drift.d.ts.map +1 -0
  28. package/dist/publish-sibling-drift.js +408 -0
  29. package/dist/publish-sibling-drift.js.map +1 -0
  30. package/dist/publish.d.ts +44 -0
  31. package/dist/publish.d.ts.map +1 -1
  32. package/dist/publish.js +243 -24
  33. package/dist/publish.js.map +1 -1
  34. package/dist/qe-bridge.d.ts +16 -0
  35. package/dist/qe-bridge.d.ts.map +1 -1
  36. package/dist/qe-bridge.js +1 -0
  37. package/dist/qe-bridge.js.map +1 -1
  38. package/dist/release.d.ts +91 -0
  39. package/dist/release.d.ts.map +1 -1
  40. package/dist/release.js +317 -21
  41. package/dist/release.js.map +1 -1
  42. package/dist/setup.d.ts +36 -0
  43. package/dist/setup.d.ts.map +1 -1
  44. package/dist/setup.js +96 -2
  45. package/dist/setup.js.map +1 -1
  46. package/dist/vector-tier.d.ts +27 -2
  47. package/dist/vector-tier.d.ts.map +1 -1
  48. package/dist/vector-tier.js +112 -3
  49. package/dist/vector-tier.js.map +1 -1
  50. package/package.json +23 -23
  51. package/sbom.json +196 -46
  52. package/src/agentdb-index.ts +65 -17
  53. package/src/apply-leg.ts +461 -37
  54. package/src/embed-socket-path.ts +113 -0
  55. package/src/index.ts +44 -3
  56. package/src/operations.ts +104 -3
  57. package/src/packed-install-smoke.ts +273 -0
  58. package/src/publish-sibling-drift.ts +498 -0
  59. package/src/publish.ts +280 -25
  60. package/src/qe-bridge.ts +14 -0
  61. package/src/release.ts +366 -19
  62. package/src/setup.ts +108 -2
  63. package/src/vector-tier.ts +147 -5
package/dist/apply-leg.js CHANGED
@@ -27,8 +27,87 @@
27
27
  * @packageDocumentation
28
28
  */
29
29
  import { existsSync, readFileSync } from 'node:fs';
30
+ import { connect as netConnect } from 'node:net';
30
31
  import { join } from 'node:path';
31
32
  import { hookCommandsOf } from './managed-hooks.js';
33
+ /**
34
+ * FR-6 (feature `hook-recall-hybrid-parity`, ADR-001 C-4): send ONE `op: recall` probe to a LIVE
35
+ * embed daemon socket and report the `engine` it answers with (`'hybrid'` | `'cosine-fallback'`) —
36
+ * `dz doctor` prints this so an operator can SEE which engine is actually serving prompts, rather
37
+ * than trusting the daemon's mere presence. Honest-degrade contract, matching every other doctor
38
+ * probe: a non-socket path (e.g. a plain file, as every non-live doctor fixture in this repo uses),
39
+ * a connection error, an unparsable reply, or a timeout all resolve to `undefined` — NEVER a thrown
40
+ * error, and never distinguishable from "no daemon" in the caller's output (the existing "socket
41
+ * present/absent" line already carries that half of the truth).
42
+ *
43
+ * `timeoutMs` defaults to 1000 ms — comfortably above the documented `HOOK_RECALL_BUDGET_MS` default
44
+ * (500 ms): under that default, a cold `recallHybrid` semantic leg routinely exceeds the budget in
45
+ * this environment (MEASURED — see the manifest's NFR-1 discussion), so the daemon's OWN answer
46
+ * time is closer to ~500-550 ms than to the socket round-trip cost alone; a shorter probe timeout
47
+ * would silently miss a live, correctly-answering daemon and report no engine at all.
48
+ *
49
+ * AM-8 (fix round 1): lives HERE, not in `operations.ts` — this module already owns the daemon's
50
+ * wire protocol (`recallHookSource`/`embedDaemonSource`'s generated `op: recall` handshake) and its
51
+ * socket-path resolution; `operations.ts`'s `runDoctor` reaches it via a dynamic `import()`
52
+ * (matching its existing `embed-socket-path.js` import one line above the call site) rather than
53
+ * duplicating a second, independent `node:net` IO surface in a file whose job is orchestration, not
54
+ * protocol.
55
+ */
56
+ export function probeRecallEngine(socketPath, timeoutMs = 1000) {
57
+ return new Promise((resolvePromise) => {
58
+ let settled = false;
59
+ const done = (v) => {
60
+ if (settled)
61
+ return;
62
+ settled = true;
63
+ try {
64
+ sock.destroy();
65
+ }
66
+ catch {
67
+ /* already gone */
68
+ }
69
+ resolvePromise(v);
70
+ };
71
+ let sock;
72
+ try {
73
+ sock = netConnect(socketPath);
74
+ }
75
+ catch {
76
+ resolvePromise(undefined);
77
+ return;
78
+ }
79
+ const timer = setTimeout(() => done(undefined), timeoutMs);
80
+ timer.unref?.();
81
+ let buf = '';
82
+ sock.on('connect', () => {
83
+ try {
84
+ sock.write(`${JSON.stringify({ op: 'recall', prompt: 'dz doctor probe', limit: 1 })}\n`);
85
+ }
86
+ catch {
87
+ done(undefined);
88
+ }
89
+ });
90
+ sock.on('data', (chunk) => {
91
+ buf += chunk.toString('utf-8');
92
+ const nl = buf.indexOf('\n');
93
+ if (nl === -1)
94
+ return;
95
+ clearTimeout(timer);
96
+ try {
97
+ const msg = JSON.parse(buf.slice(0, nl));
98
+ // Codex round-3: only the protocol's own vocabulary is reported; anything else is "unknown" (undefined)
99
+ done(msg.engine === 'hybrid' || msg.engine === 'cosine-fallback' || msg.engine === 'none' ? msg.engine : undefined);
100
+ }
101
+ catch {
102
+ done(undefined);
103
+ }
104
+ });
105
+ sock.on('error', () => {
106
+ clearTimeout(timer);
107
+ done(undefined);
108
+ });
109
+ });
110
+ }
32
111
  /**
33
112
  * Version stamped into BOTH generated helper files as `// dz-apply-leg-version: N` (line 2, right
34
113
  * after the shebang). Bump on ANY change to {@link recallHookSource} or {@link embedDaemonSource}'s
@@ -39,8 +118,33 @@ import { hookCommandsOf } from './managed-hooks.js';
39
118
  * `recallHookSource`'s `loadCoreModule` candidate list is now built with a conditional spread so a
40
119
  * `null` `coreDistDir` (the hub's own portable marker, C-6/finding-6) degrades cleanly to the
41
120
  * project-relative fallbacks — the generated BYTES changed for every caller, hub and consumer alike.
121
+ *
122
+ * Bumped 3→4 (feature `embed-socket-short-path`): both generated files now resolve the socket path
123
+ * through the same `DZ_EMBED_SOCKET` → project-path-if-short → tmpdir-short-hash logic as
124
+ * {@link resolveEmbedSocketPath} (inlined as TEXT in both — a template string cannot `import` a
125
+ * compiled module), the daemon writes a `.dz/embed.sock.path` pointer when it picks the tmpdir-short
126
+ * branch, and `ready` is now printed only after `existsSync(SOCKET)` confirms the bind actually
127
+ * landed (previously logged unconditionally, before `listen` even ran).
128
+ *
129
+ * Bumped 4→5 (feature `hook-recall-hybrid-parity`, ADR-001 D1/D2): the daemon's `op: recall`
130
+ * handler now tries core's `recallHybrid` FIRST — under a time budget (`HOOK_RECALL_BUDGET_MS`,
131
+ * default 500 ms) — via the SAME `CORE_DIST_DIR` + `loadCoreModule` mechanism the hook already
132
+ * used only for its policy modules; on budget overrun, engine error, or no resolvable core module
133
+ * it falls back to today's brute-force cosine, honestly labelled `engine: 'cosine-fallback'` with a
134
+ * `reason`. The hook now reads `engine`/`reason` off the daemon's reply (stderr-only, never
135
+ * context) and applies its relevance floor to the NEW `score` format when `engine === 'hybrid'`,
136
+ * preserving today's cosine-calibrated floor unchanged for the `cosine-fallback` path.
137
+ *
138
+ * Bumped 5→6 (`hook-recall-hybrid-parity`, fix round 1 — AM-1/AM-2/AM-3/AM-5): the daemon now
139
+ * (a) fires a fire-and-forget engine warm-up before `listen()` (AM-1) so the first REAL `op: recall`
140
+ * is less likely to pay a cold `resolveAgentdbEmbedder` init; (b) arms the budget timer BEFORE
141
+ * `loadCoreModule()`, not after (AM-2, wall clock from request receipt); (c) treats ANY failure
142
+ * past the budget race — a malformed hit, `patternRecordId()` throwing — as an honest cosine
143
+ * fallback rather than a bare protocol error (AM-3); (d) reports the RAW core RRF score, unchanged,
144
+ * instead of a locally re-normalized [0,1] value (AM-5) — the hook's own `HOOK_SCORE_FLOOR` default
145
+ * moved from `0.01` to `0.005` to match (see that constant's own comment for the measurement).
42
146
  */
43
- export const APPLY_LEG_VERSION = 3;
147
+ export const APPLY_LEG_VERSION = 6;
44
148
  /**
45
149
  * Parse the `dz-apply-leg-version` stamp from a deployed helper file. Unlike
46
150
  * `writerVersionOf` (which floors an absent stamp at `0`), this returns `-1` for "no stamp at
@@ -96,6 +200,11 @@ export function bakedCoreDistDirOf(content) {
96
200
  * Behaviourally identical to the pre-existing hand-committed hub file except for: the version
97
201
  * stamp (new, line 2) and the candidate list in `loadCoreModule` (baked path first when present,
98
202
  * `/usr/lib/...` dropped — FR-3).
203
+ *
204
+ * Also carries the `embed-socket-short-path` fix (FR-1/FR-2): `SOCKET` is resolved through the
205
+ * same env → project-path-if-short → tmpdir-short-hash logic as
206
+ * {@link "./embed-socket-path.js".resolveEmbedSocketPath}, inlined as text and preferring an
207
+ * on-disk pointer when the resolver itself would land on the tmpdir-short branch.
99
208
  */
100
209
  export function recallHookSource(coreDistDir) {
101
210
  return `#!/usr/bin/env node
@@ -121,14 +230,75 @@ export function recallHookSource(coreDistDir) {
121
230
  const net = require('node:net');
122
231
  const path = require('node:path');
123
232
  const fs = require('node:fs');
233
+ const crypto = require('node:crypto');
234
+ const os = require('node:os');
124
235
  const { pathToFileURL } = require('node:url');
125
236
 
126
237
  const PROJECT = process.env.CLAUDE_PROJECT_DIR || process.cwd();
127
238
  const CORE_DIST_DIR = ${coreDistDir === null ? 'null' : JSON.stringify(coreDistDir)};
128
- const SOCKET = process.env.DZ_EMBED_SOCKET || path.join(PROJECT, '.dz', 'embed.sock');
239
+
240
+ // embed-socket-short-path (FR-1/FR-2): byte-for-byte the same logic as \`resolveEmbedSocketPath\` /
241
+ // \`resolveEffectiveEmbedSocketPath\` in \`embed-socket-path.ts\` — inlined as TEXT because this file
242
+ // is standalone and cannot \`import\` a compiled core module (apply-leg-twins.test.ts pins the copies
243
+ // to the same behavior as the daemon's own inlined copy).
244
+ const EMBED_SOCKET_PATH_BYTES_LIMIT = 100;
245
+ function resolveEmbedSocketPath(projectRoot, env) {
246
+ const fromEnv = env.DZ_EMBED_SOCKET;
247
+ if (typeof fromEnv === 'string' && fromEnv !== '') return { path: fromEnv, reason: 'env' };
248
+ const projectPath = path.join(projectRoot, '.dz', 'embed.sock');
249
+ if (Buffer.byteLength(projectPath, 'utf8') <= EMBED_SOCKET_PATH_BYTES_LIMIT) return { path: projectPath, reason: 'project' };
250
+ const hash = crypto.createHash('sha1').update(projectRoot).digest('hex').slice(0, 12);
251
+ const uid = String(process.getuid?.() ?? 'u');
252
+ const shortPath = path.join(os.tmpdir(), \`dz-\${uid}\`, \`embed-\${hash}.sock\`);
253
+ const tooLong = Buffer.byteLength(shortPath, 'utf8') > EMBED_SOCKET_PATH_BYTES_LIMIT;
254
+ return tooLong ? { path: shortPath, reason: 'tmpdir-short', tooLong: true } : { path: shortPath, reason: 'tmpdir-short' };
255
+ }
256
+ function readEmbedSocketPointer(projectRoot) {
257
+ const pointerPath = path.join(projectRoot, '.dz', 'embed.sock.path');
258
+ if (!fs.existsSync(pointerPath)) return undefined;
259
+ try {
260
+ const raw = fs.readFileSync(pointerPath, 'utf-8').trim();
261
+ return raw !== '' ? raw : undefined;
262
+ } catch {
263
+ return undefined;
264
+ }
265
+ }
266
+ function resolveEffectiveEmbedSocketPath(projectRoot, env) {
267
+ const resolved = resolveEmbedSocketPath(projectRoot, env);
268
+ if (resolved.reason !== 'tmpdir-short') return resolved;
269
+ const pointer = readEmbedSocketPointer(projectRoot);
270
+ return pointer !== undefined && fs.existsSync(pointer) ? { path: pointer, reason: 'tmpdir-short' } : resolved;
271
+ }
272
+ const SOCKET = resolveEffectiveEmbedSocketPath(PROJECT, process.env).path;
129
273
  const USAGE_LOG = process.env.DZ_RECALL_USAGE_LOG || path.join(PROJECT, '.dz', 'recall-usage.jsonl');
274
+ // Measured (2026-09-14, apply-leg-socket.test.ts): an ordinary hook round-trip (spawn + one socket
275
+ // op) took 81-121 ms; 800 ms leaves a wide margin for a loaded daemon while still bounding the AM-2
276
+ // worst case — a daemon synchronously blocked never replies at all, so THIS timeout (not the
277
+ // daemon's own internal budget race, which cannot preempt synchronous work) is what actually
278
+ // rescues the hook from hanging.
130
279
  const TIMEOUT_MS = Number(process.env.DZ_RECALL_HOOK_TIMEOUT_MS || 800);
131
280
 
281
+ // FR-5 (hook-recall-hybrid-parity, ADR-001 D2): the RRF-based \`score\` the daemon returns for
282
+ // \`engine: 'hybrid'\` is NOT on the cosine scale DEFAULT_RECALL_FLOORS (recall-hook-policy.ts) was
283
+ // calibrated on — applying the cosine floor to an RRF score would either admit everything or cut
284
+ // everything, so the hybrid path gets its OWN floor, applied to BOTH languages alike (the RRF score
285
+ // carries no language-baseline shift the way raw cosine did).
286
+ //
287
+ // AM-5 (fix round 1), MEASURED not a placeholder: recallHybrid(RRF_K=60) over a live 14-lesson
288
+ // fixture (this environment, 2026-09-14 — reproducer in the manifest's Fix-round 1 section) shows
289
+ // raw RRF score is only WEAKLY discriminating per-hit: an exact-lexical-match hit scored 0.03252
290
+ // (both legs agree at rank 0), but a genuinely IRRELEVANT query ("xkcd banana quantum toaster
291
+ // nonsense") still returned a top hit at 0.01639 — HIGHER than several truly relevant tail hits in
292
+ // OTHER queries (0.01471-0.01538). This is structural, not a fixture artifact: RRF encodes RANK,
293
+ // not similarity, and a nearest-neighbor search always returns SOME top-1 even for a garbage query.
294
+ // A raw-score floor therefore cannot cleanly separate signal from noise at the per-hit level the
295
+ // way the cosine floor does — true filtering here has to come from \`limit\` and \`selectHookHits\`'s
296
+ // own budget, not from this number. The floor's honest job is only to reject a DEGENERATE score
297
+ // (zero/negative/NaN from a malformed hit), so it is set well BELOW the measured noise floor
298
+ // (0.01471) rather than attempting to rank-filter — deliberately permissive, matching ADR-001 D2's
299
+ // stated intent that an exact lexical match (FR-4) must never be defeated by an unmeasured cutoff.
300
+ const HOOK_SCORE_FLOOR = Number(process.env.DZ_RECALL_HOOK_SCORE_FLOOR || 0.005);
301
+
132
302
  const safe = (fn, fb) => {
133
303
  try {
134
304
  return fn();
@@ -244,6 +414,9 @@ function readLogTail(chain, file) {
244
414
  }, chain && chain.EMPTY_LOG_TAIL);
245
415
  }
246
416
 
417
+ // FR-6 (hook-recall-hybrid-parity): the reply now carries \`engine\`/\`reason\` alongside \`hits\` —
418
+ // returned as a small object rather than the bare hit array, so the caller can apply the RIGHT
419
+ // floor (FR-5) and print the engine to stderr ONLY (never into the injected context, FR-2).
247
420
  function askDaemon(prompt) {
248
421
  return new Promise((resolve) => {
249
422
  if (!fs.existsSync(SOCKET)) return resolve(undefined);
@@ -265,7 +438,15 @@ function askDaemon(prompt) {
265
438
  if (nl === -1) return;
266
439
  clearTimeout(timer);
267
440
  const msg = safe(() => JSON.parse(buf.slice(0, nl)), undefined);
268
- done(msg && Array.isArray(msg.hits) ? msg.hits : undefined);
441
+ done(
442
+ msg && Array.isArray(msg.hits)
443
+ ? {
444
+ hits: msg.hits,
445
+ engine: typeof msg.engine === 'string' ? msg.engine : undefined,
446
+ reason: typeof msg.reason === 'string' ? msg.reason : undefined,
447
+ }
448
+ : undefined,
449
+ );
269
450
  });
270
451
  sock.on('error', () => {
271
452
  clearTimeout(timer);
@@ -457,8 +638,8 @@ async function main() {
457
638
  const policy = await loadPolicy();
458
639
  if (!policy) return emitContext(debt);
459
640
 
460
- const hits = await askDaemon(prompt);
461
- if (!hits) {
641
+ const daemonReply = await askDaemon(prompt);
642
+ if (!daemonReply) {
462
643
  // SELF-HEAL (2026-07-28): the daemon is started at SessionStart only, so when it dies mid-way
463
644
  // through a long-lived session NOTHING restarts it — the apply leg was silently dead for 19
464
645
  // days (MEASURED: recall-usage.jsonl last record 2026-07-09, socket absent). Spawn it
@@ -466,9 +647,19 @@ async function main() {
466
647
  reviveDaemon();
467
648
  return emitContext(debt);
468
649
  }
650
+ const { hits, engine, reason } = daemonReply;
651
+ // FR-6/FR-2: the engine (and, on fallback, why) is the caller's business, not the model's — it
652
+ // NEVER rides into additionalContext, only stderr, which Claude Code does not read as context.
653
+ if (typeof engine === 'string') {
654
+ safe(() => process.stderr.write(\`[dz-recall] engine=\${engine}\${reason ? \` reason=\${reason}\` : ''}\\n\`));
655
+ }
469
656
  if (hits.length === 0) return emitContext(debt); // daemon alive, nothing relevant — silence is correct
470
657
 
471
- const selection = policy.selectHookHits(prompt, hits);
658
+ // FR-5 (ADR-001 D2): a hybrid-engine reply carries an RRF-based score — its OWN floor, applied to
659
+ // both languages. A cosine-fallback reply (or an old daemon that never sent \`engine\` at all)
660
+ // keeps today's cosine-calibrated DEFAULT_RECALL_FLOORS untouched.
661
+ const floorOpts = engine === 'hybrid' ? { floors: { ru: HOOK_SCORE_FLOOR, en: HOOK_SCORE_FLOOR } } : {};
662
+ const selection = policy.selectHookHits(prompt, hits, floorOpts);
472
663
  // lesson-quarantine AM-2: an excluded hypothesis is logged, never a silent context shrink.
473
664
  if (typeof selection.quarantinedExcluded === 'number' && selection.quarantinedExcluded > 0) {
474
665
  try {
@@ -519,13 +710,22 @@ export function resolveIdleMs(raw) {
519
710
  }
520
711
  /**
521
712
  * Generate `.claude/helpers/dz-embed-daemon.mjs`. Behaviourally identical to the pre-existing
522
- * hand-committed hub file except for: the version stamp (new, line 2) and `resolveDeps()`, which
523
- * now tries `@huggingface/transformers` before falling back to `@xenova/transformers` — AM-3,
713
+ * hand-committed hub file except for: the version stamp (new, line 2), `resolveDeps()`, which
714
+ * tries `@huggingface/transformers` before falling back to `@xenova/transformers` — AM-3,
524
715
  * dz-harness-hub issue #10 defect 3: `agentdb >= 3.0.0-alpha` depends on the former, and an older
525
716
  * agentdb install still carries the latter, so probing only one name silently starved the daemon
526
- * on either side of that agentdb version boundary.
717
+ * on either side of that agentdb version boundary — and (feature `hook-recall-hybrid-parity`,
718
+ * ADR-001 D1) the `op: recall` handler, which now tries core's `recallHybrid` under a time budget
719
+ * before falling back to the brute-force cosine below.
720
+ *
721
+ * `coreDistDir` (new parameter, ADR-001 D1) is baked in exactly like {@link recallHookSource}'s own
722
+ * parameter of the same name — the FIRST resolve candidate for `loadCoreModule`. `null` (the
723
+ * default, and what every existing zero-arg call site gets) is the same PORTABLE marker
724
+ * `recallHookSource(null)` uses: `loadCoreModule` falls through to the project-relative fallback
725
+ * candidates, resolved from `DZ_PROJECT_ROOT`/`cwd()` at daemon RUNTIME, which is correct in any
726
+ * clone and for any consumer whose `harness-core` install is reachable under its own project tree.
527
727
  */
528
- export function embedDaemonSource() {
728
+ export function embedDaemonSource(coreDistDir = null) {
529
729
  return `#!/usr/bin/env node
530
730
  // dz-apply-leg-version: ${APPLY_LEG_VERSION}
531
731
  /**
@@ -547,18 +747,28 @@ export function embedDaemonSource() {
547
747
  * - it exits on SIGINT/SIGTERM/SIGHUP and unlinks its socket.
548
748
  *
549
749
  * PROTOCOL — newline-delimited JSON over a unix socket:
550
- * → {"op":"recall","prompt":"…","limit":8} ← {"hits":[{"dzId","pattern","score","domain"}]}
750
+ * → {"op":"recall","prompt":"…","limit":8} ← {"hits":[{"dzId","pattern","score","domain"}],"engine":"hybrid"|"cosine-fallback","reason"?}
551
751
  * → {"op":"ping"} ← {"ok":true,"model":"…","uptimeMs":N}
552
752
  * → {"op":"stop"} ← {"ok":true} (then exits)
553
753
  *
554
- * \`score\` is COSINE RELEVANCE in [0,1] — never the teaching reward. The caller applies the floor.
754
+ * ADR-001 (feature \`hook-recall-hybrid-parity\`): \`op: recall\` first tries core's \`recallHybrid\`
755
+ * (same engine \`dz recall\` uses) under \`HOOK_RECALL_BUDGET_MS\` (default 500 ms, < the hook's own
756
+ * 800 ms timeout); on budget overrun, engine error, or no resolvable core module it falls back to
757
+ * the brute-force cosine below. \`score\` on \`engine:"hybrid"\` is the RAW core RRF score, UNCHANGED
758
+ * (AM-5, fix round 1) — the exact same number \`dz recall --json\` reports as \`relevance\`, never
759
+ * locally re-normalized; on \`engine:"cosine-fallback"\` it is COSINE RELEVANCE in [0,1] as before —
760
+ * two DIFFERENT scales, never the teaching reward either way. The caller applies the right floor
761
+ * for whichever scale \`engine\` names.
555
762
  */
556
763
 
557
764
  import { createServer } from 'node:net';
558
- import { existsSync, unlinkSync, readFileSync } from 'node:fs';
559
- import { join } from 'node:path';
765
+ import { existsSync, unlinkSync, readFileSync, mkdirSync, writeFileSync, renameSync, statSync } from 'node:fs';
766
+ import { join, dirname } from 'node:path';
560
767
  import { createRequire } from 'node:module';
561
768
  import { connect } from 'node:net';
769
+ import { createHash } from 'node:crypto';
770
+ import { tmpdir } from 'node:os';
771
+ import { pathToFileURL } from 'node:url';
562
772
 
563
773
  const log = (...a) => console.error('[dz-embed]', ...a);
564
774
 
@@ -566,7 +776,84 @@ const log = (...a) => console.error('[dz-embed]', ...a);
566
776
  console.log = (...a) => console.error(...a);
567
777
 
568
778
  const PROJECT = process.env['DZ_PROJECT_ROOT'] ?? process.cwd();
569
- const SOCKET = process.env['DZ_EMBED_SOCKET'] ?? join(PROJECT, '.dz', 'embed.sock');
779
+
780
+ // ADR-001 (hook-recall-hybrid-parity, D1): the SAME candidate-list resolution the hook uses for its
781
+ // own policy modules — the baked \`coreDistDir\` first (a real install's absolute dist path), then
782
+ // project-relative fallbacks resolved from PROJECT at RUNTIME. \`null\` (the hub's own portable
783
+ // marker, matching \`recallHookSource(null)\`) skips straight to the fallbacks. Loaded ONCE and
784
+ // memoized (\`coreModulePromise\`) — a fresh \`import()\` per recall would defeat FR-3's "opened once".
785
+ const CORE_DIST_DIR = ${coreDistDir === null ? 'null' : JSON.stringify(coreDistDir)};
786
+ let coreModulePromise;
787
+ function loadCoreModule() {
788
+ if (coreModulePromise !== undefined) return coreModulePromise;
789
+ coreModulePromise = (async () => {
790
+ const candidates = [
791
+ ...(CORE_DIST_DIR ? [join(CORE_DIST_DIR, 'index.js')] : []),
792
+ join(PROJECT, 'node_modules', '@dzhechkov', 'harness-core', 'dist', 'index.js'),
793
+ join(PROJECT, 'packages', '@dzhechkov', 'harness-core', 'dist', 'index.js'),
794
+ ];
795
+ for (const c of candidates) {
796
+ if (!existsSync(c)) continue;
797
+ try {
798
+ const mod = await import(pathToFileURL(c).href);
799
+ if (typeof mod.recallHybrid === 'function' && typeof mod.patternRecordId === 'function') return mod;
800
+ } catch {
801
+ /* try the next candidate */
802
+ }
803
+ }
804
+ return undefined;
805
+ })();
806
+ return coreModulePromise;
807
+ }
808
+
809
+ // FR-2 (hook-recall-hybrid-parity): the hybrid leg is time-boxed so a slow/cold engine can never make ONE prompt pay the full
810
+ // cost — it falls back to the warm cosine below instead. 500 ms leaves the hook's own 800 ms
811
+ // timeout (recallHookSource's TIMEOUT_MS) headroom for the socket round-trip itself.
812
+ // Measured 2026-09-14 (nfr1-measure.mjs, real 743-pattern store, warm-up on, n=100 x2): hybrid p50 60-65 ms,
813
+ // p95 100-180 ms, max 374 ms; 500 ms ≈ 3x p95 and stays under the hook's own 800 ms client timeout.
814
+ const HOOK_RECALL_BUDGET_MS = Number(process.env['HOOK_RECALL_BUDGET_MS'] || 500);
815
+ // Codex round-2 (2026-09-14): a hybrid attempt that LOST the race keeps running in the background —
816
+ // this cap keeps a burst of slow requests from stacking unbounded engine work; past it, requests answer
817
+ // with cosine at once, honestly labelled. Real cancellation needs worker isolation (backlog 14c1316b).
818
+ const HYBRID_MAX_IN_FLIGHT = (() => {
819
+ const raw = Number(process.env['HOOK_HYBRID_MAX_IN_FLIGHT'] || 2);
820
+ // Codex round-3: NaN/Infinity/0/negative must not silently disable the cap — fall back to 2.
821
+ return Number.isFinite(raw) && raw >= 1 ? Math.floor(raw) : 2;
822
+ })();
823
+ let hybridInFlight = 0;
824
+ // Test-only fault injection (AC-2): a positive value delays the hybrid leg so the budget can be
825
+ // PROVEN to fire without a real slow engine. Absent/0 in every real deployment.
826
+ const DZ_EMBED_HYBRID_DELAY_MS = Number(process.env['DZ_EMBED_HYBRID_DELAY_MS'] || 0);
827
+ // AM-5 (fix round 1): the daemon used to re-normalize recallHybrid's raw RRF score into [0,1] with
828
+ // its OWN copy of vector-tier.ts's RRF_K constant — two numbers that could silently drift apart
829
+ // (this file is standalone generated text and cannot \`import\` the compiled core constant), AND a
830
+ // scale \`dz recall --json\`'s own \`relevance\` field (cli.ts: \`relevance: … h.score …\`) never
831
+ // applies — so the hook's floor and the CLI's floor were never comparable numbers even though both
832
+ // ultimately came from the same recallHybrid() call. Fixed: the daemon now reports \`h.score\`
833
+ // UNCHANGED — the exact raw core score \`dz recall --json\` already reports as \`relevance\` — so a
834
+ // floor calibrated against one is valid against the other (AM-4's parity test asserts the two are
835
+ // literally equal, not merely proportional).
836
+
837
+ // embed-socket-short-path (FR-1): a unix socket path has a hard platform limit on \`sun_path\`
838
+ // (Linux 108 bytes incl. NUL, macOS 104) — a deeply nested project's \`.dz/embed.sock\` can exceed
839
+ // it, and \`listen()\` then fails while every OTHER part of the daemon looks healthy. This mirrors
840
+ // {@link resolveEmbedSocketPath} in \`embed-socket-path.ts\` byte-for-byte (this file is generated
841
+ // TEXT, standalone, and cannot \`import\` a compiled core module — apply-leg-twins.test.ts pins the
842
+ // two copies to the same behavior).
843
+ const EMBED_SOCKET_PATH_BYTES_LIMIT = 100;
844
+ function resolveEmbedSocketPath(projectRoot, env) {
845
+ const fromEnv = env['DZ_EMBED_SOCKET'];
846
+ if (typeof fromEnv === 'string' && fromEnv !== '') return { path: fromEnv, reason: 'env' };
847
+ const projectPath = join(projectRoot, '.dz', 'embed.sock');
848
+ if (Buffer.byteLength(projectPath, 'utf8') <= EMBED_SOCKET_PATH_BYTES_LIMIT) return { path: projectPath, reason: 'project' };
849
+ const hash = createHash('sha1').update(projectRoot).digest('hex').slice(0, 12);
850
+ const uid = String(process.getuid?.() ?? 'u');
851
+ const shortPath = join(tmpdir(), \`dz-\${uid}\`, \`embed-\${hash}.sock\`);
852
+ const tooLong = Buffer.byteLength(shortPath, 'utf8') > EMBED_SOCKET_PATH_BYTES_LIMIT;
853
+ return tooLong ? { path: shortPath, reason: 'tmpdir-short', tooLong: true } : { path: shortPath, reason: 'tmpdir-short' };
854
+ }
855
+ const { path: SOCKET, reason: SOCKET_REASON, tooLong: SOCKET_TOO_LONG } = resolveEmbedSocketPath(PROJECT, process.env);
856
+ const SOCKET_POINTER = join(PROJECT, '.dz', 'embed.sock.path');
570
857
  // AM-10 (issue #10 defect 7): a setTimeout delay is a 32-bit signed int in Node — anything
571
858
  // above 2_147_483_647 ms silently becomes ~1ms (a "30 days" idle setting exited in ~1 second,
572
859
  // MEASURED). 0/NaN/negative disables the idle exit outright rather than firing immediately.
@@ -723,7 +1010,116 @@ async function main() {
723
1010
 
724
1011
  let patterns = loadPatterns();
725
1012
  let patternsAt = Date.now();
726
- log(\`ready: \${patterns.length} pattern vectors, model \${model}, socket \${SOCKET}\`);
1013
+
1014
+ // ADR-001 (hook-recall-hybrid-parity, D1): try core's recallHybrid FIRST, budget-bounded.
1015
+ // AM-2 (fix round 1, wall clock from request receipt): the budget timer is armed BEFORE
1016
+ // \`loadCoreModule()\` runs, not after it resolves — the FIRST call's dynamic \`import()\` cost used
1017
+ // to be spent OUTSIDE the race, so a slow/cold module resolution could add its own latency on top
1018
+ // of the full \`HOOK_RECALL_BUDGET_MS\` window instead of eating into it.
1019
+ // NAMED LIMIT (AM-2): \`Promise.race\` cannot PREEMPT synchronous work — if \`core.recallHybrid\`
1020
+ // (or anything it calls) blocks the event loop synchronously, this race does not return until
1021
+ // that work finishes, budget or not; Node has no cooperative-preemption primitive for that. The
1022
+ // budget only bounds work that yields the event loop somewhere (every real I/O/await in
1023
+ // recallHybrid does). The hook's OWN client-side \`TIMEOUT_MS\` (recallHookSource, 800 ms) is the
1024
+ // actual backstop against a synchronously-blocked daemon: it times out the SOCKET, not the
1025
+ // daemon's internal race, so the hook always returns promptly even if this promise never does.
1026
+ //
1027
+ // \`hybridRecall\`'s own promise is left running past a timeout loss (never awaited a second time)
1028
+ // — its \`.catch\` below only silences a LATE rejection so a slow, eventually-failing engine call
1029
+ // can never become an unhandled-rejection crash for this long-lived process.
1030
+ async function hybridRecall(prompt, limit) {
1031
+ if (hybridInFlight >= HYBRID_MAX_IN_FLIGHT) {
1032
+ return { ok: false, reason: \`hybrid saturated (\${hybridInFlight} attempt(s) still in flight, cap \${HYBRID_MAX_IN_FLIGHT})\` };
1033
+ }
1034
+ const TIMED_OUT = Symbol('timed-out');
1035
+ let timer;
1036
+ const budget = new Promise((resolve) => {
1037
+ timer = setTimeout(() => resolve(TIMED_OUT), HOOK_RECALL_BUDGET_MS);
1038
+ timer.unref?.();
1039
+ });
1040
+ hybridInFlight += 1;
1041
+ const attempt = (async () => {
1042
+ const core = await loadCoreModule();
1043
+ if (core === undefined) return { unavailable: true };
1044
+ if (DZ_EMBED_HYBRID_DELAY_MS > 0) await new Promise((r) => setTimeout(r, DZ_EMBED_HYBRID_DELAY_MS));
1045
+ const result = await core.recallHybrid(PROJECT, prompt, { limit, mode: 'hook', deferExposures: true });
1046
+ return { unavailable: false, result, core };
1047
+ })();
1048
+ // the in-flight count follows the UNDERLYING attempt, not the race: a timed-out attempt still
1049
+ // occupies its slot until it settles (that is the whole point of the cap)
1050
+ attempt.then(() => { hybridInFlight -= 1; }, () => { hybridInFlight -= 1; });
1051
+ attempt.catch(() => {}); // swallow a rejection that arrives AFTER the budget already won the race
1052
+ try {
1053
+ const raced = await Promise.race([attempt, budget]);
1054
+ clearTimeout(timer);
1055
+ if (raced === TIMED_OUT) return { ok: false, reason: \`budget exceeded (\${HOOK_RECALL_BUDGET_MS} ms)\` };
1056
+ if (raced.unavailable) return { ok: false, reason: 'core module unavailable' };
1057
+ // AM-3 (fix round 1): everything past the race — reading result.hits, a hit missing its
1058
+ // required fields, patternRecordId() throwing on a malformed pattern — is now INSIDE this
1059
+ // try, so any such failure falls back to cosine with an honest \`reason\` instead of reaching
1060
+ // the socket handler's outer catch, which used to turn it into a bare protocol {error} reply
1061
+ // (never engine:'cosine-fallback') — the exact defect this amendment fixes.
1062
+ const { result, core } = raced;
1063
+ const hits = (result.hits || []).map((h) => ({
1064
+ dzId: core.patternRecordId(h.pattern),
1065
+ pattern: h.pattern.pattern,
1066
+ score: h.score, // AM-5: raw core score, unchanged — the same number \`dz recall --json\` reports as \`relevance\`
1067
+ domain: h.pattern.domain,
1068
+ ...(h.quarantined ? { quarantined: true } : {}),
1069
+ }));
1070
+ return { ok: true, hits: hits.slice(0, limit) };
1071
+ } catch (err) {
1072
+ clearTimeout(timer);
1073
+ return { ok: false, reason: \`recallHybrid failed: \${err?.message ?? err}\` };
1074
+ }
1075
+ }
1076
+
1077
+ /** \`op: recall\`'s whole answer: hybrid first (budget-bounded), cosine fallback on ANY failure —
1078
+ * always honestly labelled with \`engine\`/\`reason\` (FR-2/FR-6). */
1079
+ async function answerRecall(prompt, limitRaw) {
1080
+ const limit = Math.min(Number(limitRaw) || 8, 32);
1081
+ if (prompt.trim() === '') return { hits: [], engine: 'none', reason: 'empty prompt' }; // Codex round-2: every reply carries \`engine\`
1082
+ const hybrid = await hybridRecall(prompt, limit);
1083
+ if (hybrid.ok) return { hits: hybrid.hits, engine: 'hybrid' };
1084
+ // Reload the cosine mirror if it changed on disk (a \`dz teach\` between turns) — the SAME
1085
+ // staleness window as before this feature, just checked only when actually falling back.
1086
+ if (Date.now() - patternsAt > 5000) {
1087
+ try {
1088
+ patterns = loadPatterns();
1089
+ } catch {
1090
+ /* keep the previous snapshot */
1091
+ }
1092
+ patternsAt = Date.now();
1093
+ }
1094
+ if (patterns.length === 0) return { hits: [], engine: 'cosine-fallback', reason: hybrid.reason };
1095
+ const qv = await embed(prompt);
1096
+ const scored = patterns.map((p) => ({ dzId: p.dzId, pattern: p.pattern, score: cos(qv, p.vec), ...(p.quarantined ? { quarantined: true } : {}) }));
1097
+ scored.sort((a, b) => b.score - a.score);
1098
+ return { hits: scored.slice(0, limit), engine: 'cosine-fallback', reason: hybrid.reason };
1099
+ }
1100
+
1101
+ // AM-1 (fix round 1): warm resolveAgentdbEmbedder — cached PER PROCESS since db1521ba (cold
1102
+ // ~2-3.6 s, warm ~1 ms, MEASURED, see the manifest's T8/AM-1 discussion) — OFF the request path,
1103
+ // so the first REAL \`op: recall\` is not the one that pays the cold init. Fired fire-and-forget
1104
+ // right before \`listen()\` below, never awaited by startup: this is a best-effort head start, not
1105
+ // a guarantee — a request landing in the few-hundred-ms window before it completes still pays the
1106
+ // cold cost exactly as before this amendment, and a warm-up failure (no core module, engine
1107
+ // error) is silently swallowed — never-block applies to startup exactly as it does to a request.
1108
+ // Measured: the slowest cold resolveAgentdbEmbedder init observed in this environment was 3653 ms
1109
+ // (T8 log, 2026-09-14) — 10 s leaves a wide margin without risking an unbounded warm-up hang.
1110
+ const WARMUP_TIMEOUT_MS = 10_000;
1111
+ async function warmUpHybridEngine() {
1112
+ const core = await loadCoreModule();
1113
+ if (core === undefined) return;
1114
+ const guard = new Promise((resolve) => {
1115
+ const t = setTimeout(resolve, WARMUP_TIMEOUT_MS);
1116
+ t.unref?.();
1117
+ });
1118
+ // An empty-string query still exercises the FULL semantic leg (embed + engine.search), which is
1119
+ // exactly what needs warming; recallHybrid degrades any error inside it honestly, so nothing
1120
+ // here needs its own try/catch beyond the outer .catch(() => {}) at the call site below.
1121
+ await Promise.race([core.recallHybrid(PROJECT, '', { limit: 1, mode: 'hook', deferExposures: true }), guard]);
1122
+ }
727
1123
 
728
1124
  let idleTimer;
729
1125
  let lastActivityAt = Date.now();
@@ -759,24 +1155,8 @@ async function main() {
759
1155
  sock.write(JSON.stringify({ ok: true }) + '\\n');
760
1156
  return shutdown(0);
761
1157
  } else if (msg.op === 'recall') {
762
- // Reload the mirror if it changed on disk (a \`dz teach\` between turns).
763
- if (Date.now() - patternsAt > 5000) {
764
- try {
765
- patterns = loadPatterns();
766
- } catch {
767
- /* keep the previous snapshot */
768
- }
769
- patternsAt = Date.now();
770
- }
771
1158
  const prompt = typeof msg.prompt === 'string' ? msg.prompt : '';
772
- if (prompt.trim() === '' || patterns.length === 0) {
773
- reply = { hits: [] };
774
- } else {
775
- const qv = await embed(prompt);
776
- const scored = patterns.map((p) => ({ dzId: p.dzId, pattern: p.pattern, score: cos(qv, p.vec), ...(p.quarantined ? { quarantined: true } : {}) }));
777
- scored.sort((a, b) => b.score - a.score);
778
- reply = { hits: scored.slice(0, Math.min(Number(msg.limit) || 8, 32)) };
779
- }
1159
+ reply = await answerRecall(prompt, msg.limit);
780
1160
  } else {
781
1161
  reply = { error: \`unknown op \${String(msg.op)}\` };
782
1162
  }
@@ -804,16 +1184,65 @@ async function main() {
804
1184
  } catch {
805
1185
  /* ignore */
806
1186
  }
1187
+ try {
1188
+ // Only OUR pointer is removed — one that already names another daemon's socket stays.
1189
+ if (SOCKET_REASON === 'tmpdir-short' && existsSync(SOCKET_POINTER) && readFileSync(SOCKET_POINTER, 'utf-8').trim() === SOCKET) unlinkSync(SOCKET_POINTER);
1190
+ } catch {
1191
+ /* ignore */
1192
+ }
807
1193
  process.exit(code);
808
1194
  }
809
1195
 
810
1196
  for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(sig, () => shutdown(0));
811
1197
 
812
- server.listen(SOCKET, () => touch());
813
- server.on('error', (err) => {
814
- log('listen failed:', err?.message ?? err);
815
- process.exit(0);
1198
+ // AM-1: fire-and-forget, never awaited — bind proceeds immediately regardless of warm-up outcome.
1199
+ warmUpHybridEngine().catch(() => {});
1200
+
1201
+ // FR-3 ("absence of a receipt is not success"): \`ready\` is printed ONLY after \`listen\`'s callback
1202
+ // AND a fresh \`existsSync(SOCKET)\` both confirm the socket file is actually on disk — a caller
1203
+ // that greps stderr for "ready" must never see it for a socket that silently failed to bind.
1204
+ function bindFailed(detail) {
1205
+ log(\`bind failed: \${detail} (path \${Buffer.byteLength(SOCKET, 'utf8')} bytes)\`);
1206
+ process.exit(3);
1207
+ }
1208
+
1209
+ // A fresh project's SOCKET directory (\`.dz/\`, or a caller-injected DZ_EMBED_SOCKET's own parent)
1210
+ // may not exist yet — \`dz setup\` usually creates \`.dz/\` before this daemon ever runs, but a
1211
+ // missing parent must not surface as an opaque platform EACCES/ENOENT when a plain mkdir fixes it.
1212
+ if (SOCKET_TOO_LONG) bindFailed('even the tmpdir-short fallback exceeds the unix socket path limit — set DZ_EMBED_SOCKET to a short path');
1213
+ try {
1214
+ // Lead edit after Codex review (finding 2): the private per-user directory is created 0700 and
1215
+ // verified — a socket in a world-writable tmpdir could be pre-bound or hijacked by a neighbour.
1216
+ mkdirSync(dirname(SOCKET), { recursive: true, mode: 0o700 });
1217
+ if (SOCKET_REASON === 'tmpdir-short') {
1218
+ const st = statSync(dirname(SOCKET));
1219
+ const ownUid = typeof process.getuid === 'function' ? process.getuid() : st.uid;
1220
+ if (st.uid !== ownUid || (st.mode & 0o077) !== 0) bindFailed(\`socket directory \${dirname(SOCKET)} is not private (uid \${st.uid}, mode \${(st.mode & 0o777).toString(8)})\`);
1221
+ }
1222
+ } catch (err) {
1223
+ if (SOCKET_REASON === 'tmpdir-short') bindFailed(\`cannot prepare socket directory: \${err?.message ?? err}\`);
1224
+ /* project branch: listen() below reports the real reason if the directory truly cannot be created */
1225
+ }
1226
+
1227
+ server.listen(SOCKET, () => {
1228
+ if (!existsSync(SOCKET)) return bindFailed('socket file missing after listen');
1229
+ if (SOCKET_REASON === 'tmpdir-short') {
1230
+ // Lead edit after Codex review (finding 3): the pointer is published ATOMICALLY (tmp + rename)
1231
+ // and BEFORE \`ready\` — a reader never sees a half-written or missing pointer after \`ready\`;
1232
+ // a pointer that cannot be published is a bind failure, not a warning.
1233
+ try {
1234
+ mkdirSync(join(PROJECT, '.dz'), { recursive: true });
1235
+ const tmp = \`\${SOCKET_POINTER}.\${process.pid}.tmp\`;
1236
+ writeFileSync(tmp, SOCKET);
1237
+ renameSync(tmp, SOCKET_POINTER);
1238
+ } catch (err) {
1239
+ return bindFailed(\`could not publish socket pointer: \${err?.message ?? err}\`);
1240
+ }
1241
+ }
1242
+ log(\`ready: \${patterns.length} pattern vectors, model \${model}, socket \${SOCKET}\`);
1243
+ touch();
816
1244
  });
1245
+ server.on('error', (err) => bindFailed(err?.message ?? String(err)));
817
1246
  }
818
1247
 
819
1248
  main().catch((err) => {