@edihasaj/recall 2.0.7 → 2.0.9

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 (85) hide show
  1. package/README.md +11 -0
  2. package/dist/{chunk-2WBJWKIK.js → chunk-27L3NQUO.js} +20 -6
  3. package/dist/chunk-27L3NQUO.js.map +1 -0
  4. package/dist/{chunk-MZTZKBRL.js → chunk-BTHB6Q43.js} +2 -2
  5. package/dist/{chunk-BJZCBMU4.js → chunk-D6COH25L.js} +22 -16
  6. package/dist/chunk-D6COH25L.js.map +1 -0
  7. package/dist/{chunk-VH3FI2X3.js → chunk-DH6RDBAI.js} +843 -144
  8. package/dist/chunk-DH6RDBAI.js.map +1 -0
  9. package/dist/{chunk-EDUIDJWZ.js → chunk-IKD5BHN6.js} +2 -2
  10. package/dist/{chunk-EDUIDJWZ.js.map → chunk-IKD5BHN6.js.map} +1 -1
  11. package/dist/{chunk-DQMKYMUS.js → chunk-J3QU7QT3.js} +435 -89
  12. package/dist/chunk-J3QU7QT3.js.map +1 -0
  13. package/dist/{chunk-63H4ENYA.js → chunk-J4EGDZIT.js} +351 -139
  14. package/dist/chunk-J4EGDZIT.js.map +1 -0
  15. package/dist/{chunk-AVUTQWZE.js → chunk-K3Z6YUKH.js} +5 -5
  16. package/dist/{chunk-V3MYT3AT.js → chunk-KHE2ME44.js} +3 -3
  17. package/dist/{chunk-YDVBXHX2.js → chunk-N23KB2S7.js} +5 -5
  18. package/dist/{chunk-QPOOF2GK.js → chunk-NENWBA4Q.js} +3 -3
  19. package/dist/{chunk-M5MPUMCJ.js → chunk-RELMDL4Y.js} +3 -3
  20. package/dist/{chunk-S46JVROA.js → chunk-ROFI66JK.js} +2 -2
  21. package/dist/{chunk-W75S5CK3.js → chunk-SJ23JYZJ.js} +2 -2
  22. package/dist/{chunk-BTD3BYVV.js → chunk-T3DS4QYF.js} +2 -2
  23. package/dist/{chunk-MQPMF5F3.js → chunk-TEDEFEXJ.js} +7 -7
  24. package/dist/{chunk-EX5UTOIU.js → chunk-UJHXM7FK.js} +9 -9
  25. package/dist/{chunk-FOJHR4JJ.js → chunk-VBX7MM2C.js} +2 -2
  26. package/dist/{cleanup-EDWLCJPH.js → cleanup-FGPVQRYE.js} +11 -11
  27. package/dist/cli.js +839 -249
  28. package/dist/cli.js.map +1 -1
  29. package/dist/{codex-trust-H6KNABHV.js → codex-trust-CWD4SYOS.js} +4 -4
  30. package/dist/daemon.js +208 -48
  31. package/dist/daemon.js.map +1 -1
  32. package/dist/dispatcher-L77LKD7R.js +22 -0
  33. package/dist/{embeddings-W24SA6R3.js → embeddings-J24U3RAX.js} +5 -5
  34. package/dist/ingest-UU7VULPA.js +20 -0
  35. package/dist/{keychain-LVWMAS7D.js → keychain-23KFNHQ6.js} +3 -3
  36. package/dist/mcp.js +15 -15
  37. package/dist/{memory-value-GMYJ5NGO.js → memory-value-MWWV4P4X.js} +11 -11
  38. package/dist/{provenance-KSBMVJO5.js → provenance-U2VAENS6.js} +9 -9
  39. package/dist/quality-PIYKKBIT.js +25 -0
  40. package/dist/retrieval-DDYCXIUG.js +15 -0
  41. package/dist/{store-QYLHMBPE.js → store-DL6YQ6C3.js} +4 -4
  42. package/dist/sync-server.js +2 -2
  43. package/dist/{tasks-7P7XOGSC.js → tasks-3VQQG77M.js} +11 -11
  44. package/dist/{usage-KVVZQTZA.js → usage-UB4GLDGI.js} +4 -4
  45. package/dist/webui/assets/{GraphPage-DJhwG-72.js → GraphPage-BH_Mch3C.js} +2 -2
  46. package/dist/webui/assets/{GraphPage-DJhwG-72.js.map → GraphPage-BH_Mch3C.js.map} +1 -1
  47. package/dist/webui/assets/{index-Cpn2MjW0.js → index-CPFc-fiv.js} +25 -25
  48. package/dist/webui/assets/index-CPFc-fiv.js.map +1 -0
  49. package/dist/webui/index.html +1 -1
  50. package/package.json +2 -2
  51. package/dist/chunk-2WBJWKIK.js.map +0 -1
  52. package/dist/chunk-63H4ENYA.js.map +0 -1
  53. package/dist/chunk-BJZCBMU4.js.map +0 -1
  54. package/dist/chunk-DQMKYMUS.js.map +0 -1
  55. package/dist/chunk-VH3FI2X3.js.map +0 -1
  56. package/dist/dispatcher-W3PTGEKN.js +0 -22
  57. package/dist/ingest-FF67DX3F.js +0 -20
  58. package/dist/quality-6BN2ERKC.js +0 -25
  59. package/dist/retrieval-QLC3DNMW.js +0 -15
  60. package/dist/webui/assets/index-Cpn2MjW0.js.map +0 -1
  61. /package/dist/{chunk-MZTZKBRL.js.map → chunk-BTHB6Q43.js.map} +0 -0
  62. /package/dist/{chunk-AVUTQWZE.js.map → chunk-K3Z6YUKH.js.map} +0 -0
  63. /package/dist/{chunk-V3MYT3AT.js.map → chunk-KHE2ME44.js.map} +0 -0
  64. /package/dist/{chunk-YDVBXHX2.js.map → chunk-N23KB2S7.js.map} +0 -0
  65. /package/dist/{chunk-QPOOF2GK.js.map → chunk-NENWBA4Q.js.map} +0 -0
  66. /package/dist/{chunk-M5MPUMCJ.js.map → chunk-RELMDL4Y.js.map} +0 -0
  67. /package/dist/{chunk-S46JVROA.js.map → chunk-ROFI66JK.js.map} +0 -0
  68. /package/dist/{chunk-W75S5CK3.js.map → chunk-SJ23JYZJ.js.map} +0 -0
  69. /package/dist/{chunk-BTD3BYVV.js.map → chunk-T3DS4QYF.js.map} +0 -0
  70. /package/dist/{chunk-MQPMF5F3.js.map → chunk-TEDEFEXJ.js.map} +0 -0
  71. /package/dist/{chunk-EX5UTOIU.js.map → chunk-UJHXM7FK.js.map} +0 -0
  72. /package/dist/{chunk-FOJHR4JJ.js.map → chunk-VBX7MM2C.js.map} +0 -0
  73. /package/dist/{cleanup-EDWLCJPH.js.map → cleanup-FGPVQRYE.js.map} +0 -0
  74. /package/dist/{codex-trust-H6KNABHV.js.map → codex-trust-CWD4SYOS.js.map} +0 -0
  75. /package/dist/{dispatcher-W3PTGEKN.js.map → dispatcher-L77LKD7R.js.map} +0 -0
  76. /package/dist/{embeddings-W24SA6R3.js.map → embeddings-J24U3RAX.js.map} +0 -0
  77. /package/dist/{ingest-FF67DX3F.js.map → ingest-UU7VULPA.js.map} +0 -0
  78. /package/dist/{keychain-LVWMAS7D.js.map → keychain-23KFNHQ6.js.map} +0 -0
  79. /package/dist/{memory-value-GMYJ5NGO.js.map → memory-value-MWWV4P4X.js.map} +0 -0
  80. /package/dist/{provenance-KSBMVJO5.js.map → provenance-U2VAENS6.js.map} +0 -0
  81. /package/dist/{quality-6BN2ERKC.js.map → quality-PIYKKBIT.js.map} +0 -0
  82. /package/dist/{retrieval-QLC3DNMW.js.map → retrieval-DDYCXIUG.js.map} +0 -0
  83. /package/dist/{store-QYLHMBPE.js.map → store-DL6YQ6C3.js.map} +0 -0
  84. /package/dist/{tasks-7P7XOGSC.js.map → tasks-3VQQG77M.js.map} +0 -0
  85. /package/dist/{usage-KVVZQTZA.js.map → usage-UB4GLDGI.js.map} +0 -0
package/dist/cli.js CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
+ computeReliabilityReport,
3
4
  dispatchCodexNotify,
4
5
  ensureDailyBackup,
5
6
  executeAssistantCompletionHook,
@@ -14,6 +15,7 @@ import {
14
15
  formatInjectionContext,
15
16
  formatMaintenanceBacklogContext,
16
17
  formatPendingConfirmationsContext,
18
+ formatReliabilityReport,
17
19
  getDoctorReport,
18
20
  getHookCallStats,
19
21
  getLaunchAgentInfo,
@@ -53,20 +55,21 @@ import {
53
55
  unregisterStrayApps,
54
56
  verifyBackupIntegrity,
55
57
  writeRepoContextArtifact
56
- } from "./chunk-VH3FI2X3.js";
58
+ } from "./chunk-DH6RDBAI.js";
57
59
  import {
58
60
  hasCommand,
59
61
  installCodexHooks,
60
62
  resolveCodexHookTargets,
61
63
  resolveUserHomeDir,
62
64
  uninstallCodexHooks
63
- } from "./chunk-QPOOF2GK.js";
65
+ } from "./chunk-NENWBA4Q.js";
64
66
  import {
65
67
  closeDb,
66
68
  compileContext,
67
69
  compileContextHybrid,
68
70
  computeMetrics,
69
71
  createActivityEvent,
72
+ createLoopCoverageCache,
70
73
  createPolicy,
71
74
  deletePolicy,
72
75
  discoverLocalRepos,
@@ -86,7 +89,9 @@ import {
86
89
  listHistorySnippets,
87
90
  listPendingApprovals,
88
91
  listPolicies,
92
+ loadInjectedMemoryIds,
89
93
  loadRetrievalEvalFile,
94
+ loopRepoForMemory,
90
95
  pruneMemories,
91
96
  recordSignal,
92
97
  requestApproval,
@@ -100,7 +105,7 @@ import {
100
105
  startEvalSession,
101
106
  summarizeValueRetrievalEval,
102
107
  togglePolicy
103
- } from "./chunk-63H4ENYA.js";
108
+ } from "./chunk-J4EGDZIT.js";
104
109
  import {
105
110
  autoResolveContradictions,
106
111
  computeAllHealthScores,
@@ -109,14 +114,16 @@ import {
109
114
  formatHealthReport,
110
115
  getRepoQualityProfile,
111
116
  inferScope,
117
+ isHighRiskRule,
118
+ isNonUserCaptureContext,
112
119
  listContradictions,
113
120
  processCorrection,
114
121
  processReviewFeedback,
115
122
  resolveContradiction
116
- } from "./chunk-DQMKYMUS.js";
117
- import "./chunk-MQPMF5F3.js";
118
- import "./chunk-W75S5CK3.js";
119
- import "./chunk-MZTZKBRL.js";
123
+ } from "./chunk-J3QU7QT3.js";
124
+ import "./chunk-TEDEFEXJ.js";
125
+ import "./chunk-SJ23JYZJ.js";
126
+ import "./chunk-BTHB6Q43.js";
120
127
  import {
121
128
  confirmMemory,
122
129
  createMemory,
@@ -124,16 +131,21 @@ import {
124
131
  getAuditTrail,
125
132
  getMemory,
126
133
  getRecentAudit,
134
+ hasNonDurableProvenance,
127
135
  listMemories,
128
136
  listRepos,
129
137
  queryMemories,
130
138
  recordAudit,
139
+ recordAuditWithSnapshot,
131
140
  rejectMemory,
132
141
  rollbackMemory
133
- } from "./chunk-BJZCBMU4.js";
134
- import "./chunk-V3MYT3AT.js";
135
- import "./chunk-S46JVROA.js";
142
+ } from "./chunk-D6COH25L.js";
136
143
  import {
144
+ desc
145
+ } from "./chunk-KHE2ME44.js";
146
+ import "./chunk-ROFI66JK.js";
147
+ import {
148
+ CONFIDENCE,
137
149
  bootstrapEmbeddings,
138
150
  ensureEmbeddingProviderReady,
139
151
  flushEmbeddingJobs,
@@ -144,51 +156,351 @@ import {
144
156
  rebuildEmbeddingIndex,
145
157
  searchMemoryFtsIndex,
146
158
  semanticSearch,
159
+ upsertMemoryFtsRow,
147
160
  verifyEmbeddings
148
- } from "./chunk-2WBJWKIK.js";
161
+ } from "./chunk-27L3NQUO.js";
149
162
  import {
150
163
  deleteApiKey,
151
164
  hasKeychainApiKey,
152
165
  init_keychain,
153
166
  init_outbound_url,
154
167
  normalizeSyncRemoteUrl
155
- } from "./chunk-FOJHR4JJ.js";
156
- import "./chunk-M5MPUMCJ.js";
168
+ } from "./chunk-VBX7MM2C.js";
169
+ import "./chunk-RELMDL4Y.js";
157
170
  import {
158
- activityEvents,
159
171
  and,
172
+ auditTrail,
160
173
  eq,
161
174
  gt,
162
- gte,
163
175
  memories,
164
- memoryInjections,
165
- memoryValueEvents,
176
+ sql,
166
177
  syncState
167
- } from "./chunk-BTD3BYVV.js";
178
+ } from "./chunk-T3DS4QYF.js";
168
179
  import {
169
180
  init_define_RECALL_BUILD_INFO
170
- } from "./chunk-EDUIDJWZ.js";
181
+ } from "./chunk-IKD5BHN6.js";
171
182
 
172
183
  // src/cli.ts
173
184
  init_define_RECALL_BUILD_INFO();
174
185
  import { Command } from "commander";
175
- import { resolve as resolve3 } from "path";
176
- import { writeFileSync, readFileSync as readFileSync2, realpathSync } from "fs";
177
- import { join as join4 } from "path";
186
+
187
+ // src/cli/harness2.ts
188
+ init_define_RECALL_BUILD_INFO();
189
+
190
+ // src/importers/harness2.ts
191
+ init_define_RECALL_BUILD_INFO();
192
+ import { createHash } from "crypto";
193
+ import {
194
+ closeSync,
195
+ constants,
196
+ fstatSync,
197
+ openSync,
198
+ readSync
199
+ } from "fs";
200
+ import { resolve } from "path";
201
+ var MAX_DOCUMENT_BYTES = 128 * 1024;
202
+ var MAX_DOCUMENT_CODEPOINTS = 2e4;
203
+ var MAX_REPO_LENGTH = 255;
204
+ var MAX_SOURCE_REF_LENGTH = 2e3;
205
+ var HARNESS2_DEDUPE_PREFIX = "harness2sha256:";
206
+ function normalizeHarness2Experience(text) {
207
+ return text.replace(/^\uFEFF/u, "").replace(/\r\n?|\n/g, "\n").trim();
208
+ }
209
+ function previewHarness2Experience(text, options) {
210
+ const repo = validateRepo(options.repo);
211
+ const sourceRef = validateSourceRef(options.sourceRef);
212
+ validateRawDocument(text);
213
+ const content = normalizeHarness2Experience(text);
214
+ validateDocument(content);
215
+ const digest = sha256(`${repo}
216
+ ${content}`);
217
+ const id = uuidFromDigest(digest);
218
+ const cloudImport = {
219
+ provider: "harness2",
220
+ project: repo,
221
+ content,
222
+ sourceRef
223
+ };
224
+ return {
225
+ ...cloudImport,
226
+ digest,
227
+ id,
228
+ candidate: {
229
+ type: "gotcha",
230
+ scope: "repo",
231
+ status: "candidate",
232
+ confidence: 0.4,
233
+ source: "tool_outcome",
234
+ autoInject: false
235
+ },
236
+ cloudImport
237
+ };
238
+ }
239
+ function readHarness2Experience(file, options) {
240
+ const sourceRef = options.sourceRef ?? resolve(file);
241
+ validateSourceRef(sourceRef);
242
+ const flags = constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW;
243
+ let fd;
244
+ try {
245
+ fd = openSync(file, flags);
246
+ const stat = fstatSync(fd);
247
+ if (!stat.isFile()) throw new Error("Harness2 import requires a regular file.");
248
+ if (stat.size > MAX_DOCUMENT_BYTES) {
249
+ throw new Error(`Harness2 EXPERIENCE.md exceeds ${MAX_DOCUMENT_BYTES} bytes.`);
250
+ }
251
+ const buffer = Buffer.alloc(stat.size);
252
+ let offset = 0;
253
+ while (offset < buffer.length) {
254
+ const count = readSync(fd, buffer, offset, buffer.length - offset, offset);
255
+ if (count === 0) break;
256
+ offset += count;
257
+ }
258
+ if (offset !== stat.size) throw new Error("Harness2 EXPERIENCE.md changed while it was read.");
259
+ let text;
260
+ try {
261
+ text = new TextDecoder("utf-8", { fatal: true }).decode(buffer);
262
+ } catch {
263
+ throw new Error("Harness2 EXPERIENCE.md must be valid UTF-8.");
264
+ }
265
+ return previewHarness2Experience(text, { ...options, sourceRef });
266
+ } finally {
267
+ if (fd !== void 0) closeSync(fd);
268
+ }
269
+ }
270
+ function importHarness2Experience(db, preview) {
271
+ assertPreviewIntegrity(preview);
272
+ const { created, memory } = db.$client.transaction(() => {
273
+ const existing = db.select().from(memories).where(eq(memories.id, preview.id)).get();
274
+ if (existing) return { created: false, memory: existing };
275
+ const now = (/* @__PURE__ */ new Date()).toISOString();
276
+ const sourceFile = preview.sourceRef ?? "EXPERIENCE.md";
277
+ const generatedContext = `<agent-response> experimental Harness2 EXPERIENCE.md import; sourceRef=${sourceFile}; sha256=${preview.digest}`;
278
+ db.insert(memories).values({
279
+ id: preview.id,
280
+ type: "gotcha",
281
+ text: preview.content,
282
+ scope: "repo",
283
+ path_scope: null,
284
+ repo: preview.project,
285
+ status: "candidate",
286
+ confidence: 0.4,
287
+ source: "tool_outcome",
288
+ evidence: [
289
+ {
290
+ type: "review_feedback",
291
+ reported_by_user: false,
292
+ reviewer: "harness2",
293
+ timestamp: now,
294
+ context: generatedContext
295
+ },
296
+ { type: "repo_scan", file: sourceFile, timestamp: now }
297
+ ],
298
+ capture_context: null,
299
+ note: null,
300
+ supersedes: null,
301
+ dedupe_key: `${HARNESS2_DEDUPE_PREFIX}${preview.digest}`,
302
+ created_at: now,
303
+ updated_at: now,
304
+ last_validated_at: null,
305
+ last_injected_at: null,
306
+ injection_count: 0,
307
+ override_count: 0,
308
+ repetition_count: 0,
309
+ auto_inject: false
310
+ }).run();
311
+ const inserted = db.select().from(memories).where(and(
312
+ eq(memories.id, preview.id),
313
+ eq(memories.repo, preview.project)
314
+ )).get();
315
+ if (!inserted) throw new Error("Harness2 import did not retain its inserted candidate.");
316
+ upsertMemoryFtsRow(db, inserted);
317
+ recordAudit(db, preview.id, "created", "harness2", "imported EXPERIENCE.md");
318
+ return { created: true, memory: inserted };
319
+ }).immediate();
320
+ return { id: memory.id, created, memory, preview };
321
+ }
322
+ function validateRepo(value) {
323
+ const repo = value?.trim();
324
+ if (!repo) throw new Error("Harness2 import requires --repo.");
325
+ if (codePointLength(repo) > MAX_REPO_LENGTH) {
326
+ throw new Error(`Harness2 repo must be at most ${MAX_REPO_LENGTH} characters.`);
327
+ }
328
+ if (repo.includes("\0")) throw new Error("Harness2 repo must not contain NUL.");
329
+ if (/[\r\n]/u.test(repo)) throw new Error("Harness2 repo must be a single line.");
330
+ return repo;
331
+ }
332
+ function validateSourceRef(value) {
333
+ if (value == null) return null;
334
+ const sourceRef = value.trim();
335
+ if (!sourceRef) return null;
336
+ if (codePointLength(sourceRef) > MAX_SOURCE_REF_LENGTH) {
337
+ throw new Error(`Harness2 sourceRef must be at most ${MAX_SOURCE_REF_LENGTH} characters.`);
338
+ }
339
+ if (sourceRef.includes("\0")) throw new Error("Harness2 sourceRef must not contain NUL.");
340
+ return sourceRef;
341
+ }
342
+ function validateDocument(content) {
343
+ if (!content) throw new Error("Harness2 EXPERIENCE.md must not be empty.");
344
+ if (content.includes("\0")) throw new Error("Harness2 EXPERIENCE.md must not contain NUL.");
345
+ if (codePointLength(content) > MAX_DOCUMENT_CODEPOINTS) {
346
+ throw new Error(`Harness2 EXPERIENCE.md must be at most ${MAX_DOCUMENT_CODEPOINTS} Unicode code points.`);
347
+ }
348
+ if (Buffer.byteLength(content, "utf8") > MAX_DOCUMENT_BYTES) {
349
+ throw new Error(`Harness2 EXPERIENCE.md exceeds ${MAX_DOCUMENT_BYTES} bytes.`);
350
+ }
351
+ }
352
+ function validateRawDocument(text) {
353
+ if (text.includes("\0")) throw new Error("Harness2 EXPERIENCE.md must not contain NUL.");
354
+ if (Buffer.byteLength(text, "utf8") > MAX_DOCUMENT_BYTES) {
355
+ throw new Error(`Harness2 EXPERIENCE.md exceeds ${MAX_DOCUMENT_BYTES} bytes.`);
356
+ }
357
+ for (let index = 0; index < text.length; index += 1) {
358
+ const unit = text.charCodeAt(index);
359
+ if (unit >= 55296 && unit <= 56319) {
360
+ const next = text.charCodeAt(index + 1);
361
+ if (next >= 56320 && next <= 57343) {
362
+ index += 1;
363
+ continue;
364
+ }
365
+ throw new Error("Harness2 EXPERIENCE.md must not contain an unpaired UTF-16 surrogate.");
366
+ }
367
+ if (unit >= 56320 && unit <= 57343) {
368
+ throw new Error("Harness2 EXPERIENCE.md must not contain an unpaired UTF-16 surrogate.");
369
+ }
370
+ }
371
+ }
372
+ function assertPreviewIntegrity(preview) {
373
+ const expected = previewHarness2Experience(preview.content, {
374
+ repo: preview.project,
375
+ sourceRef: preview.sourceRef ?? void 0
376
+ });
377
+ if (preview.digest !== expected.digest || preview.id !== expected.id) {
378
+ throw new Error("Harness2 preview digest does not match its content.");
379
+ }
380
+ }
381
+ function sha256(value) {
382
+ return createHash("sha256").update(value, "utf8").digest("hex");
383
+ }
384
+ function uuidFromDigest(digest) {
385
+ const bytes = Buffer.from(digest.slice(0, 32), "hex");
386
+ bytes[6] = bytes[6] & 15 | 80;
387
+ bytes[8] = bytes[8] & 63 | 128;
388
+ const hex = bytes.toString("hex");
389
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
390
+ }
391
+ function codePointLength(value) {
392
+ return Array.from(value).length;
393
+ }
394
+
395
+ // src/cli/harness2.ts
396
+ function registerHarness2Commands(program2) {
397
+ const harness2 = program2.command("harness2").description("Import experimental Harness2 experience documents");
398
+ harness2.command("import <file>").description("Preview or import one Harness2 EXPERIENCE.md document").requiredOption("--repo <slug>", "Repository slug for the candidate").option("--source-ref <ref>", "Optional original Harness2 source reference").option("--apply", "Write the candidate after previewing it").option("--json", "Emit a cloud-import compatible JSON payload").action((file, options) => {
399
+ const preview = readHarness2Experience(file, {
400
+ repo: options.repo,
401
+ sourceRef: options.sourceRef
402
+ });
403
+ const result = options.apply ? importHarness2Experience(initDb(), preview) : void 0;
404
+ if (options.json) {
405
+ console.log(JSON.stringify({
406
+ applied: Boolean(options.apply),
407
+ created: result?.created ?? false,
408
+ preview,
409
+ memory: result?.memory ?? null,
410
+ cloudImport: preview.cloudImport
411
+ }, null, 2));
412
+ return;
413
+ }
414
+ const memory = result?.memory;
415
+ const verb = options.apply ? result.created ? "Imported" : "Already imported" : "Preview";
416
+ console.log(`${verb} Harness2 candidate: ${memory?.id ?? preview.id}`);
417
+ console.log(` repo: ${memory?.repo ?? preview.project}`);
418
+ console.log(` digest: ${preview.digest}`);
419
+ if (memory) {
420
+ console.log(` status: ${memory.status} (confidence ${memory.confidence.toFixed(2)}, auto-inject ${memory.auto_inject ? "on" : "off"})`);
421
+ } else {
422
+ console.log(` status: preview candidate (confidence 0.40, auto-inject off)`);
423
+ }
424
+ console.log(` content: ${preview.content.slice(0, 160)}${preview.content.length > 160 ? "\u2026" : ""}`);
425
+ if (!options.apply) {
426
+ console.log(`
427
+ To import: recall harness2 import ${JSON.stringify(file)} --repo ${JSON.stringify(preview.project)} --apply`);
428
+ }
429
+ if (memory?.status === "candidate") {
430
+ console.log(`To confirm after review: recall confirm ${memory.id}`);
431
+ } else if (memory?.status === "rejected") {
432
+ console.log(`This retained import is rejected. To review it again: recall reactivate ${memory.id}`);
433
+ }
434
+ });
435
+ }
436
+
437
+ // src/cli.ts
438
+ import { resolve as resolve4 } from "path";
439
+ import { writeFileSync, readFileSync as readFileSync3, realpathSync } from "fs";
440
+ import { join as join5 } from "path";
178
441
 
179
442
  // src/ump/serve.ts
180
443
  init_define_RECALL_BUILD_INFO();
181
444
  import {
182
445
  UmpServer,
183
- generateKeyPair,
184
446
  createHttpServer,
185
447
  createMcpServer
186
448
  } from "@universalmemoryprotocol/core";
187
- import { RecallStore, fromAmpId } from "@universalmemoryprotocol/core/adapters/recall";
449
+ import { RecallStore, fromAmpId as fromAmpId2 } from "@universalmemoryprotocol/core/adapters/recall";
188
450
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
189
451
 
190
452
  // src/ump/backend.ts
191
453
  init_define_RECALL_BUILD_INFO();
454
+ import {
455
+ fromAmpId,
456
+ kindToRecallType,
457
+ recallMemoryToRecord,
458
+ toUmpId
459
+ } from "@universalmemoryprotocol/core/adapters/recall";
460
+
461
+ // src/ump/records.ts
462
+ init_define_RECALL_BUILD_INFO();
463
+ function storedUmpRecord(value) {
464
+ if (!value || typeof value !== "object") return void 0;
465
+ const record = value;
466
+ if (record.ump !== "1.0" || typeof record.id !== "string" || typeof record.kind !== "string" || !record.body || typeof record.body.text !== "string" || !record.scope || typeof record.scope.owner !== "string" || !record.time || typeof record.time.created !== "string") {
467
+ return void 0;
468
+ }
469
+ return record;
470
+ }
471
+ function canonicalizeStoredRecord(record, canonicalId, previous) {
472
+ const validTo = earliestValidTo(previous?.time.valid_to, record.time.valid_to);
473
+ return {
474
+ ...record,
475
+ id: canonicalId,
476
+ time: {
477
+ ...record.time,
478
+ ...validTo !== void 0 ? { valid_to: validTo } : {}
479
+ },
480
+ // A replacement closes a predecessor and adds its successor. Never lose
481
+ // that history if an adapter sends a partial lifecycle rewrite.
482
+ supersedes: unionStrings(previous?.supersedes, record.supersedes),
483
+ superseded_by: unionStrings(previous?.superseded_by, record.superseded_by),
484
+ // Relations are a full-record field. A revise may intentionally remove
485
+ // one, so only lifecycle lineage is merged defensively above.
486
+ relations: record.relations,
487
+ integrity: void 0
488
+ };
489
+ }
490
+ function earliestValidTo(previous, incoming) {
491
+ if (previous == null) return incoming;
492
+ if (incoming == null) return previous;
493
+ const previousAt = Date.parse(previous);
494
+ const incomingAt = Date.parse(incoming);
495
+ if (Number.isNaN(previousAt) || Number.isNaN(incomingAt)) return previous;
496
+ return previousAt <= incomingAt ? previous : incoming;
497
+ }
498
+ function unionStrings(left, right) {
499
+ const values = [...left ?? [], ...right ?? []];
500
+ return values.length ? [...new Set(values)] : void 0;
501
+ }
502
+
503
+ // src/ump/backend.ts
192
504
  var SEARCH_MIN_SIM = parseFloat(process.env.UMP_RECALL_MIN_SIM ?? "0.3");
193
505
  var RRF_K = 60;
194
506
  function toRecallMemory(m) {
@@ -214,56 +526,195 @@ function toRecallMemory(m) {
214
526
  };
215
527
  }
216
528
  function tokenOverlap(query, text) {
217
- const q = new Set(query.toLowerCase().split(/[^a-z0-9]+/).filter((t2) => t2.length > 1));
218
- if (q.size === 0) return 0;
219
- const t = text.toLowerCase();
529
+ const queryTokens = new Set(query.toLowerCase().split(/[^a-z0-9]+/).filter((t) => t.length > 1));
530
+ if (queryTokens.size === 0) return 0;
531
+ const candidate = text.toLowerCase();
220
532
  let hits = 0;
221
- for (const w of q) if (t.includes(w)) hits++;
222
- return hits / q.size;
533
+ for (const word of queryTokens) if (candidate.includes(word)) hits++;
534
+ return hits / queryTokens.size;
535
+ }
536
+ function statusForNative(memory) {
537
+ if (memory.status === "rejected") return "tombstoned";
538
+ const saved = storedUmpRecord(memory.capture_context?.ump_record);
539
+ if (saved?.lifecycle?.status === "tombstoned") return "tombstoned";
540
+ return memory.status === "active" ? "active" : "candidate";
541
+ }
542
+ function recordForMemory(memory, owner) {
543
+ const saved = storedUmpRecord(memory.capture_context?.ump_record);
544
+ if (saved) {
545
+ return {
546
+ ...saved,
547
+ id: toUmpId(memory.id),
548
+ integrity: void 0,
549
+ lifecycle: {
550
+ ...saved.lifecycle,
551
+ status: statusForNative(memory)
552
+ }
553
+ };
554
+ }
555
+ return recallMemoryToRecord(toRecallMemory(memory), owner);
556
+ }
557
+ function matchesScope(record, requested) {
558
+ if (!requested) return true;
559
+ return Object.keys(requested).every((key) => requested[key] === void 0 || record.scope[key] === requested[key]);
223
560
  }
224
- function makeRecallBackend(db) {
561
+ function matchesFilter(record, filter) {
562
+ if (!filter) return true;
563
+ const status = record.lifecycle?.status ?? "active";
564
+ if (filter.status && !filter.status.includes(status)) return false;
565
+ if (filter.kind && !filter.kind.includes(record.kind)) return false;
566
+ if (filter.valid_at) {
567
+ const at = Date.parse(filter.valid_at);
568
+ const from = Date.parse(record.time.valid_from ?? record.time.created);
569
+ const to = record.time.valid_to == null ? Number.POSITIVE_INFINITY : Date.parse(record.time.valid_to);
570
+ if (!Number.isFinite(at) || !Number.isFinite(from) || Number.isNaN(to)) return false;
571
+ if (at < from || at > to) return false;
572
+ }
573
+ return true;
574
+ }
575
+ function candidateMatches(memory, owner, request) {
576
+ const record = recordForMemory(memory, owner);
577
+ if (statusForNative(memory) === "tombstoned") return false;
578
+ if (record.scope.owner !== owner) return false;
579
+ return matchesScope(record, request.scope) && matchesFilter(record, request.filter);
580
+ }
581
+ function asTemporalScope(record) {
582
+ if (record.scope.project) {
583
+ return { scope: "repo", repo: record.scope.project, path: null };
584
+ }
585
+ return { scope: "global", repo: null, path: null };
586
+ }
587
+ function confidenceFor(record) {
588
+ const confidence = record.lifecycle?.confidence ?? 0.8;
589
+ return record.lifecycle?.status === "candidate" ? Math.min(confidence, 0.59) : Math.max(confidence, 0.6);
590
+ }
591
+ function captureContextFor(record, canonicalId, previous) {
592
+ const prior = storedUmpRecord(previous?.capture_context?.ump_record);
593
+ return {
594
+ ...previous?.capture_context ?? {},
595
+ ump_kind: record.kind,
596
+ ump_record: canonicalizeStoredRecord(record, canonicalId, prior)
597
+ };
598
+ }
599
+ function putUmpRecord(db, record, existingId) {
600
+ const targetId = existingId ?? (record.id.startsWith("urn:ump:") ? safeRecallId(record.id) : void 0);
601
+ const existing = targetId ? getMemory(db, targetId) : void 0;
602
+ if (existing) {
603
+ const captureContext = captureContextFor(record, toUmpId(existing.id), existing);
604
+ const scope2 = asTemporalScope(record);
605
+ const tombstoned = record.lifecycle?.status === "tombstoned";
606
+ const nativeStatus = existing.status === "rejected" ? "rejected" : record.lifecycle?.status === "candidate" ? "candidate" : "active";
607
+ db.update(memories).set({
608
+ text: record.body.text,
609
+ type: kindToRecallType(record.kind),
610
+ scope: scope2.scope,
611
+ repo: scope2.repo,
612
+ path_scope: scope2.path,
613
+ confidence: confidenceFor(record),
614
+ status: nativeStatus,
615
+ capture_context: captureContext,
616
+ // A UMP record can carry validity, source, and structured semantics
617
+ // that the instruction compiler does not understand. Keep all direct
618
+ // UMP writes out of automatic instructions until that path is proven.
619
+ auto_inject: false,
620
+ updated_at: (/* @__PURE__ */ new Date()).toISOString()
621
+ }).where(eq(memories.id, existing.id)).run();
622
+ if (tombstoned && existing.status !== "rejected") {
623
+ rejectMemory(db, existing.id, "ump");
624
+ }
625
+ return existing.id;
626
+ }
627
+ const scope = asTemporalScope(record);
628
+ const id = db.$client.transaction(() => {
629
+ const initialContext = {
630
+ ump_kind: record.kind,
631
+ ump_record: canonicalizeStoredRecord(record, record.id, void 0)
632
+ };
633
+ const createdId = createMemory(db, {
634
+ type: kindToRecallType(record.kind),
635
+ text: record.body.text,
636
+ scope: scope.scope,
637
+ repo: scope.repo,
638
+ path_scope: scope.path,
639
+ source: "user_correction",
640
+ confidence: confidenceFor(record),
641
+ // Equal text with distinct validity windows is intentional.
642
+ dedupe: false,
643
+ auto_inject: false,
644
+ capture_context: initialContext
645
+ });
646
+ db.update(memories).set({
647
+ capture_context: captureContextFor(record, toUmpId(createdId), void 0),
648
+ auto_inject: false,
649
+ updated_at: (/* @__PURE__ */ new Date()).toISOString()
650
+ }).where(eq(memories.id, createdId)).run();
651
+ return createdId;
652
+ })();
653
+ if (record.lifecycle?.status === "tombstoned") rejectMemory(db, id, "ump");
654
+ return id;
655
+ }
656
+ function safeRecallId(umpId) {
657
+ try {
658
+ return fromAmpId(umpId);
659
+ } catch {
660
+ return void 0;
661
+ }
662
+ }
663
+ function makeRecallBackend(db, owner) {
225
664
  const umpSessionId = `ump:${process.pid}:${Date.now().toString(36)}`;
226
665
  return {
227
- queryMemories: (f) => queryMemories(db, { repo: f.repo }).map(toRecallMemory),
666
+ queryMemories: (filter) => queryMemories(db, { repo: filter.repo }).map(toRecallMemory),
228
667
  getMemory: (id) => {
229
- const m = getMemory(db, id);
230
- return m ? toRecallMemory(m) : void 0;
668
+ const memory = getMemory(db, id);
669
+ return memory ? toRecallMemory(memory) : void 0;
231
670
  },
232
- compileHybrid: async ({ query, repo, limit }) => {
233
- const cap = limit ?? 8;
234
- const window = Math.max(cap * 5, 30);
235
- const rrf = /* @__PURE__ */ new Map();
236
- const add = (id, rank) => rrf.set(id, (rrf.get(id) ?? 0) + 1 / (RRF_K + rank));
237
- const cfg = loadEmbeddingConfigFromEnv();
238
- if (cfg) {
671
+ compileHybrid: async (request) => {
672
+ const cap = request.limit ?? 8;
673
+ const totalCandidates = queryMemories(db, {}).length;
674
+ const window = Math.max(totalCandidates, cap);
675
+ const scores = /* @__PURE__ */ new Map();
676
+ const add = (id, rank) => scores.set(id, (scores.get(id) ?? 0) + 1 / (RRF_K + rank));
677
+ const config = loadEmbeddingConfigFromEnv();
678
+ if (config && window > 0) {
239
679
  try {
240
- const sem = await semanticSearch(
680
+ const semantic = await semanticSearch(
241
681
  db,
242
- query,
243
- { ...cfg, similarity_threshold: SEARCH_MIN_SIM },
244
- { repo, limit: window }
682
+ request.query,
683
+ { ...config, similarity_threshold: SEARCH_MIN_SIM },
684
+ { repo: request.repo, limit: window }
245
685
  );
246
- sem.forEach((s, i) => add(s.memory.id, i));
686
+ semantic.forEach((result, index) => add(result.memory.id, index));
247
687
  } catch {
248
688
  }
249
689
  }
250
- try {
251
- searchMemoryFtsIndex(db, query, { repo, limit: window }).forEach((l, i) => add(l.memory_id, i));
252
- } catch {
253
- }
254
- if (rrf.size > 0) {
255
- const out = [];
256
- for (const [id, score] of [...rrf.entries()].sort((a, b) => b[1] - a[1])) {
257
- const m = getMemory(db, id);
258
- if (m && (m.status === "active" || m.status === "candidate")) {
259
- out.push({ memory: toRecallMemory(m), score });
260
- if (out.length >= cap) break;
261
- }
690
+ if (window > 0) {
691
+ try {
692
+ searchMemoryFtsIndex(db, request.query, { repo: request.repo, limit: window }).forEach((result, index) => add(result.memory_id, index));
693
+ } catch {
262
694
  }
263
- if (out.length > 0) return out;
264
695
  }
265
- return queryMemories(db, {}).filter((m) => m.status === "active" || m.status === "candidate").map((m) => ({ memory: toRecallMemory(m), score: tokenOverlap(query, m.text) })).filter((r) => r.score > 0).sort((a, b) => b.score - a.score).slice(0, cap);
696
+ const ranked = [];
697
+ for (const [id, score] of [...scores.entries()].sort((a, b) => b[1] - a[1])) {
698
+ const memory = getMemory(db, id);
699
+ if (!memory || !candidateMatches(memory, owner, request)) continue;
700
+ ranked.push({ memory: toRecallMemory(memory), score });
701
+ if (ranked.length >= cap) return ranked;
702
+ }
703
+ const rankedIds = new Set(scores.keys());
704
+ const fallback = queryMemories(db, {}).filter((memory) => !rankedIds.has(memory.id)).filter((memory) => candidateMatches(memory, owner, request)).map((memory) => ({ memory, score: tokenOverlap(request.query, memory.text) })).sort((a, b) => b.score - a.score);
705
+ for (const result of fallback) {
706
+ ranked.push({ memory: toRecallMemory(result.memory), score: result.score });
707
+ if (ranked.length >= cap) break;
708
+ }
709
+ return ranked;
266
710
  },
711
+ putRecord: async (record, existingId) => {
712
+ const id = putUmpRecord(db, record, existingId);
713
+ await flushEmbeddingJobs();
714
+ return id;
715
+ },
716
+ // SDK 1.0.2 compatibility only. SDK 1.0.3 uses putRecord for all direct
717
+ // writes, including lifecycle revisions and tombstones.
267
718
  storeDirect: async ({ text, type, scope, repo, confidence, kind }) => {
268
719
  const id = createMemory(db, {
269
720
  type,
@@ -272,6 +723,7 @@ function makeRecallBackend(db) {
272
723
  repo: repo ?? null,
273
724
  source: "user_correction",
274
725
  confidence,
726
+ dedupe: false,
275
727
  capture_context: { ump_kind: kind }
276
728
  });
277
729
  await flushEmbeddingJobs();
@@ -279,34 +731,103 @@ function makeRecallBackend(db) {
279
731
  },
280
732
  tombstone: (id) => rejectMemory(db, id, "ump"),
281
733
  capture: async ({ text, repo, path }) => {
282
- const res = await processCorrection(db, text, {
283
- // Unique per server process: a constant "ump" session id made
284
- // stablePromptId() dedupe identical rule text forever, so a rule
285
- // re-sent in a later UMP session was silently never re-extracted.
734
+ const result = await processCorrection(db, text, {
286
735
  sessionId: umpSessionId,
287
736
  repo,
288
737
  path,
289
738
  agent: "ump",
290
739
  force_semantic_capture: true
291
740
  });
292
- return { ids: res.ids ?? [] };
741
+ return { ids: result.ids ?? [] };
293
742
  }
294
743
  };
295
744
  }
296
745
 
746
+ // src/ump/identity.ts
747
+ init_define_RECALL_BUILD_INFO();
748
+ import {
749
+ closeSync as closeSync2,
750
+ fchmodSync,
751
+ fsyncSync,
752
+ linkSync,
753
+ openSync as openSync2,
754
+ readFileSync,
755
+ unlinkSync,
756
+ writeSync
757
+ } from "fs";
758
+ import { dirname, join } from "path";
759
+ import { randomBytes } from "crypto";
760
+ import { generateKeyPair } from "@universalmemoryprotocol/core";
761
+ var SEED_FILE = "ump-operator-ed25519.seed";
762
+ var ED25519_SEED_LENGTH = 32;
763
+ function loadPersistedUmpOperatorKey(dbPath = getDbPath()) {
764
+ const path = join(dirname(dbPath), SEED_FILE);
765
+ let seed;
766
+ try {
767
+ seed = new Uint8Array(readFileSync(path));
768
+ } catch (error) {
769
+ if (!isMissingFile(error)) throw new Error("Unable to read Recall UMP operator identity");
770
+ seed = createSeed(path);
771
+ }
772
+ if (seed.byteLength !== ED25519_SEED_LENGTH) {
773
+ throw new Error("Invalid persisted Recall UMP operator identity");
774
+ }
775
+ return generateKeyPair(seed);
776
+ }
777
+ function createSeed(path) {
778
+ const seed = randomBytes(ED25519_SEED_LENGTH);
779
+ const temporaryPath = `${path}.${process.pid}.${randomBytes(8).toString("hex")}.tmp`;
780
+ let fd;
781
+ try {
782
+ fd = openSync2(temporaryPath, "wx", 384);
783
+ fchmodSync(fd, 384);
784
+ writeSync(fd, seed);
785
+ fsyncSync(fd);
786
+ closeSync2(fd);
787
+ fd = void 0;
788
+ linkSync(temporaryPath, path);
789
+ return seed;
790
+ } catch (error) {
791
+ if (isAlreadyExists(error)) {
792
+ const existing = new Uint8Array(readFileSync(path));
793
+ if (existing.byteLength !== ED25519_SEED_LENGTH) {
794
+ throw new Error("Invalid persisted Recall UMP operator identity");
795
+ }
796
+ return existing;
797
+ }
798
+ throw new Error("Unable to create Recall UMP operator identity");
799
+ } finally {
800
+ if (fd !== void 0) closeSync2(fd);
801
+ try {
802
+ unlinkSync(temporaryPath);
803
+ } catch {
804
+ }
805
+ }
806
+ }
807
+ function isMissingFile(error) {
808
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
809
+ }
810
+ function isAlreadyExists(error) {
811
+ return typeof error === "object" && error !== null && "code" in error && error.code === "EEXIST";
812
+ }
813
+
297
814
  // src/ump/serve.ts
298
815
  function createRecallUmpServer(db, opts = {}) {
299
- const key = generateKeyPair();
816
+ const dbPath = db.$client.name;
817
+ if (!opts.key && (!dbPath || dbPath === ":memory:" || dbPath.startsWith("file::memory:"))) {
818
+ throw new Error("In-memory Recall UMP servers require an injected operator key");
819
+ }
820
+ const key = opts.key ?? loadPersistedUmpOperatorKey(dbPath);
300
821
  const owner = key.did;
301
822
  const server = new UmpServer({
302
823
  name: "recall",
303
- version: "ump-0.1",
824
+ version: "ump-1.0.4",
304
825
  conformance: "L1",
305
- store: new RecallStore(makeRecallBackend(db), { owner, smart: opts.smart }),
826
+ store: new RecallStore(makeRecallBackend(db, owner), { owner, smart: opts.smart }),
306
827
  key,
307
828
  onFeedback: async (req) => {
308
829
  signalOutcomeFallback(db, {
309
- memory_id: fromAmpId(req.id),
830
+ memory_id: fromAmpId2(req.id),
310
831
  session_id: req.session ?? `ump:${process.pid}`,
311
832
  injected: true,
312
833
  outcome: req.outcome,
@@ -344,7 +865,7 @@ async function runUmpServer(opts = {}) {
344
865
  });
345
866
  }
346
867
  if (opts.stdio ?? !opts.http) {
347
- await createMcpServer(server).connect(new StdioServerTransport());
868
+ await createMcpServer(server, { owner }).connect(new StdioServerTransport());
348
869
  process.stderr.write(`[recall ump] MCP binding on stdio (owner ${owner})
349
870
  `);
350
871
  }
@@ -386,7 +907,22 @@ async function pushMemories(db, config) {
386
907
  if (localMemories.length === 0) {
387
908
  return { pushed: 0, version: state.last_push_version };
388
909
  }
389
- const payload = localMemories.map((m) => ({
910
+ const syncableMemories = localMemories.filter(
911
+ (memory) => !hasUmpRecordMarker(memory.capture_context)
912
+ );
913
+ const pushedThroughVersion = Math.max(
914
+ ...localMemories.map((memory) => memory.sync_version)
915
+ );
916
+ if (syncableMemories.length === 0) {
917
+ updateSyncState(db, {
918
+ remote_url: remoteUrl,
919
+ team_id: config.team_id,
920
+ last_push_at: (/* @__PURE__ */ new Date()).toISOString(),
921
+ last_push_version: pushedThroughVersion
922
+ });
923
+ return { pushed: 0, version: pushedThroughVersion };
924
+ }
925
+ const payload = syncableMemories.map((m) => ({
390
926
  ...m,
391
927
  origin_id: m.id,
392
928
  evidence: typeof m.evidence === "string" ? JSON.parse(m.evidence) : m.evidence
@@ -411,9 +947,7 @@ async function pushMemories(db, config) {
411
947
  remote_url: remoteUrl,
412
948
  team_id: config.team_id,
413
949
  last_push_at: (/* @__PURE__ */ new Date()).toISOString(),
414
- last_push_version: Math.max(
415
- ...localMemories.map((m) => m.sync_version)
416
- )
950
+ last_push_version: pushedThroughVersion
417
951
  });
418
952
  return result;
419
953
  }
@@ -439,8 +973,10 @@ async function pullMemories(db, config) {
439
973
  let pulled = 0;
440
974
  let conflicts = 0;
441
975
  for (const remote of data.memories) {
976
+ if (hasUmpRecordMarker(remote.capture_context)) continue;
442
977
  const localMem = db.select().from(memories).where(eq(memories.id, remote.origin_id)).get();
443
978
  if (localMem) {
979
+ if (hasUmpRecordMarker(localMem.capture_context)) continue;
444
980
  if (remote.updated_at > localMem.updated_at) {
445
981
  db.update(memories).set({
446
982
  text: remote.text,
@@ -483,6 +1019,21 @@ async function pullMemories(db, config) {
483
1019
  });
484
1020
  return { pulled, conflicts };
485
1021
  }
1022
+ function hasUmpRecordMarker(captureContext) {
1023
+ const context = parseCaptureContext(captureContext);
1024
+ return context !== null && Object.prototype.hasOwnProperty.call(context, "ump_record");
1025
+ }
1026
+ function parseCaptureContext(value) {
1027
+ let context = value;
1028
+ if (typeof context === "string") {
1029
+ try {
1030
+ context = JSON.parse(context);
1031
+ } catch {
1032
+ return null;
1033
+ }
1034
+ }
1035
+ return context !== null && typeof context === "object" && !Array.isArray(context) ? context : null;
1036
+ }
486
1037
  async function sync(db, config) {
487
1038
  const errors = [];
488
1039
  let pushed = 0;
@@ -532,140 +1083,158 @@ async function joinTeam(config, teamId) {
532
1083
  if (!resp.ok) throw new Error(`Failed to join team: ${resp.statusText}`);
533
1084
  }
534
1085
 
535
- // src/reliability/report.ts
1086
+ // src/pruning/restore.ts
536
1087
  init_define_RECALL_BUILD_INFO();
537
- function ratio(numerator, denominator) {
538
- return denominator > 0 ? numerator / denominator : 0;
539
- }
540
- function computeReliabilityReport(db, options = {}) {
541
- const end = (/* @__PURE__ */ new Date()).toISOString();
542
- const start = options.since ?? new Date(Date.now() - 14 * 864e5).toISOString();
543
- const activityConditions = [gte(activityEvents.created_at, start)];
544
- const injectionConditions = [gte(memoryInjections.injected_at, start)];
545
- const valueConditions = [gte(memoryValueEvents.created_at, start)];
546
- if (options.repo) {
547
- activityConditions.push(eq(activityEvents.repo, options.repo));
548
- injectionConditions.push(eq(memoryInjections.repo, options.repo));
549
- valueConditions.push(eq(memoryValueEvents.repo, options.repo));
550
- }
551
- const activity = db.select().from(activityEvents).where(and(...activityConditions)).all();
552
- const injections = db.select().from(memoryInjections).where(and(...injectionConditions)).all();
553
- const valueEvents = db.select().from(memoryValueEvents).where(and(...valueConditions)).all();
554
- const lifecycle = activity.filter(
555
- (event) => event.session_id && (event.event_type === "session_start" || event.event_type === "session_end")
556
- );
557
- const sessionIds = new Set(lifecycle.map((event) => event.session_id));
558
- const attributedSessionIds = new Set(
559
- lifecycle.filter((event) => Boolean(event.repo)).map((event) => event.session_id)
560
- );
561
- const scopedSessionIds = new Set(attributedSessionIds);
562
- for (const event of lifecycle) {
563
- if (!event.session_id) continue;
564
- const request = typeof event.request === "string" ? JSON.parse(event.request) : event.request;
565
- const repoPath = typeof request?.repo_path === "string" ? request.repo_path : "";
566
- if (repoPath && repoAttributionExpected(repoPath)) scopedSessionIds.add(event.session_id);
567
- }
568
- const emittedPairs = /* @__PURE__ */ new Set();
569
- for (const event of activity) {
570
- if (event.event_type !== "session_event" || !event.session_id) continue;
571
- const request = typeof event.request === "string" ? JSON.parse(event.request) : event.request;
572
- if (request?.name !== "memory_emitted") continue;
573
- const memoryIds = Array.isArray(event.memory_ids) ? event.memory_ids : [];
574
- for (const memoryId of memoryIds) {
575
- emittedPairs.add(`${event.session_id}\0${memoryId}`);
576
- }
577
- }
578
- const selectedPairs = new Set(
579
- injections.map((injection) => `${injection.session_id}\0${injection.memory_id}`)
580
- );
581
- const emittedSelected = [...emittedPairs].filter((key) => selectedPairs.has(key)).length;
582
- const observedUses = valueEvents.filter((event) => event.event_type === "used").length;
583
- const resolvedOutcomes = injections.filter((injection) => injection.outcome != null).length;
584
- const retrievalMisses = valueEvents.filter((event) => event.event_type === "retrieval_miss").length;
585
- const retrievalUses = valueEvents.filter((event) => event.event_type === "used").length;
586
- const candidates = db.select({ id: memories.id, auto_inject: memories.auto_inject, repo: memories.repo }).from(memories).where(eq(memories.status, "candidate")).all();
587
- const injectableCandidates = candidates.filter((memory) => memory.auto_inject);
588
- const candidatesByRepo = /* @__PURE__ */ new Map();
589
- for (const memory of injectableCandidates) {
590
- const key = memory.repo ?? "global";
591
- candidatesByRepo.set(key, (candidatesByRepo.get(key) ?? 0) + 1);
592
- }
593
- const candidateBacklog = options.repo ? injectableCandidates.length : Math.max(0, ...candidatesByRepo.values());
594
- const activeMemories = db.select({ id: memories.id }).from(memories).where(eq(memories.status, "active")).all().length;
595
- const repoAttribution = ratio(attributedSessionIds.size, scopedSessionIds.size);
596
- const emissionCoverage = ratio(emittedSelected, selectedPairs.size);
597
- const outcomeCoverage = ratio(resolvedOutcomes, emittedSelected);
598
- const retrievalObservations = retrievalMisses + retrievalUses;
599
- const checks = [
600
- { name: "repo_attribution", status: scopedSessionIds.size === 0 ? "warn" : repoAttribution >= 0.95 ? "pass" : repoAttribution >= 0.8 ? "warn" : "fail", value: repoAttribution, target: ">=95%" },
601
- { name: "emission_coverage", status: selectedPairs.size === 0 ? "warn" : emissionCoverage >= 0.99 ? "pass" : emissionCoverage >= 0.95 ? "warn" : "fail", value: emissionCoverage, target: ">=99%" },
602
- { name: "outcome_coverage", status: emittedSelected === 0 ? "warn" : outcomeCoverage >= 0.8 ? "pass" : outcomeCoverage >= 0.5 ? "warn" : "fail", value: outcomeCoverage, target: ">=80%" },
603
- { name: "retrieval_observations", status: retrievalObservations >= 20 ? "pass" : retrievalObservations >= 5 ? "warn" : "fail", value: retrievalObservations, target: ">=20" },
604
- { name: "candidate_backlog", status: candidateBacklog <= 50 ? "pass" : candidateBacklog <= 100 ? "warn" : "fail", value: candidateBacklog, target: "<=50" }
605
- ];
606
- const overall = checks.some((check) => check.status === "fail") ? "fail" : checks.some((check) => check.status === "warn") ? "warn" : "pass";
607
- return {
608
- window_start: start,
609
- window_end: end,
610
- sessions: sessionIds.size,
611
- sessions_requiring_repo: scopedSessionIds.size,
612
- sessions_with_repo: attributedSessionIds.size,
613
- repo_attribution_rate: repoAttribution,
614
- selected_injections: selectedPairs.size,
615
- emitted_injections: emittedSelected,
616
- emission_coverage: emissionCoverage,
617
- observed_uses: observedUses,
618
- resolved_outcomes: resolvedOutcomes,
619
- outcome_coverage: outcomeCoverage,
620
- retrieval_misses: retrievalMisses,
621
- retrieval_observations: retrievalObservations,
622
- candidate_backlog: candidateBacklog,
623
- candidate_injectable_total: injectableCandidates.length,
624
- candidate_total: candidates.length,
625
- active_memories: activeMemories,
626
- checks,
627
- overall
1088
+ var DAY_MS = 864e5;
1089
+ var CONFIDENCE_EPSILON = 1e-9;
1090
+ var RESTORE_ACTOR = "auto-pruner";
1091
+ var RESTORE_REASON_PREFIX = "Restored to auto-injection: demoted while the injection loop was inactive";
1092
+ function isRiskyToRestore(memory) {
1093
+ if (isHighRiskRule(memory.text) || isNonUserCaptureContext(memory.text) || hasNonDurableProvenance(memory)) return true;
1094
+ const contexts = memory.evidence.filter((entry) => entry.type === "session_correction" || entry.type === "review_feedback").map((entry) => entry.context?.trim()).filter((context) => Boolean(context));
1095
+ return contexts.length > 0 && contexts.every(isNonUserCaptureContext);
1096
+ }
1097
+ function prunerArchivalAt(db, memory) {
1098
+ const latest = db.select().from(auditTrail).where(eq(auditTrail.memory_id, memory.id)).orderBy(desc(auditTrail.timestamp), sql`rowid DESC`).limit(1).get();
1099
+ if (!latest || latest.action !== "demoted" || latest.actor !== RESTORE_ACTOR || !/^Archived (?:unconfirmed candidate after \d+(?:\.\d+)?d without selection or repetition|from auto-injection: no activity since )/.test(latest.reason ?? "") || !latest.after_snapshot) return null;
1100
+ try {
1101
+ const after = JSON.parse(latest.after_snapshot);
1102
+ if (!after || typeof after !== "object" || Array.isArray(after)) return null;
1103
+ const fields = [
1104
+ "id",
1105
+ "type",
1106
+ "text",
1107
+ "scope",
1108
+ "repo",
1109
+ "path_scope",
1110
+ "status",
1111
+ "confidence",
1112
+ "source",
1113
+ "created_at",
1114
+ "updated_at",
1115
+ "last_validated_at",
1116
+ "last_injected_at",
1117
+ "injection_count",
1118
+ "override_count",
1119
+ "repetition_count",
1120
+ "auto_inject",
1121
+ "evidence",
1122
+ "capture_context",
1123
+ "supersedes"
1124
+ ];
1125
+ if (fields.some(
1126
+ (field) => JSON.stringify(after[field]) !== JSON.stringify(memory[field])
1127
+ ) || (after.note ?? null) !== (memory.note ?? null)) return null;
1128
+ if (latest.before_snapshot) {
1129
+ const before = JSON.parse(latest.before_snapshot);
1130
+ if (!before || before.auto_inject !== true) return null;
1131
+ }
1132
+ return typeof after.updated_at === "string" && Number.isFinite(Date.parse(after.updated_at)) ? after.updated_at : null;
1133
+ } catch {
1134
+ return null;
1135
+ }
1136
+ }
1137
+ function restoreUnmeasuredCandidates(db, options = {}) {
1138
+ const minConfidence = options.minConfidence ?? CONFIDENCE.ACTIVE_MIN;
1139
+ const lookbackDays = options.lookbackDays ?? 30;
1140
+ const dryRun = options.dryRun ?? false;
1141
+ if (!Number.isFinite(minConfidence) || minConfidence < 0 || minConfidence > 1) {
1142
+ throw new RangeError("minConfidence must be a number between 0 and 1");
1143
+ }
1144
+ if (!Number.isFinite(lookbackDays) || lookbackDays <= 0) {
1145
+ throw new RangeError("lookbackDays must be a positive number");
1146
+ }
1147
+ const now = options.now ?? Date.now();
1148
+ const nowIso = new Date(now).toISOString();
1149
+ const sinceIso = new Date(now - lookbackDays * DAY_MS).toISOString();
1150
+ const loopCovered = createLoopCoverageCache(db);
1151
+ const result = {
1152
+ restored: [],
1153
+ skipped_below_gate: 0,
1154
+ skipped_loop_active: 0,
1155
+ skipped_risky: 0,
1156
+ skipped_not_pruner_archived: 0,
1157
+ min_confidence: minConfidence,
1158
+ lookback_days: lookbackDays,
1159
+ dry_run: dryRun
1160
+ };
1161
+ const restore = () => {
1162
+ const selected = loadInjectedMemoryIds(db);
1163
+ const archived = queryMemories(db, {
1164
+ repo: options.repo,
1165
+ status: "candidate",
1166
+ auto_inject: false
1167
+ }).filter((memory) => memory.injection_count === 0 && !selected.has(memory.id));
1168
+ for (const before of archived) {
1169
+ if (before.confidence + CONFIDENCE_EPSILON < minConfidence) {
1170
+ result.skipped_below_gate++;
1171
+ continue;
1172
+ }
1173
+ if (isRiskyToRestore(before)) {
1174
+ result.skipped_risky++;
1175
+ continue;
1176
+ }
1177
+ const archivedAt = prunerArchivalAt(db, before);
1178
+ if (!archivedAt) {
1179
+ result.skipped_not_pruner_archived++;
1180
+ continue;
1181
+ }
1182
+ const archiveWindowStart = new Date(Date.parse(archivedAt) - lookbackDays * DAY_MS).toISOString();
1183
+ const repo = loopRepoForMemory(before);
1184
+ if (loopCovered(repo, archiveWindowStart, archivedAt) || loopCovered(repo, sinceIso, nowIso)) {
1185
+ result.skipped_loop_active++;
1186
+ continue;
1187
+ }
1188
+ result.restored.push(before.id);
1189
+ if (dryRun) continue;
1190
+ db.update(memories).set({ auto_inject: true, updated_at: nowIso }).where(eq(memories.id, before.id)).run();
1191
+ const reason = `${RESTORE_REASON_PREFIX} (no injection coverage in ${lookbackDays}d; archival ${archivedAt})`;
1192
+ recordAuditWithSnapshot(
1193
+ db,
1194
+ before.id,
1195
+ "policy_applied",
1196
+ RESTORE_ACTOR,
1197
+ reason,
1198
+ before,
1199
+ getMemory(db, before.id) ?? null
1200
+ );
1201
+ }
628
1202
  };
1203
+ const transaction = db.$client.transaction(restore);
1204
+ if (dryRun) transaction();
1205
+ else transaction.immediate();
1206
+ return result;
629
1207
  }
630
- function formatReliabilityReport(report) {
631
- const percent = (value) => `${(value * 100).toFixed(1)}%`;
1208
+ function formatRestoreReport(result) {
1209
+ const prefix = result.dry_run ? "[DRY RUN] " : "";
632
1210
  const lines = [
633
- "# Recall Reliability",
634
- "",
635
- `Window: ${report.window_start} to ${report.window_end}`,
636
- `Overall: ${report.overall.toUpperCase()}`,
637
- "",
638
- `Sessions: ${report.sessions} (${report.sessions_requiring_repo} required repo, ${report.sessions_with_repo} attributed, ${percent(report.repo_attribution_rate)})`,
639
- `Injections: ${report.selected_injections} selected, ${report.emitted_injections} emitted (${percent(report.emission_coverage)})`,
640
- `Evidence: ${report.observed_uses} observed uses, ${report.resolved_outcomes} resolved outcomes (${percent(report.outcome_coverage)})`,
641
- `Retrieval: ${report.retrieval_observations} observations, ${report.retrieval_misses} misses`,
642
- `Memory: ${report.active_memories} active, ${report.candidate_injectable_total} injectable candidates total, ${report.candidate_backlog} max in one repo, ${report.candidate_total} total candidates`,
643
- "",
644
- "## Checks"
1211
+ `${prefix}Restore Unmeasured Candidates`,
1212
+ ``,
1213
+ `Gate: confidence >= ${result.min_confidence.toFixed(2)}, loop window ${result.lookback_days}d`,
1214
+ `${result.dry_run ? "Would restore" : "Restored"}: ${result.restored.length}`,
1215
+ `Below gate: ${result.skipped_below_gate}`,
1216
+ `Loop active: ${result.skipped_loop_active}`,
1217
+ `Risky (confirm): ${result.skipped_risky}`,
1218
+ `No pruner proof: ${result.skipped_not_pruner_archived}`
645
1219
  ];
646
- for (const check of report.checks) {
647
- const value = check.name.endsWith("coverage") || check.name === "repo_attribution" ? percent(check.value) : String(check.value);
648
- lines.push(`${check.status.toUpperCase().padEnd(4)} ${check.name}: ${value} (target ${check.target})`);
1220
+ if (result.restored.length > 0) {
1221
+ lines.push("", result.dry_run ? "Would restore:" : "Restored:");
1222
+ for (const id of result.restored.slice(0, 10)) lines.push(` ${id.slice(0, 8)}`);
1223
+ if (result.restored.length > 10) lines.push(` ... and ${result.restored.length - 10} more`);
649
1224
  }
650
1225
  return lines.join("\n");
651
1226
  }
652
- function repoAttributionExpected(repoPath) {
653
- const normalized = repoPath.replace(/\\/g, "/").replace(/\/+$/, "");
654
- if (/\/(?:private\/)?(?:var\/folders\/[^/]+\/[^/]+\/T|tmp)(?:\/|$)/.test(normalized)) return false;
655
- if (/\/Projects$/i.test(normalized)) return false;
656
- return true;
657
- }
658
1227
 
659
1228
  // src/reliability/canary.ts
660
1229
  init_define_RECALL_BUILD_INFO();
661
1230
  import { mkdtempSync, rmSync } from "fs";
662
1231
  import { tmpdir } from "os";
663
- import { join } from "path";
1232
+ import { join as join2 } from "path";
664
1233
  import { randomUUID as randomUUID2 } from "crypto";
665
1234
  async function runReliabilityCanary(options = {}) {
666
1235
  const started = performance.now();
667
- const root = mkdtempSync(join(tmpdir(), "recall-reliability-canary-"));
668
- const db = initStandaloneDb(join(root, "recall.db"));
1236
+ const root = mkdtempSync(join2(tmpdir(), "recall-reliability-canary-"));
1237
+ const db = initStandaloneDb(join2(root, "recall.db"));
669
1238
  const priorDisabled = process.env.RECALL_EMBEDDINGS_DISABLED;
670
1239
  const realEmbeddings = options.real_embeddings === true;
671
1240
  const checks = {};
@@ -790,34 +1359,34 @@ async function runReliabilityProbe(db, options = {}) {
790
1359
  init_define_RECALL_BUILD_INFO();
791
1360
  import { existsSync } from "fs";
792
1361
  import { execFileSync } from "child_process";
793
- import { basename, dirname, join as join2, resolve } from "path";
1362
+ import { basename, dirname as dirname2, join as join3, resolve as resolve2 } from "path";
794
1363
  import { fileURLToPath } from "url";
795
1364
  function resolveRuntimePaths(appPath) {
796
1365
  const override = process.env.RECALL_RUNTIME_DIR;
797
1366
  if (override) {
798
1367
  return {
799
1368
  appPath: override,
800
- runtimeNodePath: join2(override, "bin", "node"),
801
- runtimeCliPath: join2(override, "dist", "cli.js"),
802
- runtimeMcpPath: join2(override, "dist", "mcp.js")
1369
+ runtimeNodePath: join3(override, "bin", "node"),
1370
+ runtimeCliPath: join3(override, "dist", "cli.js"),
1371
+ runtimeMcpPath: join3(override, "dist", "mcp.js")
803
1372
  };
804
1373
  }
805
1374
  if (appPath || process.platform === "darwin" && existsSync("/Applications/Recall.app")) {
806
1375
  const resolvedAppPath = appPath ?? "/Applications/Recall.app";
807
- const runtimeRoot = join2(resolvedAppPath, "Contents", "Resources", "Runtime");
1376
+ const runtimeRoot = join3(resolvedAppPath, "Contents", "Resources", "Runtime");
808
1377
  return {
809
1378
  appPath: resolvedAppPath,
810
- runtimeNodePath: join2(runtimeRoot, "bin", "node"),
811
- runtimeCliPath: join2(runtimeRoot, "dist", "cli.js"),
812
- runtimeMcpPath: join2(runtimeRoot, "dist", "mcp.js")
1379
+ runtimeNodePath: join3(runtimeRoot, "bin", "node"),
1380
+ runtimeCliPath: join3(runtimeRoot, "dist", "cli.js"),
1381
+ runtimeMcpPath: join3(runtimeRoot, "dist", "mcp.js")
813
1382
  };
814
1383
  }
815
- const distDir = dirname(fileURLToPath(import.meta.url));
1384
+ const distDir = dirname2(fileURLToPath(import.meta.url));
816
1385
  return {
817
1386
  appPath: distDir,
818
1387
  runtimeNodePath: process.execPath,
819
- runtimeCliPath: join2(distDir, "cli.js"),
820
- runtimeMcpPath: join2(distDir, "mcp.js")
1388
+ runtimeCliPath: join3(distDir, "cli.js"),
1389
+ runtimeMcpPath: join3(distDir, "mcp.js")
821
1390
  };
822
1391
  }
823
1392
  function runLocalSetup(opts = {}) {
@@ -867,7 +1436,7 @@ function runRecallSetup(opts = {}) {
867
1436
  throw new Error(`Recall MCP entry not found at ${paths.runtimeMcpPath}`);
868
1437
  }
869
1438
  const targetAgents = resolveTargetAgents(opts.agent);
870
- const cwd = resolve(opts.cwd ?? process.cwd());
1439
+ const cwd = resolve2(opts.cwd ?? process.cwd());
871
1440
  const claudeMdEnabled = opts.claudeMd ?? true;
872
1441
  const agents = targetAgents.map(
873
1442
  (agent) => setupAgent(agent, {
@@ -998,9 +1567,9 @@ function configureMcp(agent, options) {
998
1567
  }
999
1568
  function configureHooks(agent, options) {
1000
1569
  const codexTargets = agent === "codex" ? options.scope === "project" ? [{
1001
- home: dirname(options.configPath),
1570
+ home: dirname2(options.configPath),
1002
1571
  configPath: options.configPath,
1003
- hooksPath: join2(dirname(options.configPath), "hooks.json")
1572
+ hooksPath: join3(dirname2(options.configPath), "hooks.json")
1004
1573
  }] : resolveCodexHookTargets() : [];
1005
1574
  if (options.dryRun) {
1006
1575
  const base = options.uninstallHooks ? `would remove hooks from ${options.configPath}` : `would install hooks into ${options.configPath}${options.promptInjection === false ? " (prompt injection opt-out)" : ""}`;
@@ -1049,18 +1618,18 @@ function resolveTargetAgents(target) {
1049
1618
  }
1050
1619
  function detectAgent(agent) {
1051
1620
  if (agent === "codex") {
1052
- return hasCommand("codex") || existsSync(join2(resolveUserHomeDir(), ".codex", "config.toml"));
1621
+ return hasCommand("codex") || existsSync(join3(resolveUserHomeDir(), ".codex", "config.toml"));
1053
1622
  }
1054
1623
  if (agent === "claude-code") {
1055
- return hasCommand("claude") || existsSync(join2(resolveUserHomeDir(), ".claude", "settings.json"));
1624
+ return hasCommand("claude") || existsSync(join3(resolveUserHomeDir(), ".claude", "settings.json"));
1056
1625
  }
1057
1626
  return resolveAdapter(agent).detect() === "installed";
1058
1627
  }
1059
1628
  function resolveHookConfigPath(agent, scope, cwd) {
1060
1629
  if (scope === "project") {
1061
- return agent === "codex" ? join2(cwd, ".codex", "config.toml") : join2(cwd, ".claude", "settings.json");
1630
+ return agent === "codex" ? join3(cwd, ".codex", "config.toml") : join3(cwd, ".claude", "settings.json");
1062
1631
  }
1063
- return agent === "codex" ? join2(resolveUserHomeDir(), ".codex", "config.toml") : join2(resolveUserHomeDir(), ".claude", "settings.json");
1632
+ return agent === "codex" ? join3(resolveUserHomeDir(), ".codex", "config.toml") : join3(resolveUserHomeDir(), ".claude", "settings.json");
1064
1633
  }
1065
1634
  function defaultRunner(command, args, options) {
1066
1635
  execFileSync(command, args, { ...stdioOpts(), ...options?.env ? { env: options.env } : {} });
@@ -1093,13 +1662,13 @@ init_define_RECALL_BUILD_INFO();
1093
1662
  import { execFileSync as execFileSync2 } from "child_process";
1094
1663
  import {
1095
1664
  existsSync as existsSync2,
1096
- readFileSync,
1665
+ readFileSync as readFileSync2,
1097
1666
  readdirSync,
1098
1667
  rmSync as rmSync2,
1099
1668
  rmdirSync
1100
1669
  } from "fs";
1101
1670
  import { homedir } from "os";
1102
- import { dirname as dirname2, join as join3, parse, resolve as resolve2 } from "path";
1671
+ import { dirname as dirname3, join as join4, parse, resolve as resolve3 } from "path";
1103
1672
  init_keychain();
1104
1673
 
1105
1674
  // src/daemon/service.ts
@@ -1148,12 +1717,12 @@ var PROVIDERS = [
1148
1717
  "azure-openai"
1149
1718
  ];
1150
1719
  function resolveRecallDataDir(options = {}) {
1151
- const home = resolve2(options.homeDir ?? homedir());
1152
- return resolve2(options.dataDir ?? process.env.RECALL_DATA_DIR ?? join3(home, ".recall"));
1720
+ const home = resolve3(options.homeDir ?? homedir());
1721
+ return resolve3(options.dataDir ?? process.env.RECALL_DATA_DIR ?? join4(home, ".recall"));
1153
1722
  }
1154
1723
  function purgeLocalData(options = {}) {
1155
1724
  const dryRun = options.dryRun ?? false;
1156
- const home = resolve2(options.homeDir ?? homedir());
1725
+ const home = resolve3(options.homeDir ?? homedir());
1157
1726
  const dataDir = resolveRecallDataDir({ dataDir: options.dataDir, homeDir: home });
1158
1727
  assertSafeDataDir(dataDir, home);
1159
1728
  const repoRoots = options.repoRoots ?? configuredRepoRoots(home);
@@ -1207,7 +1776,7 @@ function purgeLocalData(options = {}) {
1207
1776
  }
1208
1777
  try {
1209
1778
  rmSync2(contextPath, { force: true });
1210
- removeDirectoryIfEmpty(dirname2(contextPath));
1779
+ removeDirectoryIfEmpty(dirname3(contextPath));
1211
1780
  actions.push({
1212
1781
  category: "artifact",
1213
1782
  target: contextPath,
@@ -1255,7 +1824,7 @@ function assertSafeDataDir(dataDir, home) {
1255
1824
  }
1256
1825
  function configuredRepoRoots(home) {
1257
1826
  const configured = process.env.RECALL_REPO_ROOTS?.split(",").map((value) => value.trim()).filter(Boolean);
1258
- return configured?.length ? configured.map((value) => resolve2(value)) : [join3(home, "Projects")];
1827
+ return configured?.length ? configured.map((value) => resolve3(value)) : [join4(home, "Projects")];
1259
1828
  }
1260
1829
  function findGeneratedContextArtifacts(repoRoots) {
1261
1830
  const paths = /* @__PURE__ */ new Set();
@@ -1270,7 +1839,7 @@ function findGeneratedContextArtifacts(repoRoots) {
1270
1839
  function isGeneratedContext(path) {
1271
1840
  if (!existsSync2(path)) return false;
1272
1841
  try {
1273
- return readFileSync(path, "utf8").startsWith(GENERATED_CONTEXT_MARKER);
1842
+ return readFileSync2(path, "utf8").startsWith(GENERATED_CONTEXT_MARKER);
1274
1843
  } catch {
1275
1844
  return false;
1276
1845
  }
@@ -1423,6 +1992,7 @@ function defaultRecallAppPath(platform = process.platform) {
1423
1992
  return platform === "darwin" ? "/Applications/Recall.app" : void 0;
1424
1993
  }
1425
1994
  program.name("recall").description("Cross-tool coding memory and instruction compiler").version(pkg.version);
1995
+ registerHarness2Commands(program);
1426
1996
  program.command("init").description("Initialize Recall database").action(() => {
1427
1997
  initDb();
1428
1998
  console.log("Recall initialized. Database ready.");
@@ -1469,7 +2039,7 @@ program.command("doctor").description("Show local Recall runtime, DB, embedding,
1469
2039
  const finalReport = opts.fix ? getDoctorReport() : report;
1470
2040
  const codexEntry = finalReport.agents.find((agent) => agent.agent === "codex" && agent.detected);
1471
2041
  if (codexEntry) {
1472
- const { inspectCodexTrust } = await import("./codex-trust-H6KNABHV.js");
2042
+ const { inspectCodexTrust } = await import("./codex-trust-CWD4SYOS.js");
1473
2043
  codexEntry.hook_trust = await inspectCodexTrust();
1474
2044
  }
1475
2045
  if (opts.json) {
@@ -1642,9 +2212,9 @@ function safeHookAction(event, action) {
1642
2212
  try {
1643
2213
  const { appendFileSync, mkdirSync, statSync, renameSync, rmSync: rmSync3 } = await import("fs");
1644
2214
  const { homedir: homedir2 } = await import("os");
1645
- const dir = join4(homedir2(), ".recall", "logs");
2215
+ const dir = join5(homedir2(), ".recall", "logs");
1646
2216
  mkdirSync(dir, { recursive: true });
1647
- logPath = join4(dir, "hook-errors.log");
2217
+ logPath = join5(dir, "hook-errors.log");
1648
2218
  try {
1649
2219
  const maxBytes = parseInt(process.env.RECALL_HOOK_LOG_MAX_BYTES ?? String(1024 * 1024), 10);
1650
2220
  if (maxBytes > 0 && statSync(logPath).size >= maxBytes) {
@@ -1801,7 +2371,7 @@ program.command("ump").description("Serve the Universal Memory Protocol (UMP) ov
1801
2371
  });
1802
2372
  program.command("scan").description("Scan a repository and bootstrap memories").argument("[path]", "Repository path", ".").option("-s, --session <id>", "Session ID").action((path, opts) => {
1803
2373
  const db = initDb();
1804
- const repoPath = resolve3(path);
2374
+ const repoPath = resolve4(path);
1805
2375
  const ids = scanAndStore(db, repoPath);
1806
2376
  const artifact = writeRepoContextArtifact(db, {
1807
2377
  repo: inferRepoSlugFromPath(repoPath),
@@ -2048,7 +2618,7 @@ program.command("export").description("Export memories as markdown instruction f
2048
2618
  console.error(`Could not resolve local repo path for ${opts.repo}`);
2049
2619
  process.exit(1);
2050
2620
  }
2051
- content = readFileSync2(artifact.output_path, "utf-8");
2621
+ content = readFileSync3(artifact.output_path, "utf-8");
2052
2622
  if (!opts.output) {
2053
2623
  console.log(content);
2054
2624
  return;
@@ -2067,7 +2637,7 @@ program.command("export").description("Export memories as markdown instruction f
2067
2637
  });
2068
2638
  program.command("publish").description("Write repo-local .recall/context.md for the current repo").argument("[path]", "Repository path", ".").action((path) => {
2069
2639
  const db = initDb();
2070
- const repoPath = resolve3(path);
2640
+ const repoPath = resolve4(path);
2071
2641
  const artifact = writeRepoContextArtifact(db, {
2072
2642
  repo: inferRepoSlugFromPath(repoPath),
2073
2643
  repo_path: repoPath
@@ -2196,7 +2766,7 @@ evalCmd.command("value-retrieval").description("Run retrieval eval cases synthes
2196
2766
  });
2197
2767
  let snapshot = null;
2198
2768
  if (opts.snapshot) {
2199
- const { computeQualityReport, recordQualitySnapshot } = await import("./quality-6BN2ERKC.js");
2769
+ const { computeQualityReport, recordQualitySnapshot } = await import("./quality-PIYKKBIT.js");
2200
2770
  const qualityReport = computeQualityReport(db, { sinceIso: report.since });
2201
2771
  snapshot = recordQualitySnapshot(
2202
2772
  db,
@@ -2481,7 +3051,27 @@ contradictCmd.command("auto-resolve").description("Auto-resolve contradictions (
2481
3051
  const count = autoResolveContradictions(db, opts.repo);
2482
3052
  console.log(`Auto-resolved ${count} contradiction(s).`);
2483
3053
  });
2484
- program.command("prune").description("Auto-prune stale and unhealthy memories").option("-r, --repo <repo>", "Limit pruning to one repo").option("--candidate-days <n>", "Days before archiving an unconfirmed, never-selected candidate", "30").option("--stale-days <n>", "Days before rejecting stale memories", "90").option("--rejected-days <n>", "Days before deleting rejected memories", "30").option("--transient-days <n>", "Days before deleting transient memories", "7").option("--min-health <n>", "Min health score for active memories", "0.2").option("--dry-run", "Preview without making changes").action((opts) => {
3054
+ program.command("prune").description("Auto-prune stale and unhealthy memories").option("-r, --repo <repo>", "Limit pruning to one repo").option("--candidate-days <n>", "Days before archiving an unconfirmed, never-selected candidate", "30").option("--stale-days <n>", "Days before rejecting stale memories", "90").option("--rejected-days <n>", "Days before deleting rejected memories", "30").option("--transient-days <n>", "Days before deleting transient memories", "7").option("--min-health <n>", "Min health score for active memories", "0.2").option("--dry-run", "Preview without making changes").option("--restore-unmeasured", "Restore candidates with audited auto-pruner archival during an inactive injection loop (runs instead of pruning)").option("--min-confidence <n>", "With --restore-unmeasured: lowest confidence to restore (default: 0.60)").option("--lookback-days <n>", "With --restore-unmeasured: injection-coverage window in days", "30").action((opts) => {
3055
+ if (opts.restoreUnmeasured) {
3056
+ const minConfidence = opts.minConfidence === void 0 ? void 0 : Number(opts.minConfidence);
3057
+ const lookbackDays = Number(opts.lookbackDays);
3058
+ if (minConfidence !== void 0 && !(Number.isFinite(minConfidence) && minConfidence >= 0 && minConfidence <= 1)) {
3059
+ console.error("--min-confidence must be a number between 0 and 1.");
3060
+ process.exit(1);
3061
+ }
3062
+ if (!(Number.isFinite(lookbackDays) && lookbackDays > 0)) {
3063
+ console.error("--lookback-days must be a positive number.");
3064
+ process.exit(1);
3065
+ }
3066
+ const restored = restoreUnmeasuredCandidates(initDb(), {
3067
+ repo: opts.repo,
3068
+ minConfidence,
3069
+ lookbackDays,
3070
+ dryRun: opts.dryRun ?? false
3071
+ });
3072
+ console.log(formatRestoreReport(restored));
3073
+ return;
3074
+ }
2485
3075
  const db = initDb();
2486
3076
  const result = pruneMemories(db, {
2487
3077
  repo: opts.repo,
@@ -2614,27 +3204,27 @@ daemonCmd.command("install").description("Install and start the user service").o
2614
3204
  nodePath: opts.nodePath,
2615
3205
  daemonScript: opts.daemonScript
2616
3206
  });
2617
- console.log(getServiceInfo(status.label));
3207
+ console.log(getServiceInfo(opts.label));
2618
3208
  });
2619
3209
  daemonCmd.command("start").description("Start the installed service").option("--label <label>", "Service label", defaultLabel).action((opts) => {
2620
3210
  const status = startService(opts.label);
2621
- console.log(getServiceInfo(status.label));
3211
+ console.log(getServiceInfo(opts.label));
2622
3212
  });
2623
3213
  daemonCmd.command("stop").description("Stop the service").option("--label <label>", "Service label", defaultLabel).action((opts) => {
2624
3214
  const status = stopService(opts.label);
2625
- console.log(getServiceInfo(status.label));
3215
+ console.log(getServiceInfo(opts.label));
2626
3216
  });
2627
3217
  daemonCmd.command("restart").description("Restart the service").option("--label <label>", "Service label", defaultLabel).action((opts) => {
2628
3218
  stopService(opts.label);
2629
3219
  const status = startService(opts.label);
2630
- console.log(getServiceInfo(status.label));
3220
+ console.log(getServiceInfo(opts.label));
2631
3221
  });
2632
3222
  daemonCmd.command("status").description("Show service status").option("--label <label>", "Service label", defaultLabel).action((opts) => {
2633
3223
  console.log(getServiceInfo(opts.label));
2634
3224
  });
2635
3225
  daemonCmd.command("uninstall").description("Remove the service").option("--label <label>", "Service label", defaultLabel).action((opts) => {
2636
3226
  const status = uninstallService(opts.label);
2637
- console.log(getServiceInfo(status.label));
3227
+ console.log(getServiceInfo(opts.label));
2638
3228
  });
2639
3229
  var uiCmd = program.command("ui").description("Control the Recall WebUI dashboard (browser-based view of memories, graph, sessions)");
2640
3230
  uiCmd.command("start", { isDefault: true }).description("Start the WebUI and open it in your default browser").option("--port <port>", "WebUI port", "7891").option("--daemon-port <port>", "Daemon port", "7890").option("--no-open", "Do not open the browser automatically").action(async (opts) => {
@@ -2705,15 +3295,15 @@ uiCmd.command("status").description("Show WebUI status").option("--daemon-port <
2705
3295
  var graphCmd = program.command("graph").description("Inspect and rebuild the knowledge graph (entities + relations)");
2706
3296
  graphCmd.command("stats").description("Show entity/relation counts").action(async () => {
2707
3297
  const db = initDb();
2708
- const { countEntities, countRelations } = await import("./store-QYLHMBPE.js");
3298
+ const { countEntities, countRelations } = await import("./store-DL6YQ6C3.js");
2709
3299
  console.log(`entities: ${countEntities(db)}`);
2710
3300
  console.log(`relations: ${countRelations(db)}`);
2711
3301
  });
2712
3302
  graphCmd.command("backfill").description("Run the heuristic extractor over every active memory (idempotent)").option("--repo <repo>", "Limit to a single repo").option("--limit <n>", "Cap rows processed", "10000").option("--rebuild", "Clear all existing entities/relations first, then re-extract").action(async (opts) => {
2713
3303
  const db = initDb();
2714
- const { ingestMemoryHeuristic } = await import("./ingest-FF67DX3F.js");
3304
+ const { ingestMemoryHeuristic } = await import("./ingest-UU7VULPA.js");
2715
3305
  if (opts.rebuild) {
2716
- const { clearGraph } = await import("./store-QYLHMBPE.js");
3306
+ const { clearGraph } = await import("./store-DL6YQ6C3.js");
2717
3307
  clearGraph(db);
2718
3308
  console.log("Cleared existing graph entities and relations.");
2719
3309
  }
@@ -2735,7 +3325,7 @@ graphCmd.command("backfill").description("Run the heuristic extractor over every
2735
3325
  });
2736
3326
  graphCmd.command("entities").description("List entities").option("--repo <repo>", "Filter by repo").option("--kind <kind>", "Filter by entity kind").option("--search <q>", "Substring filter on name").option("--limit <n>", "Max rows", "50").action(async (opts) => {
2737
3327
  const db = initDb();
2738
- const { listEntities } = await import("./store-QYLHMBPE.js");
3328
+ const { listEntities } = await import("./store-DL6YQ6C3.js");
2739
3329
  const rows = listEntities(db, {
2740
3330
  repo: opts.repo,
2741
3331
  kind: opts.kind,
@@ -2754,8 +3344,8 @@ graphCmd.command("entities").description("List entities").option("--repo <repo>"
2754
3344
  });
2755
3345
  graphCmd.command("query <query...>").description("Run graph-aware retrieval for a query").option("--repo <repo>", "Restrict to repo").option("--hops <n>", "Graph hops", "2").option("--limit <n>", "Max hits", "10").action(async (queryTokens, opts) => {
2756
3346
  const db = initDb();
2757
- const { graphQuery } = await import("./retrieval-QLC3DNMW.js");
2758
- const { loadEmbeddingConfigFromEnv: loadEmbeddingConfigFromEnv2 } = await import("./embeddings-W24SA6R3.js");
3347
+ const { graphQuery } = await import("./retrieval-DDYCXIUG.js");
3348
+ const { loadEmbeddingConfigFromEnv: loadEmbeddingConfigFromEnv2 } = await import("./embeddings-J24U3RAX.js");
2759
3349
  const embeddingConfig = loadEmbeddingConfigFromEnv2();
2760
3350
  const result = await graphQuery(db, queryTokens.join(" "), embeddingConfig, {
2761
3351
  repo: opts.repo,
@@ -2771,7 +3361,7 @@ graphCmd.command("query <query...>").description("Run graph-aware retrieval for
2771
3361
  });
2772
3362
  var maintenanceCmd = program.command("maintenance").description("Inspect and manage the delegated maintenance task queue");
2773
3363
  maintenanceCmd.command("stats").description("Show backlog counts, completion stats, and mean latency").action(async () => {
2774
- const { getTaskStats } = await import("./tasks-7P7XOGSC.js");
3364
+ const { getTaskStats } = await import("./tasks-3VQQG77M.js");
2775
3365
  const db = initDb();
2776
3366
  const stats = getTaskStats(db);
2777
3367
  console.log(`Total tasks: ${stats.total}`);
@@ -2797,7 +3387,7 @@ maintenanceCmd.command("stats").description("Show backlog counts, completion sta
2797
3387
  }
2798
3388
  });
2799
3389
  maintenanceCmd.command("list").description("List tasks (default: pending)").option("-s, --status <status>", "pending|claimed|completed|abandoned", "pending").option("-k, --kind <kind>", "Filter by kind").option("-r, --repo <repo>", "Filter by repo").option("-n, --limit <n>", "Max entries", "20").action(async (opts) => {
2800
- const { listTasks } = await import("./tasks-7P7XOGSC.js");
3390
+ const { listTasks } = await import("./tasks-3VQQG77M.js");
2801
3391
  const db = initDb();
2802
3392
  const tasks = listTasks(db, {
2803
3393
  status: opts.status,
@@ -2819,7 +3409,7 @@ maintenanceCmd.command("list").description("List tasks (default: pending)").opti
2819
3409
  }
2820
3410
  });
2821
3411
  maintenanceCmd.command("drop").description("Delete a task by id (or id prefix)").argument("<task-id>", "Task id or prefix").action(async (taskIdArg) => {
2822
- const { deleteTask, listTasks } = await import("./tasks-7P7XOGSC.js");
3412
+ const { deleteTask, listTasks } = await import("./tasks-3VQQG77M.js");
2823
3413
  const db = initDb();
2824
3414
  const all = listTasks(db, { limit: 1e4 });
2825
3415
  const matches = all.filter((t) => t.id === taskIdArg || t.id.startsWith(taskIdArg));
@@ -2838,7 +3428,7 @@ maintenanceCmd.command("drop").description("Delete a task by id (or id prefix)")
2838
3428
  });
2839
3429
  var credentialsCmd = maintenanceCmd.command("credentials").description("Manage LLM provider API keys in macOS Keychain (env fallback on other platforms)");
2840
3430
  credentialsCmd.command("list", { isDefault: true }).description("Show which providers have credentials available").action(async () => {
2841
- const { listCredentials } = await import("./keychain-LVWMAS7D.js");
3431
+ const { listCredentials } = await import("./keychain-23KFNHQ6.js");
2842
3432
  const creds = listCredentials();
2843
3433
  if (creds.length === 0) {
2844
3434
  console.log("No API keys configured. Set one with:");
@@ -2852,7 +3442,7 @@ credentialsCmd.command("list", { isDefault: true }).description("Show which prov
2852
3442
  }
2853
3443
  });
2854
3444
  credentialsCmd.command("set").description("Store credentials for an LLM provider in the macOS Keychain").argument("<provider>", "openai|anthropic|azure").argument("[key]", "API key (prompts via stdin if omitted; required for openai/anthropic and for azure unless --stdin-json is used)").option("--endpoint <url>", "Azure OpenAI resource endpoint (e.g. https://myresource.openai.azure.com)").option("--deployment <name>", "Azure OpenAI deployment name").option("--api-version <version>", "Azure OpenAI api-version (e.g. 2024-10-21)").option("--stdin-json", "Read the azure config (endpoint/deployment/api_version/key) as a JSON object from stdin").action(async (providerArg, keyArg, opts) => {
2855
- const { setApiKey, setAzureConfig } = await import("./keychain-LVWMAS7D.js");
3445
+ const { setApiKey, setAzureConfig } = await import("./keychain-23KFNHQ6.js");
2856
3446
  const provider = providerArg === "azure" ? "azure-openai" : providerArg;
2857
3447
  if (provider === "openai" || provider === "anthropic") {
2858
3448
  const key = keyArg ?? await readStdinKey();
@@ -2914,7 +3504,7 @@ credentialsCmd.command("set").description("Store credentials for an LLM provider
2914
3504
  process.exit(1);
2915
3505
  });
2916
3506
  credentialsCmd.command("clear").description("Remove provider credentials from the macOS Keychain").argument("<provider>", "openai|anthropic|azure").action(async (providerArg) => {
2917
- const { deleteApiKey: deleteApiKey2 } = await import("./keychain-LVWMAS7D.js");
3507
+ const { deleteApiKey: deleteApiKey2 } = await import("./keychain-23KFNHQ6.js");
2918
3508
  const provider = providerArg === "azure" ? "azure-openai" : providerArg;
2919
3509
  if (provider !== "openai" && provider !== "anthropic" && provider !== "azure-openai") {
2920
3510
  console.error(`Provider must be "openai", "anthropic", or "azure", got "${providerArg}".`);
@@ -2925,8 +3515,8 @@ credentialsCmd.command("clear").description("Remove provider credentials from th
2925
3515
  else console.log(`No ${provider} credentials found in Keychain.`);
2926
3516
  });
2927
3517
  maintenanceCmd.command("dispatch").description("Run the daemon-owned dispatcher once against pending maintenance tasks (requires a configured LLM provider)").option("--provider <provider>", "openai|anthropic|azure-openai (defaults to whichever is configured)").option("--model <model>", "Model override").option("--kind <kind>", "Restrict to a single task kind (repeatable)", (value, acc = []) => [...acc, value], []).option("--repo <repo>", "Restrict to a single repo").option("--max <n>", "Max tasks to run this round", "5").option("--dry-run", "Show which tasks would be dispatched; do not call the LLM").option("--preview", "Show the actual prompts that would be sent (no provider needed; no LLM call)").option("--json", "Emit the raw JSON report").action(async (opts) => {
2928
- const { dispatchPendingTasks, formatDispatchReport, buildPrompt } = await import("./dispatcher-W3PTGEKN.js");
2929
- const { listTasks } = await import("./tasks-7P7XOGSC.js");
3518
+ const { dispatchPendingTasks, formatDispatchReport, buildPrompt } = await import("./dispatcher-L77LKD7R.js");
3519
+ const { listTasks } = await import("./tasks-3VQQG77M.js");
2930
3520
  const db = initDb();
2931
3521
  if (opts.preview) {
2932
3522
  const pending = listTasks(db, {
@@ -2983,12 +3573,12 @@ ${p.prompt.max_output_tokens}
2983
3573
  console.log(formatDispatchReport(report));
2984
3574
  });
2985
3575
  maintenanceCmd.command("quarantine-generated").description("Preview memories supported only by generated messages; preserve them outside injection").option("--apply", "Quarantine matching memories with reversible audit snapshots").action(async (opts) => {
2986
- const { quarantineGeneratedMemories } = await import("./provenance-KSBMVJO5.js");
3576
+ const { quarantineGeneratedMemories } = await import("./provenance-U2VAENS6.js");
2987
3577
  const ids = quarantineGeneratedMemories(initDb(), Boolean(opts.apply));
2988
3578
  console.log(JSON.stringify({ applied: Boolean(opts.apply), count: ids.length, memory_ids: ids }, null, 2));
2989
3579
  });
2990
3580
  maintenanceCmd.command("cleanup").description("Run deterministic, LLM-free cleanup for duplicate, low-quality, stale, and mis-scoped memories").option("--apply", "Persist changes (default is dry-run)").option("--only <action>", "Restrict to one action: dedupe_exact_merge|reject_fragment_candidate|promote_repeat_correction|suppress_unproductive_command|globalize_cross_repo|reject_test_fixture_repo|reject_invalid_scope|reject_generic_scanned_tooling").option("--revert <run-id>", "Revert a previous cleanup run (id or 8-char prefix)").option("--list", "List recent cleanup runs").option("--json", "Emit the raw JSON report").action(async (opts) => {
2991
- const { runDeterministicCleanup, formatCleanupReport, revertCleanupRun, listCleanupRuns } = await import("./cleanup-EDWLCJPH.js");
3581
+ const { runDeterministicCleanup, formatCleanupReport, revertCleanupRun, listCleanupRuns } = await import("./cleanup-FGPVQRYE.js");
2992
3582
  const db = initDb();
2993
3583
  if (opts.list) {
2994
3584
  const runs = listCleanupRuns(db);
@@ -3042,7 +3632,7 @@ maintenanceCmd.command("quality").description("Show injection outcome distributi
3042
3632
  recordQualitySnapshot,
3043
3633
  listQualitySnapshots,
3044
3634
  diffQualitySnapshots
3045
- } = await import("./quality-6BN2ERKC.js");
3635
+ } = await import("./quality-PIYKKBIT.js");
3046
3636
  const db = initDb();
3047
3637
  if (opts.history) {
3048
3638
  const snaps = listQualitySnapshots(db);
@@ -3103,7 +3693,7 @@ maintenanceCmd.command("value-backfill").description("Backfill memory value even
3103
3693
  const {
3104
3694
  backfillMemoryValueEvents,
3105
3695
  formatMemoryValueBackfillReport
3106
- } = await import("./memory-value-GMYJ5NGO.js");
3696
+ } = await import("./memory-value-MWWV4P4X.js");
3107
3697
  const db = initDb();
3108
3698
  const report = backfillMemoryValueEvents(db, {
3109
3699
  sinceIso: opts.since,
@@ -3116,7 +3706,7 @@ maintenanceCmd.command("value-backfill").description("Backfill memory value even
3116
3706
  console.log(formatMemoryValueBackfillReport(report));
3117
3707
  });
3118
3708
  maintenanceCmd.command("usage").description("Summarize LLM API usage (tokens, cost) across recent maintenance runs").option("--since <iso>", "Window start (default: last 30 days)").option("--limit <n>", "Recent-call rows to show", "10").option("--json", "Emit raw JSON summary").action(async (opts) => {
3119
- const { summarizeUsage, formatUsageReport } = await import("./usage-KVVZQTZA.js");
3709
+ const { summarizeUsage, formatUsageReport } = await import("./usage-UB4GLDGI.js");
3120
3710
  const db = initDb();
3121
3711
  const summary = summarizeUsage(db, {
3122
3712
  sinceIso: opts.since,