@dzhechkov/harness-core 0.3.40 → 0.3.42

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/src/index.ts CHANGED
@@ -27,7 +27,7 @@ export { recommend } from './recommend.js';
27
27
  export { pretrain } from './pretrain.js';
28
28
  export { loadPatterns, loadSessions, computePatternBoost, readLearningConfig, BOOST_CAP, recordPattern, loadStorePatternsSync, patternToRecord, recordToPattern, consolidateSessions, recallPatterns } from './patterns.js';
29
29
  export type { PatternRecord, SessionRecord, LearningConfig, LoadOptions, ConsolidateResult, ConsolidateOptions, SqliteBackendMode, RecallHit, SessionsSource } from './patterns.js';
30
- export { runSetup } from './setup.js';
30
+ export { runSetup, generateHooksConfig, generateAgentdbWriter, writerVersionOf, AGENTDB_WRITER_VERSION } from './setup.js';
31
31
  export { generatePlugin } from './plugin.js';
32
32
  export type { PluginManifest } from './plugin.js';
33
33
  export type { SetupOptions, SetupResult, SetupStep } from './setup.js';
package/src/operations.ts CHANGED
@@ -500,5 +500,57 @@ export async function runDoctor(options: { projectRoot: string }): Promise<Docto
500
500
  });
501
501
  }
502
502
 
503
+ // 8. agentdb brownfield health (gap G2) — only when agentdb artifacts are present, to keep
504
+ // non-agentdb projects noise-free. Detects installs from BEFORE the real-write fix.
505
+ const settingsPath = join(root, '.claude', 'settings.json');
506
+ const settingsRaw = existsSync(settingsPath) ? readFileSync(settingsPath, 'utf-8') : '';
507
+ if (settingsRaw.includes('agentdb add')) {
508
+ checks.push({
509
+ name: 'agentdb hooks',
510
+ ok: false,
511
+ detail: 'LEGACY broken hooks call non-existent `agentdb add` (they never wrote anything) — re-run: dz setup --target <t> --memory agentdb',
512
+ });
513
+ }
514
+ if (existsSync(join(root, '.dz', 'memory.rvf'))) {
515
+ checks.push({
516
+ name: 'agentdb store',
517
+ ok: false,
518
+ detail: 'orphan .dz/memory.rvf placeholder from an old setup (nothing reads it) — delete it; the real store is .dz/agentdb.db',
519
+ });
520
+ }
521
+ const legacyMcp = join(root, '.claude', 'mcp.json');
522
+ if (existsSync(legacyMcp) && readFileSync(legacyMcp, 'utf-8').includes('agentdb')) {
523
+ checks.push({
524
+ name: 'agentdb mcp location',
525
+ ok: false,
526
+ detail: '.claude/mcp.json is NOT loaded by Claude Code — re-run dz setup to register agentdb in .mcp.json (project root)',
527
+ });
528
+ }
529
+ const writerPath = join(root, '.dz', 'agentdb-writer.mjs');
530
+ if (existsSync(writerPath)) {
531
+ const { writerVersionOf, AGENTDB_WRITER_VERSION } = await import('./setup.js');
532
+ const deployed = writerVersionOf(readFileSync(writerPath, 'utf-8'));
533
+ if (deployed < AGENTDB_WRITER_VERSION) {
534
+ checks.push({
535
+ name: 'agentdb writer version',
536
+ ok: false,
537
+ detail: `deployed writer v${deployed} < current v${AGENTDB_WRITER_VERSION} — re-run dz setup to upgrade (no --force needed)`,
538
+ });
539
+ }
540
+ // Version drift between the local agentdb copy and the .mcp.json pin (gap G7)
541
+ try {
542
+ const localVer = (JSON.parse(readFileSync(join(root, 'node_modules', 'agentdb', 'package.json'), 'utf-8')) as { version?: string }).version;
543
+ const mcp = JSON.parse(readFileSync(join(root, '.mcp.json'), 'utf-8')) as { mcpServers?: Record<string, { args?: string[] }> };
544
+ const pinned = mcp.mcpServers?.['agentdb']?.args?.[0];
545
+ if (localVer && pinned && pinned !== `agentdb@${localVer}`) {
546
+ checks.push({
547
+ name: 'agentdb version drift',
548
+ ok: false,
549
+ detail: `local agentdb@${localVer} != MCP pin ${pinned} (alpha schema drift risk on the shared DB) — re-run dz setup`,
550
+ });
551
+ }
552
+ } catch { /* either side absent — covered by other checks */ }
553
+ }
554
+
503
555
  return { node: process.version, checks, ok: checks.every((check) => check.ok) };
504
556
  }
package/src/patterns.ts CHANGED
Binary file
package/src/setup.ts CHANGED
@@ -4,8 +4,10 @@
4
4
  * Unlike `dz init` (skills only), `dz setup` configures the complete
5
5
  * self-learning environment:
6
6
  * 1. Skills installation (via init)
7
- * 2. Claude Code hooks (session-start/end for memory)
8
- * 3. Memory database initialization (.dz/memory.db)
7
+ * 2. Claude Code session hooks (start/end) with `--memory agentdb`, a real vector-store
8
+ * write via `.dz/agentdb-writer.mjs`; otherwise a `.dz/sessions.jsonl` marker
9
+ * 3. Memory store: `.dz/agentdb.db` (agentdb, shared with the MCP server via AGENTDB_PATH)
10
+ * or `.dz/sessions.jsonl` + `.dz/patterns.jsonl` (jsonl default)
9
11
  * 4. Pretrain (project analysis → auto-recommend)
10
12
  *
11
13
  * All operations are additive — never overwrites existing files.
@@ -13,8 +15,9 @@
13
15
  * @packageDocumentation
14
16
  */
15
17
 
16
- import { existsSync, mkdirSync, writeFileSync, readFileSync } from 'node:fs';
18
+ import { existsSync, mkdirSync, writeFileSync, readFileSync, rmSync } from 'node:fs';
17
19
  import { join } from 'node:path';
20
+ import { execSync } from 'node:child_process';
18
21
 
19
22
  /** Memory backend type. */
20
23
  export type MemoryBackend = 'jsonl' | 'agentdb';
@@ -48,38 +51,138 @@ export interface SetupStep {
48
51
  readonly detail: string;
49
52
  }
50
53
 
54
+ /** Absolute path to the agentdb store shared by the hook writer and the MCP server. */
55
+ function agentdbStorePath(projectRoot: string): string {
56
+ return join(projectRoot, '.dz', 'agentdb.db');
57
+ }
58
+
59
+ /**
60
+ * Version of the generated `.dz/agentdb-writer.mjs`. Bump on ANY change to
61
+ * {@link generateAgentdbWriter}'s output — setup regenerates deployed writers whose
62
+ * `dz-writer-version` stamp is older, WITHOUT requiring `--force` (audit gap G4: generated code
63
+ * must not fossilize outside the package lifecycle).
64
+ */
65
+ export const AGENTDB_WRITER_VERSION = 3;
66
+
67
+ /**
68
+ * Generate the `.dz/agentdb-writer.mjs` helper invoked by the session hooks.
69
+ *
70
+ * v2 (ADR-002, audit gaps G3 + code#1 + code#4): session markers are **metadata-only telemetry** —
71
+ * a plain row in the `dz_session_events` table inside the SAME shared `.dz/agentdb.db` the MCP
72
+ * server is pinned to (`AGENTDB_PATH`). No embedding, no model load, no `successRate`:
73
+ * - ~ms latency (v1 loaded a ~90 MB transformers model → 12 s cold-timeout losing the marker);
74
+ * - zero pollution of the HNSW index real learnings live in (those enter via `agentdb_*` MCP tools);
75
+ * - uses better-sqlite3 DIRECTLY (WAL + busy_timeout) — if it is unavailable the writer falls back
76
+ * to the jsonl marker instead of ever touching the sql.js in-memory backend, whose
77
+ * last-write-wins semantics were the design's one real corruption vector.
78
+ *
79
+ * Best-effort and never throws: any failure degrades to a `.dz/sessions.jsonl` line labelled
80
+ * `jsonl-fallback` (with the error), so the hook always exits 0 and never blocks a session.
81
+ */
82
+ export function generateAgentdbWriter(projectRoot: string): string {
83
+ const dbPath = agentdbStorePath(projectRoot);
84
+ const sessionsPath = join(projectRoot, '.dz', 'sessions.jsonl');
85
+ return `#!/usr/bin/env node
86
+ // dz-writer-version: ${AGENTDB_WRITER_VERSION}
87
+ // Auto-generated by \`dz setup --memory agentdb\`. Do not edit — re-run \`dz setup\` to upgrade
88
+ // (setup regenerates automatically when this version stamp is outdated; --force not required).
89
+ // Writes a metadata-only session-event row into the shared AgentDB store (.dz/agentdb.db — the
90
+ // same file the agentdb MCP server is pinned to via AGENTDB_PATH). Real learnings go into the
91
+ // vector index via the agentdb_* MCP tools; this is deliberately non-semantic telemetry.
92
+ // On SessionEnd it ALSO fires a detached \`dz consolidate\` (Option C, ADR-003): harvest this
93
+ // session's learnings into the lexical store and mirror them — with real embeddings — into the
94
+ // shared AgentDB vector index. Detached + unref'd: the hook returns immediately; the model-load
95
+ // cost happens off the session's critical path.
96
+ // Best-effort: on ANY error it appends a .dz/sessions.jsonl marker and exits 0 — never throws,
97
+ // never blocks the session.
98
+ import { appendFileSync } from 'node:fs';
99
+ import { spawn } from 'node:child_process';
100
+
101
+ const event = process.argv[2] === 'end' ? 'end' : 'start';
102
+ const ts = new Date().toISOString();
103
+ const DB = process.env.AGENTDB_PATH || ${JSON.stringify(dbPath)};
104
+ const SESSIONS = ${JSON.stringify(sessionsPath)};
105
+ const ROOT = ${JSON.stringify(projectRoot)};
106
+
107
+ function note(extra) {
108
+ try {
109
+ appendFileSync(SESSIONS, JSON.stringify({ event, ts, ...extra }) + '\\n');
110
+ } catch { /* last resort: swallow */ }
111
+ }
112
+ function fallback(err) {
113
+ note({ backend: 'jsonl-fallback', error: String((err && err.message) || err) });
114
+ }
115
+
116
+ try {
117
+ // Native better-sqlite3 ONLY (prebuilt; synchronous; WAL). Never the sql.js fallback — its
118
+ // whole-file-in-memory persistence is unsafe against a concurrently-writing MCP server.
119
+ const { default: Database } = await import('better-sqlite3');
120
+ const db = new Database(DB);
121
+ db.pragma('journal_mode = WAL');
122
+ db.pragma('busy_timeout = 5000'); // wait out a brief MCP-server write lock instead of failing
123
+ db.exec('CREATE TABLE IF NOT EXISTS dz_session_events (id INTEGER PRIMARY KEY AUTOINCREMENT, event TEXT NOT NULL, ts TEXT NOT NULL, source TEXT NOT NULL DEFAULT \\'dz-session-hook\\')');
124
+ db.prepare('INSERT INTO dz_session_events (event, ts) VALUES (?, ?)').run(event, ts);
125
+ db.close();
126
+ } catch (err) {
127
+ fallback(err);
128
+ }
129
+
130
+ if (event === 'end') {
131
+ // Option C: harvest learnings + mirror to the vector index, DETACHED (fire-and-forget) so the
132
+ // hook never waits on transcript parsing or the embedding model. Uses the globally-installed
133
+ // \`dz\` from PATH. NO shell on posix: spawn's args-array + shell:true silently word-splits a
134
+ // ROOT containing spaces AND is Node's documented command-injection hazard (QE P1+P2); a plain
135
+ // spawn searches PATH itself and quotes nothing. Windows needs a shell for the .cmd shim, so
136
+ // there we pass ONE pre-quoted string (") — quotes are illegal in Windows paths, so wrapping
137
+ // is sufficient. Failure is detected via BOTH the error event (posix ENOENT) and a non-zero
138
+ // exit code (shell-mediated "not found"), each leaving an honest note.
139
+ try {
140
+ const child = process.platform === 'win32'
141
+ ? spawn('dz consolidate --project "' + ROOT + '"', { detached: true, stdio: 'ignore', shell: true, cwd: ROOT })
142
+ : spawn('dz', ['consolidate', '--project', ROOT], { detached: true, stdio: 'ignore', cwd: ROOT });
143
+ child.on('error', (err) => note({ consolidate: 'skipped', error: String((err && err.message) || err) }));
144
+ child.on('exit', (code) => { if (code !== null && code !== 0) note({ consolidate: 'skipped', error: 'dz exited ' + code + ' (not on PATH?)' }); });
145
+ child.unref();
146
+ } catch (err) {
147
+ note({ consolidate: 'skipped', error: String((err && err.message) || err) });
148
+ }
149
+ }
150
+ `;
151
+ }
152
+
153
+ /** Parse the `dz-writer-version` stamp from a deployed writer file ('' or absent → 0). */
154
+ export function writerVersionOf(content: string): number {
155
+ const m = /^\/\/ dz-writer-version:\s*(\d+)/m.exec(content);
156
+ return m ? parseInt(m[1] ?? '0', 10) : 0;
157
+ }
158
+
51
159
  /** Generate Claude Code hooks configuration for self-learning. */
52
- function generateHooksConfig(projectRoot: string, backend: MemoryBackend): string {
160
+ export function generateHooksConfig(projectRoot: string, backend: MemoryBackend): string {
53
161
  const dzDir = join(projectRoot, '.dz');
54
162
 
55
163
  if (backend === 'agentdb') {
56
- // agentdb backend: hooks use agentdb CLI to store patterns
57
- const rvfPath = join(dzDir, 'memory.rvf');
164
+ // agentdb backend: hooks invoke the generated writer, which does a REAL vector-store write
165
+ // (ReasoningBank.storePattern) into the AGENTDB_PATH store the MCP server shares. The writer
166
+ // self-degrades to a sessions.jsonl marker on any failure, so no hook ever throws.
167
+ const writer = join(dzDir, 'agentdb-writer.mjs');
58
168
  return JSON.stringify({
59
169
  hooks: {
60
- SessionStart: [{
61
- type: 'command',
62
- command: `node -e "const fs=require('fs');const d=new Date().toISOString();try{require('child_process').execSync('npx agentdb add \\'${rvfPath}\\' \\'session-start: '+d+'\\'',{stdio:'pipe'})}catch{fs.appendFileSync('${dzDir}/sessions.jsonl',JSON.stringify({event:'start',ts:d,backend:'agentdb'})+'\\n')}"`,
63
- }],
64
- SessionEnd: [{
65
- type: 'command',
66
- command: `node -e "const fs=require('fs');const d=new Date().toISOString();try{require('child_process').execSync('npx agentdb add \\'${rvfPath}\\' \\'session-end: '+d+'\\'',{stdio:'pipe'})}catch{fs.appendFileSync('${dzDir}/sessions.jsonl',JSON.stringify({event:'end',ts:d,backend:'agentdb'})+'\\n')}"`,
67
- }],
170
+ SessionStart: [{ type: 'command', command: `node ${JSON.stringify(writer)} start` }],
171
+ SessionEnd: [{ type: 'command', command: `node ${JSON.stringify(writer)} end` }],
68
172
  },
69
173
  }, null, 2);
70
174
  }
71
175
 
72
- // JSONL backend (default)
176
+ // JSONL backend (default) — honest session bookkeeping, no vector store involved.
177
+ // Use a RELATIVE path (Claude Code runs hooks from the project root): interpolating the absolute
178
+ // ${dzDir} into a single-quoted JS literal inside shell double-quotes breaks on Windows backslash
179
+ // paths (\U, \b…) and on any path containing a quote. `.dz/sessions.jsonl` sidesteps all of it.
180
+ const jsonlCmd = (event: 'start' | 'end'): string =>
181
+ `node -e "const fs=require('fs');const d=new Date().toISOString();fs.appendFileSync('.dz/sessions.jsonl',JSON.stringify({event:'${event}',ts:d,backend:'jsonl'})+'\\n')"`;
73
182
  return JSON.stringify({
74
183
  hooks: {
75
- SessionStart: [{
76
- type: 'command',
77
- command: `node -e "const fs=require('fs');const d=new Date().toISOString();fs.appendFileSync('${dzDir}/sessions.jsonl',JSON.stringify({event:'start',ts:d})+'\\n')"`,
78
- }],
79
- SessionEnd: [{
80
- type: 'command',
81
- command: `node -e "const fs=require('fs');const d=new Date().toISOString();fs.appendFileSync('${dzDir}/sessions.jsonl',JSON.stringify({event:'end',ts:d})+'\\n')"`,
82
- }],
184
+ SessionStart: [{ type: 'command', command: jsonlCmd('start') }],
185
+ SessionEnd: [{ type: 'command', command: jsonlCmd('end') }],
83
186
  },
84
187
  }, null, 2);
85
188
  }
@@ -96,9 +199,10 @@ function generateDzConfig(target: string, preset: string | undefined, backend: M
96
199
  // recommend() reads .dz/patterns.jsonl back as a ranking boost (audit #2).
97
200
  // Set false to disable the boost (recommend() reverts to pure keyword scoring).
98
201
  recommendBoost: true,
99
- // No background consolidator ships in Tier 1 flag must not advertise an
100
- // unimplemented capability (the harvestDreamPatterns worker is Tier 2).
101
- patternConsolidation: false,
202
+ // agentdb backend: the SessionEnd hook fires a detached `dz consolidate` that harvests
203
+ // learnings and mirrors them into the vector index (Option C, ADR-003). jsonl backend has
204
+ // no background consolidator — the flag must not advertise an unimplemented capability.
205
+ patternConsolidation: backend === 'agentdb',
102
206
  // Store backend: 'auto' = SQLite (FTS5, scale) when better-sqlite3 is
103
207
  // available, else the JSON fallback. 'json'/'sqlite' force a backend (Tier-3).
104
208
  sqliteBackend: 'auto',
@@ -107,12 +211,18 @@ function generateDzConfig(target: string, preset: string | undefined, backend: M
107
211
  },
108
212
  memory: {
109
213
  backend,
110
- path: backend === 'agentdb' ? '.dz/memory.rvf' : '.dz/sessions.jsonl',
214
+ // agentdb: the native SQLite vector store shared by the session-hook writer and the
215
+ // agentdb MCP server (both pinned via AGENTDB_PATH). Real ReasoningBank patterns land here.
216
+ path: backend === 'agentdb' ? '.dz/agentdb.db' : '.dz/sessions.jsonl',
111
217
  maxSizeMb: backend === 'agentdb' ? 100 : 10,
112
218
  agentdb: backend === 'agentdb' ? {
113
219
  learning: true,
114
220
  vectorDim: 384,
115
221
  mcpServer: 'agentdb',
222
+ // Both the hook writer and the MCP server read/write THIS path (env AGENTDB_PATH).
223
+ storePath: '.dz/agentdb.db',
224
+ embeddingModel: 'Xenova/all-MiniLM-L6-v2',
225
+ sessionHookWrites: true,
116
226
  } : undefined,
117
227
  },
118
228
  hooks: {
@@ -122,11 +232,52 @@ function generateDzConfig(target: string, preset: string | undefined, backend: M
122
232
  }, null, 2);
123
233
  }
124
234
 
125
- /** Check if agentdb is available. */
126
- function isAgentdbAvailable(): boolean {
235
+ /** True if `agentdb` resolves from the project's node_modules (the hook writer needs it there). */
236
+ function isAgentdbInstalledLocally(projectRoot: string): boolean {
237
+ return existsSync(join(projectRoot, 'node_modules', 'agentdb', 'package.json'));
238
+ }
239
+
240
+ /**
241
+ * The exact agentdb version installed in the project, or `'latest'` as a fallback. Used to pin the
242
+ * MCP server spec (`agentdb@<version>`) so the long-running MCP server and the hook writer — which
243
+ * imports the on-disk local copy — run the SAME schema against the shared DB (agentdb is alpha;
244
+ * `@latest` could drift the MCP server's schema away from what the hook wrote).
245
+ */
246
+ function installedAgentdbSpec(projectRoot: string): string {
127
247
  try {
128
- require('child_process').execSync('npx agentdb --version', { stdio: 'pipe', timeout: 10000 });
129
- return true;
248
+ const pkg = JSON.parse(readFileSync(join(projectRoot, 'node_modules', 'agentdb', 'package.json'), 'utf-8')) as { version?: string };
249
+ return pkg.version ? `agentdb@${pkg.version}` : 'agentdb@latest';
250
+ } catch {
251
+ return 'agentdb@latest';
252
+ }
253
+ }
254
+
255
+ /**
256
+ * Install `agentdb` + `better-sqlite3` as LOCAL project deps so the session-hook writer can
257
+ * `import('agentdb')` and get a native SQLite store (better-sqlite3 ships prebuilt binaries — no
258
+ * build tools — and gives true cross-process WAL concurrency so the hook and the MCP server share
259
+ * one live store). Best-effort: returns false (caller degrades to jsonl) if install fails.
260
+ */
261
+ function installAgentdbLocally(projectRoot: string): boolean {
262
+ if (isAgentdbInstalledLocally(projectRoot)) return true;
263
+ try {
264
+ // Anchor npm to THIS project: without a package.json here, npm's prefix walk-up would
265
+ // install into (and mutate the lockfile of) the nearest ANCESTOR project (audit code#2).
266
+ const pkgJsonPath = join(projectRoot, 'package.json');
267
+ if (!existsSync(pkgJsonPath)) {
268
+ writeFileSync(pkgJsonPath, JSON.stringify({ name: 'dz-harness-project', private: true, version: '0.0.0' }, null, 2) + '\n');
269
+ }
270
+ // NB: use the ESM-imported execSync — `require()` is undefined in this ESM module (the
271
+ // original agentdb hooks failed silently for exactly this reason). stdio:'ignore' (not
272
+ // 'pipe') avoids execSync's 1 MB maxBuffer aborting the child on npm's verbose output.
273
+ // --save-exact: agentdb is alpha; a semver range would let a later `npm update` drift the
274
+ // local copy away from the version the MCP registration pins (audit gap G7).
275
+ execSync('npm install agentdb better-sqlite3 --save-exact --no-audit --no-fund --loglevel=error', {
276
+ cwd: projectRoot,
277
+ stdio: 'ignore',
278
+ timeout: 300000,
279
+ });
280
+ return isAgentdbInstalledLocally(projectRoot);
130
281
  } catch {
131
282
  return false;
132
283
  }
@@ -257,14 +408,19 @@ export function runSetup(opts: SetupOptions): SetupResult {
257
408
  const dzDir = join(opts.projectRoot, '.dz');
258
409
  const backend: MemoryBackend = opts.memory ?? 'jsonl';
259
410
 
260
- // Step 0: Check agentdb availability if requested
411
+ // Step 0: Install agentdb + better-sqlite3 locally so the session-hook writer can import them
412
+ // and share a native store with the MCP server. Best-effort — the writer self-degrades to a
413
+ // jsonl marker (and self-heals once the deps exist) if this fails.
261
414
  if (backend === 'agentdb') {
262
- const available = isAgentdbAvailable();
263
- if (available) {
264
- steps.push({ name: 'AgentDB check', status: 'done', detail: 'agentdb available' });
415
+ const ready = installAgentdbLocally(opts.projectRoot);
416
+ if (ready) {
417
+ steps.push({ name: 'Install agentdb + better-sqlite3', status: 'done', detail: 'local deps for real vector writes' });
265
418
  } else {
266
- steps.push({ name: 'AgentDB check', status: 'error', detail: 'not found — install: npm i -g agentdb' });
267
- // Fall through will still create config, hooks will fallback to JSONL
419
+ steps.push({
420
+ name: 'Install agentdb + better-sqlite3',
421
+ status: 'error',
422
+ detail: 'install failed — hooks log to sessions.jsonl until you run: npm i agentdb better-sqlite3',
423
+ });
268
424
  }
269
425
  }
270
426
 
@@ -296,22 +452,26 @@ export function runSetup(opts: SetupOptions): SetupResult {
296
452
 
297
453
  // Step 4: Initialize memory store
298
454
  if (backend === 'agentdb') {
299
- // Initialize .rvf via agentdb CLI
300
- const rvfPath = join(dzDir, 'memory.rvf');
301
- if (!existsSync(rvfPath)) {
302
- try {
303
- const { execSync } = require('child_process') as typeof import('child_process');
304
- execSync(`npx agentdb init "${rvfPath}"`, { stdio: 'pipe', timeout: 30000 });
305
- steps.push({ name: 'Initialize memory.rvf', status: 'done', detail: 'agentdb vector memory' });
306
- } catch {
307
- // Fallback: create empty file, agentdb will init on first use
308
- writeFileSync(rvfPath, '');
309
- steps.push({ name: 'Initialize memory.rvf', status: 'done', detail: 'placeholder (agentdb will init on first use)' });
310
- }
455
+ // Write the session-hook writer. The agentdb.db store itself is auto-created on first write
456
+ // by createDatabase() (both the writer and the MCP server init the schema), so there is no
457
+ // orphan placeholder file — the writer targets the real, shared native store.
458
+ const writerPath = join(dzDir, 'agentdb-writer.mjs');
459
+ // Regenerate when missing, forced, OR the deployed stamp is older than the current
460
+ // generator deployed writers must not fossilize outside the package lifecycle (gap G4).
461
+ const deployedVersion = existsSync(writerPath) ? writerVersionOf(readFileSync(writerPath, 'utf-8')) : -1;
462
+ if (deployedVersion === -1 || opts.force || deployedVersion < AGENTDB_WRITER_VERSION) {
463
+ writeFileSync(writerPath, generateAgentdbWriter(opts.projectRoot));
464
+ steps.push({
465
+ name: 'Write agentdb-writer.mjs',
466
+ status: 'done',
467
+ detail: deployedVersion > -1 && deployedVersion < AGENTDB_WRITER_VERSION
468
+ ? `upgraded v${deployedVersion} → v${AGENTDB_WRITER_VERSION}`
469
+ : `session telemetry writer v${AGENTDB_WRITER_VERSION}`,
470
+ });
311
471
  } else {
312
- steps.push({ name: 'Initialize memory.rvf', status: 'skipped', detail: 'already exists' });
472
+ steps.push({ name: 'Write agentdb-writer.mjs', status: 'skipped', detail: `current (v${deployedVersion})` });
313
473
  }
314
- // Also create JSONL fallback
474
+ // Keep the jsonl fallback log available for the writer's degraded path.
315
475
  const sessionsPath = join(dzDir, 'sessions.jsonl');
316
476
  if (!existsSync(sessionsPath)) writeFileSync(sessionsPath, '');
317
477
  } else {
@@ -332,70 +492,162 @@ export function runSetup(opts: SetupOptions): SetupResult {
332
492
  }
333
493
  }
334
494
 
335
- // Step 5: Configure hooks (write to .claude/settings.json)
495
+ // Step 5: Configure hooks (write to .claude/settings.json) — EVENT-LEVEL merge (gap G2):
496
+ // dz-generated entries (recognized by signature, incl. the broken legacy `agentdb add` hooks
497
+ // this feature fixes) are replaced in place WITHOUT --force; the user's own hooks and every
498
+ // other settings key are preserved. Full-file overwrite happens only when the file is absent.
336
499
  if (!opts.noHooks) {
337
500
  const settingsDir = join(opts.projectRoot, '.claude');
338
501
  const settingsPath = join(settingsDir, 'settings.json');
502
+ const generated = JSON.parse(generateHooksConfig(opts.projectRoot, backend)) as {
503
+ hooks: Record<string, { type: string; command: string }[]>;
504
+ };
339
505
 
340
- if (!existsSync(settingsPath) || opts.force) {
506
+ if (!existsSync(settingsPath)) {
341
507
  mkdirSync(settingsDir, { recursive: true });
342
- writeFileSync(settingsPath, generateHooksConfig(opts.projectRoot, backend));
508
+ writeFileSync(settingsPath, JSON.stringify({ hooks: generated.hooks }, null, 2));
343
509
  steps.push({ name: 'Configure hooks', status: 'done', detail: `${backend} session hooks` });
344
510
  } else {
345
511
  try {
346
512
  const existing = JSON.parse(readFileSync(settingsPath, 'utf-8')) as Record<string, unknown>;
347
- if (!existing['hooks']) {
348
- const hooks = JSON.parse(generateHooksConfig(opts.projectRoot, backend));
349
- existing['hooks'] = hooks.hooks;
513
+ const hooks = (existing['hooks'] ?? {}) as Record<string, unknown[]>;
514
+ let changed = false;
515
+ let replacedLegacy = false;
516
+ for (const event of Object.keys(generated.hooks)) {
517
+ const current = Array.isArray(hooks[event]) ? hooks[event] : [];
518
+ // Drop dz-generated entries (any vintage) — keep the user's own hooks untouched.
519
+ const kept = current.filter((entry) => {
520
+ const cmd = String((entry as { command?: unknown })?.command ?? '');
521
+ const isDz = cmd.includes('agentdb add') || cmd.includes('agentdb-writer.mjs') || cmd.includes('sessions.jsonl');
522
+ if (isDz && !cmd.includes('agentdb-writer.mjs')) replacedLegacy = true;
523
+ return !isDz;
524
+ });
525
+ const next = [...kept, ...generated.hooks[event]!];
526
+ if (JSON.stringify(next) !== JSON.stringify(current)) changed = true;
527
+ hooks[event] = next;
528
+ }
529
+ if (changed) {
530
+ existing['hooks'] = hooks;
350
531
  writeFileSync(settingsPath, JSON.stringify(existing, null, 2));
351
- steps.push({ name: 'Configure hooks', status: 'done', detail: `merged ${backend} hooks` });
532
+ steps.push({
533
+ name: 'Configure hooks',
534
+ status: 'done',
535
+ detail: replacedLegacy ? `replaced legacy dz hooks with ${backend} hooks` : `merged ${backend} hooks (user hooks preserved)`,
536
+ });
352
537
  } else {
353
- steps.push({ name: 'Configure hooks', status: 'skipped', detail: 'hooks already configured' });
538
+ steps.push({ name: 'Configure hooks', status: 'skipped', detail: 'hooks already current' });
354
539
  }
355
540
  } catch {
356
- steps.push({ name: 'Configure hooks', status: 'skipped', detail: 'could not parse existing settings' });
541
+ steps.push({ name: 'Configure hooks', status: 'error', detail: 'could not parse existing settings.json — fix it and re-run' });
357
542
  }
358
543
  }
359
544
  } else {
360
545
  steps.push({ name: 'Configure hooks', status: 'skipped', detail: '--no-hooks' });
361
546
  }
362
547
 
363
- // Step 5.5: Register agentdb MCP server (if agentdb backend)
548
+ // Step 5.5: Register agentdb MCP server (if agentdb backend) in **`.mcp.json` at the project
549
+ // root** — the project-scope location Claude Code actually loads (gap G5: the previously used
550
+ // `.claude/mcp.json` is NOT read by Claude Code, so the server never got AGENTDB_PATH and the
551
+ // shared-store invariant silently failed). READ-MERGE-WRITE: only the `agentdb` entry is
552
+ // managed; every other registered server is preserved (audit code#5 — never clobber).
364
553
  if (backend === 'agentdb') {
365
- const mcpConfigPath = join(opts.projectRoot, '.claude', 'mcp.json');
366
- if (!existsSync(mcpConfigPath) || opts.force) {
367
- const mcpConfig = {
368
- mcpServers: {
369
- agentdb: {
370
- command: 'npx',
371
- args: ['agentdb@latest', 'mcp', 'start'],
372
- },
373
- },
554
+ const agentdbEntry = {
555
+ command: 'npx',
556
+ // Pin to the INSTALLED agentdb version (not @latest) so the MCP server and the hook
557
+ // writer run the same alpha schema against one DB.
558
+ args: [installedAgentdbSpec(opts.projectRoot), 'mcp', 'start'],
559
+ // Pin the store to the SAME native DB the session-hook writer targets, so hook telemetry
560
+ // and agentdb_* pattern/reflexion data live in one shared store.
561
+ env: { AGENTDB_PATH: agentdbStorePath(opts.projectRoot) },
562
+ };
563
+ const mcpConfigPath = join(opts.projectRoot, '.mcp.json');
564
+ try {
565
+ const mcpConfig = (existsSync(mcpConfigPath)
566
+ ? JSON.parse(readFileSync(mcpConfigPath, 'utf-8'))
567
+ : {}) as { mcpServers?: Record<string, unknown> };
568
+ const servers = mcpConfig.mcpServers ?? {};
569
+ const before = JSON.stringify(servers['agentdb']);
570
+ servers['agentdb'] = agentdbEntry;
571
+ mcpConfig.mcpServers = servers;
572
+ if (before !== JSON.stringify(agentdbEntry)) {
573
+ writeFileSync(mcpConfigPath, JSON.stringify(mcpConfig, null, 2));
574
+ steps.push({ name: 'Register agentdb MCP', status: 'done', detail: '.mcp.json: 41 tools, store pinned to .dz/agentdb.db' });
575
+ } else {
576
+ steps.push({ name: 'Register agentdb MCP', status: 'skipped', detail: 'already registered and current' });
577
+ }
578
+ } catch {
579
+ steps.push({ name: 'Register agentdb MCP', status: 'error', detail: '.mcp.json unparseable — fix it and re-run' });
580
+ }
581
+ // Migrate off the legacy location: `.claude/mcp.json` is not loaded by Claude Code. If it
582
+ // holds ONLY our old agentdb registration, remove the file; otherwise leave it and warn.
583
+ const legacyPath = join(opts.projectRoot, '.claude', 'mcp.json');
584
+ if (existsSync(legacyPath)) {
585
+ try {
586
+ const legacy = JSON.parse(readFileSync(legacyPath, 'utf-8')) as { mcpServers?: Record<string, unknown> };
587
+ const keys = Object.keys(legacy.mcpServers ?? {});
588
+ if (keys.length === 1 && keys[0] === 'agentdb') {
589
+ rmSync(legacyPath);
590
+ steps.push({ name: 'Migrate legacy .claude/mcp.json', status: 'done', detail: 'removed (not loaded by Claude Code); registration now in .mcp.json' });
591
+ } else {
592
+ steps.push({ name: 'Migrate legacy .claude/mcp.json', status: 'error', detail: 'contains other servers — Claude Code does NOT load this file; move them to .mcp.json' });
593
+ }
594
+ } catch {
595
+ steps.push({ name: 'Migrate legacy .claude/mcp.json', status: 'error', detail: 'unparseable legacy file — Claude Code does not load it; review manually' });
596
+ }
597
+ }
598
+ }
599
+
600
+ // Step 5.9: agentdb wiring invariant check (audit code#3). Skip-branches across repeated runs
601
+ // can leave inconsistent combinations (e.g. writer+MCP present but hooks still jsonl). Verify
602
+ // the three-way invariant explicitly and surface a loud error step instead of silent "skipped"s.
603
+ if (backend === 'agentdb' && !opts.noHooks) {
604
+ const problems: string[] = [];
605
+ if (!isAgentdbInstalledLocally(opts.projectRoot)) problems.push('deps missing (npm i agentdb better-sqlite3)');
606
+ try {
607
+ const settings = JSON.parse(readFileSync(join(opts.projectRoot, '.claude', 'settings.json'), 'utf-8')) as {
608
+ hooks?: Record<string, { command?: string }[]>;
374
609
  };
375
- mkdirSync(join(opts.projectRoot, '.claude'), { recursive: true });
376
- writeFileSync(mcpConfigPath, JSON.stringify(mcpConfig, null, 2));
377
- steps.push({ name: 'Register agentdb MCP', status: 'done', detail: '41 tools available' });
378
- } else {
379
- steps.push({ name: 'Register agentdb MCP', status: 'skipped', detail: 'mcp.json already exists' });
610
+ const refs = ['SessionStart', 'SessionEnd'].every((ev) =>
611
+ (settings.hooks?.[ev] ?? []).some((h) => String(h?.command ?? '').includes('agentdb-writer.mjs')));
612
+ if (!refs) problems.push('hooks do not invoke the writer');
613
+ } catch {
614
+ problems.push('settings.json unreadable');
615
+ }
616
+ try {
617
+ const mcp = JSON.parse(readFileSync(join(opts.projectRoot, '.mcp.json'), 'utf-8')) as {
618
+ mcpServers?: Record<string, { env?: Record<string, string> }>;
619
+ };
620
+ if (mcp.mcpServers?.['agentdb']?.env?.['AGENTDB_PATH'] !== agentdbStorePath(opts.projectRoot)) {
621
+ problems.push('.mcp.json agentdb missing or not pinned to .dz/agentdb.db');
622
+ }
623
+ } catch {
624
+ problems.push('.mcp.json unreadable');
380
625
  }
626
+ steps.push(problems.length === 0
627
+ ? { name: 'agentdb wiring', status: 'done', detail: 'hooks → writer → .dz/agentdb.db ← MCP (one shared store)' }
628
+ : { name: 'agentdb wiring', status: 'error', detail: `INCOMPLETE: ${problems.join('; ')}` });
381
629
  }
382
630
 
383
- // Step 6: Update .gitignore
631
+ // Step 6: Update .gitignore. Append only the ENTRIES that are actually missing — a single
632
+ // sentinel check (e.g. sessions.jsonl, present in both backends) would skip agentdb.db/-wal/-shm
633
+ // on the documented jsonl→agentdb `--force` switch, leaking the binary store into git.
384
634
  const gitignorePath = join(opts.projectRoot, '.gitignore');
385
- const dzIgnoreEntry = backend === 'agentdb'
386
- ? '\n# DZ Harness learning data\n.dz/memory.rvf\n.dz/sessions.jsonl\n'
387
- : '\n# DZ Harness learning data\n.dz/sessions.jsonl\n.dz/patterns.jsonl\n';
388
- if (existsSync(gitignorePath)) {
389
- const content = readFileSync(gitignorePath, 'utf-8');
390
- if (!content.includes('.dz/sessions.jsonl')) {
391
- writeFileSync(gitignorePath, content + dzIgnoreEntry);
392
- steps.push({ name: 'Update .gitignore', status: 'done', detail: 'added .dz/sessions.jsonl + patterns.jsonl' });
393
- } else {
394
- steps.push({ name: 'Update .gitignore', status: 'skipped', detail: 'already ignoring .dz data' });
395
- }
635
+ const dzIgnoreLines = backend === 'agentdb'
636
+ ? ['.dz/agentdb.db', '.dz/agentdb.db-wal', '.dz/agentdb.db-shm', '.dz/sessions.jsonl']
637
+ : ['.dz/sessions.jsonl', '.dz/patterns.jsonl'];
638
+ const existing = existsSync(gitignorePath) ? readFileSync(gitignorePath, 'utf-8') : '';
639
+ const missing = dzIgnoreLines.filter((line) => !existing.split(/\r?\n/).includes(line));
640
+ if (missing.length > 0) {
641
+ const prefix = existing === '' ? '' : (existing.endsWith('\n') ? '' : '\n');
642
+ const block = `${prefix}\n# DZ Harness learning data\n${missing.join('\n')}\n`;
643
+ writeFileSync(gitignorePath, existing + block);
644
+ steps.push({
645
+ name: existsSync(gitignorePath) && existing !== '' ? 'Update .gitignore' : 'Create .gitignore',
646
+ status: 'done',
647
+ detail: `added ${missing.join(', ')}`,
648
+ });
396
649
  } else {
397
- writeFileSync(gitignorePath, dzIgnoreEntry);
398
- steps.push({ name: 'Create .gitignore', status: 'done', detail: 'with .dz entries' });
650
+ steps.push({ name: 'Update .gitignore', status: 'skipped', detail: 'already ignoring .dz data' });
399
651
  }
400
652
 
401
653
  // Step 7: Install the CLI-driver skill + agent docs (--install-driver)