@remnic/core 10.0.149 → 10.0.151
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/access-admin-ops-surface.js +56 -55
- package/dist/access-cli.js +56 -55
- package/dist/access-cli.js.map +1 -1
- package/dist/access-extraction-force-flush-preempt.js +56 -55
- package/dist/access-extraction-force-flush.js +56 -55
- package/dist/access-http-briefing.js +56 -55
- package/dist/access-http-query.js +56 -55
- package/dist/access-http.js +56 -55
- package/dist/access-identity-continuity-surface.js +56 -55
- package/dist/access-lcm-surface.js +56 -55
- package/dist/access-mcp.js +56 -55
- package/dist/access-observe-write-surface.js +56 -55
- package/dist/access-operations-batch.js +56 -55
- package/dist/access-operations.js +56 -55
- package/dist/access-recall-concurrency.js +56 -55
- package/dist/access-recall-response.js +56 -55
- package/dist/access-recall-surface.js +56 -55
- package/dist/access-service.js +56 -55
- package/dist/active-recall.js +9 -9
- package/dist/adapters/index.js +4 -4
- package/dist/adapters/registry.js +2 -2
- package/dist/briefing.js +10 -10
- package/dist/causal-consolidation.js +11 -11
- package/dist/{chunk-XCJDDXJX.js → chunk-272GJCTZ.js} +2 -2
- package/dist/{chunk-E6VI7POW.js → chunk-2ZYU76CG.js} +66 -66
- package/dist/{chunk-EIEANUBO.js → chunk-3YZYD5XJ.js} +7 -7
- package/dist/{chunk-66DUCUOC.js → chunk-4LF5E2LM.js} +4 -4
- package/dist/{chunk-5UYP5IQB.js → chunk-5N767BMB.js} +2 -2
- package/dist/{chunk-EYES6ALH.js → chunk-5Y3UVK6S.js} +81 -40
- package/dist/chunk-5Y3UVK6S.js.map +1 -0
- package/dist/{chunk-DOFLNJZD.js → chunk-6ENFCUYH.js} +3 -3
- package/dist/{chunk-RSPPAPFI.js → chunk-6M3VJJON.js} +2 -2
- package/dist/{chunk-ORPYIVT3.js → chunk-ALNINIUB.js} +2 -2
- package/dist/{chunk-RQ6HMDA5.js → chunk-AMPTUYKS.js} +2 -2
- package/dist/{chunk-UMC6F3Y4.js → chunk-CAFF45W4.js} +3 -3
- package/dist/{chunk-AHNGWFNG.js → chunk-DPF7TX3D.js} +2 -2
- package/dist/{chunk-TVRUUT7U.js → chunk-EK3GC76D.js} +2 -2
- package/dist/{chunk-YCASWFI6.js → chunk-EUIWWY2F.js} +3 -3
- package/dist/{chunk-HUDPXTXW.js → chunk-GXL52YZA.js} +23 -14
- package/dist/chunk-GXL52YZA.js.map +1 -0
- package/dist/{chunk-7OWV3GVD.js → chunk-HAEMXLHX.js} +2 -2
- package/dist/{chunk-JPVUBL4L.js → chunk-HOENUZJ7.js} +2 -2
- package/dist/{chunk-Z3GZRG5Z.js → chunk-J2NQZJRG.js} +2 -2
- package/dist/chunk-JA2GJCOS.js +16 -0
- package/dist/chunk-JA2GJCOS.js.map +1 -0
- package/dist/{chunk-NQJAF2Q4.js → chunk-KZBUOWKB.js} +2 -2
- package/dist/{chunk-SLZJ7HQX.js → chunk-M7BJEWPQ.js} +2 -2
- package/dist/{chunk-3DJ6R4CC.js → chunk-MX5VGD6C.js} +4 -4
- package/dist/{chunk-AWZ5CWSR.js → chunk-MXMFRU45.js} +7 -7
- package/dist/{chunk-5ZSN2OFB.js → chunk-NQ2WFFPQ.js} +6 -6
- package/dist/{chunk-MBQVWTCS.js → chunk-O2677F2E.js} +2 -2
- package/dist/{chunk-ZG4GNPRE.js → chunk-PBE7NFB5.js} +5 -5
- package/dist/{chunk-DLR3SBOM.js → chunk-RJ5L6LRD.js} +4 -4
- package/dist/{chunk-HADCITEA.js → chunk-SENCYTQ2.js} +10 -10
- package/dist/{chunk-7QKZOZF4.js → chunk-T266H3RJ.js} +2 -2
- package/dist/{chunk-QGV6JVQ7.js → chunk-T2IKH7XD.js} +2 -2
- package/dist/{chunk-TQU2RB4B.js → chunk-UUY7OEO7.js} +2 -2
- package/dist/{chunk-CA56BOUE.js → chunk-VI5ECVDF.js} +3 -3
- package/dist/{chunk-B5MB2G3H.js → chunk-VZCX3DOD.js} +2 -2
- package/dist/{chunk-GCHM5BYL.js → chunk-WWQMZBDI.js} +4 -4
- package/dist/{chunk-4JKIOAOF.js → chunk-XSG2S43P.js} +3 -3
- package/dist/{chunk-5BKH4XG5.js → chunk-XTJUE2ON.js} +2 -2
- package/dist/{chunk-6S37C5UK.js → chunk-Z5QZHDG2.js} +2 -2
- package/dist/{chunk-K6RKNQRD.js → chunk-ZFGXIEQU.js} +2 -2
- package/dist/cli.js +56 -55
- package/dist/coding/export-okf-codegraph.js +9 -9
- package/dist/compounding/engine.js +11 -11
- package/dist/config.js +9 -9
- package/dist/connectors/codex-materialize-runner.js +10 -10
- package/dist/connectors/index.js +10 -10
- package/dist/convergence-refresh.js +12 -12
- package/dist/corpus-watermark.js +12 -12
- package/dist/entity-retrieval.js +10 -10
- package/dist/explicit-capture.js +56 -55
- package/dist/extraction.js +10 -10
- package/dist/harmonic-retrieval.d.ts +3 -0
- package/dist/harmonic-retrieval.d.ts.map +1 -1
- package/dist/harmonic-retrieval.js +14 -11
- package/dist/harmonic-source-lookup.d.ts.map +1 -1
- package/dist/harmonic-source-lookup.js +2 -1
- package/dist/index.js +94 -93
- package/dist/lcm/engine.js +2 -2
- package/dist/lcm/index.js +5 -5
- package/dist/location/index.js +11 -11
- package/dist/maintenance/memory-governance.js +10 -10
- package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +10 -10
- package/dist/maintenance/rebuild-memory-projection-runner.js +12 -12
- package/dist/maintenance/rebuild-memory-projection.js +11 -11
- package/dist/map-in-batches.d.ts +10 -0
- package/dist/map-in-batches.d.ts.map +1 -0
- package/dist/map-in-batches.js +10 -0
- package/dist/map-in-batches.js.map +1 -0
- package/dist/namespaces/migrate.js +11 -11
- package/dist/namespaces/search.js +7 -7
- package/dist/namespaces/storage.js +10 -10
- package/dist/operator-doctor-corpus.js +13 -13
- package/dist/operator-toolkit.js +16 -16
- package/dist/orchestration/backlog-scheduler.js +57 -56
- package/dist/orchestration/backlog-scheduler.js.map +1 -1
- package/dist/orchestration/buffer-drain-runner.js +57 -56
- package/dist/orchestration/maintenance.js +18 -18
- package/dist/orchestrator.js +56 -55
- package/dist/recall-navigation.js +56 -55
- package/dist/resume-bundles.js +9 -9
- package/dist/search/factory.js +6 -6
- package/dist/search/index.js +11 -11
- package/dist/search/lancedb-backend.js +2 -2
- package/dist/search/meilisearch-backend.js +2 -2
- package/dist/search/orama-backend.js +2 -2
- package/dist/semantic-consolidation.js +11 -11
- package/dist/semantic-rule-promotion.js +10 -10
- package/dist/semantic-rule-verifier.js +10 -10
- package/dist/source-agent-qualifier.js +10 -10
- package/dist/standup/build.js +10 -10
- package/dist/storage.js +9 -9
- package/dist/transfer/export-okf.js +10 -10
- package/dist/verified-recall.js +10 -10
- package/dist/who-knows-cli.js +11 -11
- package/dist/who-knows.js +10 -10
- package/package.json +2 -2
- package/src/harmonic-retrieval-index.test.ts +238 -1
- package/src/harmonic-retrieval.ts +114 -41
- package/src/harmonic-source-lookup.ts +21 -15
- package/src/map-in-batches.ts +17 -0
- package/dist/chunk-EYES6ALH.js.map +0 -1
- package/dist/chunk-HUDPXTXW.js.map +0 -1
- /package/dist/{chunk-XCJDDXJX.js.map → chunk-272GJCTZ.js.map} +0 -0
- /package/dist/{chunk-E6VI7POW.js.map → chunk-2ZYU76CG.js.map} +0 -0
- /package/dist/{chunk-EIEANUBO.js.map → chunk-3YZYD5XJ.js.map} +0 -0
- /package/dist/{chunk-66DUCUOC.js.map → chunk-4LF5E2LM.js.map} +0 -0
- /package/dist/{chunk-5UYP5IQB.js.map → chunk-5N767BMB.js.map} +0 -0
- /package/dist/{chunk-DOFLNJZD.js.map → chunk-6ENFCUYH.js.map} +0 -0
- /package/dist/{chunk-RSPPAPFI.js.map → chunk-6M3VJJON.js.map} +0 -0
- /package/dist/{chunk-ORPYIVT3.js.map → chunk-ALNINIUB.js.map} +0 -0
- /package/dist/{chunk-RQ6HMDA5.js.map → chunk-AMPTUYKS.js.map} +0 -0
- /package/dist/{chunk-UMC6F3Y4.js.map → chunk-CAFF45W4.js.map} +0 -0
- /package/dist/{chunk-AHNGWFNG.js.map → chunk-DPF7TX3D.js.map} +0 -0
- /package/dist/{chunk-TVRUUT7U.js.map → chunk-EK3GC76D.js.map} +0 -0
- /package/dist/{chunk-YCASWFI6.js.map → chunk-EUIWWY2F.js.map} +0 -0
- /package/dist/{chunk-7OWV3GVD.js.map → chunk-HAEMXLHX.js.map} +0 -0
- /package/dist/{chunk-JPVUBL4L.js.map → chunk-HOENUZJ7.js.map} +0 -0
- /package/dist/{chunk-Z3GZRG5Z.js.map → chunk-J2NQZJRG.js.map} +0 -0
- /package/dist/{chunk-NQJAF2Q4.js.map → chunk-KZBUOWKB.js.map} +0 -0
- /package/dist/{chunk-SLZJ7HQX.js.map → chunk-M7BJEWPQ.js.map} +0 -0
- /package/dist/{chunk-3DJ6R4CC.js.map → chunk-MX5VGD6C.js.map} +0 -0
- /package/dist/{chunk-AWZ5CWSR.js.map → chunk-MXMFRU45.js.map} +0 -0
- /package/dist/{chunk-5ZSN2OFB.js.map → chunk-NQ2WFFPQ.js.map} +0 -0
- /package/dist/{chunk-MBQVWTCS.js.map → chunk-O2677F2E.js.map} +0 -0
- /package/dist/{chunk-ZG4GNPRE.js.map → chunk-PBE7NFB5.js.map} +0 -0
- /package/dist/{chunk-DLR3SBOM.js.map → chunk-RJ5L6LRD.js.map} +0 -0
- /package/dist/{chunk-HADCITEA.js.map → chunk-SENCYTQ2.js.map} +0 -0
- /package/dist/{chunk-7QKZOZF4.js.map → chunk-T266H3RJ.js.map} +0 -0
- /package/dist/{chunk-QGV6JVQ7.js.map → chunk-T2IKH7XD.js.map} +0 -0
- /package/dist/{chunk-TQU2RB4B.js.map → chunk-UUY7OEO7.js.map} +0 -0
- /package/dist/{chunk-CA56BOUE.js.map → chunk-VI5ECVDF.js.map} +0 -0
- /package/dist/{chunk-B5MB2G3H.js.map → chunk-VZCX3DOD.js.map} +0 -0
- /package/dist/{chunk-GCHM5BYL.js.map → chunk-WWQMZBDI.js.map} +0 -0
- /package/dist/{chunk-4JKIOAOF.js.map → chunk-XSG2S43P.js.map} +0 -0
- /package/dist/{chunk-5BKH4XG5.js.map → chunk-XTJUE2ON.js.map} +0 -0
- /package/dist/{chunk-6S37C5UK.js.map → chunk-Z5QZHDG2.js.map} +0 -0
- /package/dist/{chunk-K6RKNQRD.js.map → chunk-ZFGXIEQU.js.map} +0 -0
|
@@ -1,22 +1,25 @@
|
|
|
1
1
|
import {
|
|
2
2
|
readHarmonicSourceMemory,
|
|
3
3
|
readUnresolvedHarmonicSources
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-GXL52YZA.js";
|
|
5
5
|
import {
|
|
6
6
|
readProjectedMemoryStates
|
|
7
7
|
} from "./chunk-AZEZSQ5R.js";
|
|
8
|
+
import {
|
|
9
|
+
mapInBatches
|
|
10
|
+
} from "./chunk-JA2GJCOS.js";
|
|
8
11
|
import {
|
|
9
12
|
resolveCueAnchorStoreDir,
|
|
10
13
|
validateCueAnchor
|
|
11
14
|
} from "./chunk-FYJYQ65N.js";
|
|
12
15
|
import {
|
|
13
16
|
StorageManager
|
|
14
|
-
} from "./chunk-
|
|
17
|
+
} from "./chunk-NQ2WFFPQ.js";
|
|
15
18
|
import {
|
|
16
19
|
isValidityExpiredNow
|
|
17
20
|
} from "./chunk-6CIAGZ6X.js";
|
|
18
21
|
import {
|
|
19
|
-
|
|
22
|
+
normalizeRecallTokenSet,
|
|
20
23
|
normalizeRecallTokens
|
|
21
24
|
} from "./chunk-YCVB7X56.js";
|
|
22
25
|
import {
|
|
@@ -94,7 +97,7 @@ async function readIndexedSourceMemories(options) {
|
|
|
94
97
|
const days = utcDaysSince(rebuiltMs, options.nowMs);
|
|
95
98
|
const sourceMemories = /* @__PURE__ */ new Map();
|
|
96
99
|
const pending = [];
|
|
97
|
-
|
|
100
|
+
const resolved = await mapInBatches(options.sourceMemoryIds, async (id) => {
|
|
98
101
|
const state = batch.states.get(id);
|
|
99
102
|
let safeId = true;
|
|
100
103
|
try {
|
|
@@ -103,15 +106,16 @@ async function readIndexedSourceMemories(options) {
|
|
|
103
106
|
safeId = false;
|
|
104
107
|
}
|
|
105
108
|
const candidates = state ? [state.path, path.join(options.memoryDir, "cold", state.pathRel)] : safeId ? unprojectedCandidatePaths(options.memoryDir, id, days) : [];
|
|
106
|
-
let found = false;
|
|
107
109
|
for (const candidate of candidates) {
|
|
108
110
|
const memory = await readHarmonicSourceMemory(storage, rootReal, candidate, options.abortSignal);
|
|
109
111
|
if (memory?.frontmatter.id !== id) continue;
|
|
110
|
-
|
|
111
|
-
found = true;
|
|
112
|
-
break;
|
|
112
|
+
return { id, memory };
|
|
113
113
|
}
|
|
114
|
-
|
|
114
|
+
return { id, memory: void 0 };
|
|
115
|
+
});
|
|
116
|
+
for (const { id, memory } of resolved) {
|
|
117
|
+
if (memory) sourceMemories.set(id, memory);
|
|
118
|
+
else pending.push(id);
|
|
115
119
|
}
|
|
116
120
|
if (pending.length === 0) return sourceMemories;
|
|
117
121
|
const unresolved = await readUnresolvedHarmonicSources({
|
|
@@ -232,53 +236,88 @@ function anchorMatchesProjectedNode(anchor, nodeRef, node, allowLegacyAttributio
|
|
|
232
236
|
const anchorSourceMemoryIds = anchor.sourceMemoryIdsByNodeRef[nodeRef] ?? [];
|
|
233
237
|
return anchorSourceMemoryIds.some((sourceMemoryId) => activeSourceMemoryIds.includes(sourceMemoryId));
|
|
234
238
|
}
|
|
235
|
-
function
|
|
239
|
+
function tokenOverlap(queryTokens, fieldTokens) {
|
|
240
|
+
let matches = 0;
|
|
241
|
+
for (const token of queryTokens) {
|
|
242
|
+
if (fieldTokens.has(token)) matches += 1;
|
|
243
|
+
}
|
|
244
|
+
return matches;
|
|
245
|
+
}
|
|
246
|
+
var harmonicSearchIndexStats = { builds: 0 };
|
|
247
|
+
var harmonicSearchIndexes = /* @__PURE__ */ new WeakMap();
|
|
248
|
+
function getHarmonicSearchIndex(graph) {
|
|
249
|
+
const cached = harmonicSearchIndexes.get(graph);
|
|
250
|
+
if (cached) return cached;
|
|
251
|
+
harmonicSearchIndexStats.builds += 1;
|
|
252
|
+
const nodesById = new Map(graph.nodes.map((node) => [node.nodeId, node]));
|
|
253
|
+
const nodeTokens = graph.nodes.map((node) => ({
|
|
254
|
+
title: normalizeRecallTokenSet(node.title ?? ""),
|
|
255
|
+
summary: normalizeRecallTokenSet(node.summary ?? ""),
|
|
256
|
+
tags: normalizeRecallTokenSet(node.tags?.join(" ") ?? ""),
|
|
257
|
+
entities: normalizeRecallTokenSet(node.entityRefs?.join(" ") ?? ""),
|
|
258
|
+
kind: normalizeRecallTokenSet(`${node.kind} ${node.abstractionLevel}`)
|
|
259
|
+
}));
|
|
260
|
+
const anchorTokens = graph.anchors.map((anchor) => {
|
|
261
|
+
const eligibleNodeTags = new Set(anchor.nodeRefs.flatMap((nodeRef) => nodesById.get(nodeRef)?.tags ?? []));
|
|
262
|
+
const eligibleAnchorTags = anchor.tags?.filter((tag) => eligibleNodeTags.has(tag)) ?? [];
|
|
263
|
+
return {
|
|
264
|
+
value: normalizeRecallTokenSet(anchor.anchorValue ?? ""),
|
|
265
|
+
normalized: normalizeRecallTokenSet(anchor.normalizedCue ?? ""),
|
|
266
|
+
type: normalizeRecallTokenSet(anchor.anchorType),
|
|
267
|
+
eligibleTags: normalizeRecallTokenSet(eligibleAnchorTags.join(" "))
|
|
268
|
+
};
|
|
269
|
+
});
|
|
270
|
+
const index = { nodesById, nodeTokens, anchorTokens };
|
|
271
|
+
harmonicSearchIndexes.set(graph, index);
|
|
272
|
+
return index;
|
|
273
|
+
}
|
|
274
|
+
function scoreNode(tokens, queryTokens) {
|
|
236
275
|
const matchedFields = [];
|
|
237
276
|
let score = 0;
|
|
238
|
-
const titleMatches =
|
|
277
|
+
const titleMatches = tokenOverlap(queryTokens, tokens.title);
|
|
239
278
|
if (titleMatches > 0) {
|
|
240
279
|
score += titleMatches * 3;
|
|
241
280
|
matchedFields.push("title");
|
|
242
281
|
}
|
|
243
|
-
const summaryMatches =
|
|
282
|
+
const summaryMatches = tokenOverlap(queryTokens, tokens.summary);
|
|
244
283
|
if (summaryMatches > 0) {
|
|
245
284
|
score += summaryMatches * 3;
|
|
246
285
|
matchedFields.push("summary");
|
|
247
286
|
}
|
|
248
|
-
const tagMatches =
|
|
287
|
+
const tagMatches = tokenOverlap(queryTokens, tokens.tags);
|
|
249
288
|
if (tagMatches > 0) {
|
|
250
289
|
score += tagMatches * 2;
|
|
251
290
|
matchedFields.push("tags");
|
|
252
291
|
}
|
|
253
|
-
const entityMatches =
|
|
292
|
+
const entityMatches = tokenOverlap(queryTokens, tokens.entities);
|
|
254
293
|
if (entityMatches > 0) {
|
|
255
294
|
score += entityMatches * 2;
|
|
256
295
|
matchedFields.push("entityRefs");
|
|
257
296
|
}
|
|
258
|
-
const kindMatches =
|
|
297
|
+
const kindMatches = tokenOverlap(queryTokens, tokens.kind);
|
|
259
298
|
if (kindMatches > 0) {
|
|
260
299
|
score += kindMatches;
|
|
261
300
|
matchedFields.push("kind");
|
|
262
301
|
}
|
|
263
302
|
return { score, matchedFields };
|
|
264
303
|
}
|
|
265
|
-
function scoreAnchor(
|
|
304
|
+
function scoreAnchor(tokens, queryTokens) {
|
|
266
305
|
const matchedFields = [];
|
|
267
306
|
let score = 0;
|
|
268
|
-
const valueMatches =
|
|
269
|
-
const normalizedMatches =
|
|
307
|
+
const valueMatches = tokenOverlap(queryTokens, tokens.value);
|
|
308
|
+
const normalizedMatches = tokenOverlap(queryTokens, tokens.normalized);
|
|
270
309
|
const cueMatches = Math.max(valueMatches, normalizedMatches);
|
|
271
310
|
if (cueMatches > 0) {
|
|
272
311
|
score += cueMatches * 4;
|
|
273
312
|
if (valueMatches > 0) matchedFields.push("anchorValue");
|
|
274
313
|
if (normalizedMatches > 0) matchedFields.push("anchor");
|
|
275
314
|
}
|
|
276
|
-
const typeMatches =
|
|
315
|
+
const typeMatches = tokenOverlap(queryTokens, tokens.type);
|
|
277
316
|
if (typeMatches > 0) {
|
|
278
317
|
score += typeMatches;
|
|
279
318
|
matchedFields.push("anchorType");
|
|
280
319
|
}
|
|
281
|
-
const tagMatches =
|
|
320
|
+
const tagMatches = tokenOverlap(queryTokens, tokens.eligibleTags);
|
|
282
321
|
if (tagMatches > 0) {
|
|
283
322
|
score += tagMatches * 2;
|
|
284
323
|
matchedFields.push("anchorTags");
|
|
@@ -288,27 +327,27 @@ function scoreAnchor(anchor, queryTokens, eligibleNodeTags) {
|
|
|
288
327
|
async function readAbstractionNodes(options) {
|
|
289
328
|
const rootDir = resolveAbstractionNodeStoreDir(options.memoryDir, options.abstractionNodeStoreDir);
|
|
290
329
|
const files = await listJsonFilesStrict(path.join(rootDir, "nodes"), { allowMissingDirectory: true });
|
|
291
|
-
const
|
|
292
|
-
for (const filePath of files) {
|
|
330
|
+
const parsed = await mapInBatches(files, async (filePath) => {
|
|
293
331
|
try {
|
|
294
|
-
|
|
332
|
+
return validateAbstractionNode(await readJsonFile(filePath));
|
|
295
333
|
} catch {
|
|
334
|
+
return null;
|
|
296
335
|
}
|
|
297
|
-
}
|
|
298
|
-
return
|
|
336
|
+
});
|
|
337
|
+
return parsed.filter((node) => node !== null);
|
|
299
338
|
}
|
|
300
339
|
async function readCueAnchors(options) {
|
|
301
340
|
const abstractionRoot = resolveAbstractionNodeStoreDir(options.memoryDir, options.abstractionNodeStoreDir);
|
|
302
341
|
const rootDir = resolveCueAnchorStoreDir(abstractionRoot);
|
|
303
342
|
const files = await listJsonFilesStrict(rootDir, { allowMissingDirectory: true });
|
|
304
|
-
const
|
|
305
|
-
for (const filePath of files) {
|
|
343
|
+
const parsed = await mapInBatches(files, async (filePath) => {
|
|
306
344
|
try {
|
|
307
|
-
|
|
345
|
+
return validateCueAnchor(await readJsonFile(filePath));
|
|
308
346
|
} catch {
|
|
347
|
+
return null;
|
|
309
348
|
}
|
|
310
|
-
}
|
|
311
|
-
return
|
|
349
|
+
});
|
|
350
|
+
return parsed.filter((anchor) => anchor !== null);
|
|
312
351
|
}
|
|
313
352
|
function earliestInvalidAtMs(sourceMemories, memoryDir, nowMs) {
|
|
314
353
|
let earliest = Number.POSITIVE_INFINITY;
|
|
@@ -505,15 +544,18 @@ async function searchHarmonicRetrieval(options) {
|
|
|
505
544
|
throwIfAborted(options.abortSignal, "harmonic retrieval aborted");
|
|
506
545
|
const queryTokens = new Set(normalizeRecallTokens(options.query, ["what", "which"]));
|
|
507
546
|
if (queryTokens.size === 0 || options.maxResults <= 0) return [];
|
|
508
|
-
const
|
|
547
|
+
const graph = await readProjectedHarmonicGraph({
|
|
509
548
|
...options,
|
|
510
549
|
useCache: options.useGraphCache === true,
|
|
511
550
|
waitBudgetMs: options.waitBudgetMs === void 0 ? HARMONIC_GRAPH_WAIT_BUDGET_MS : options.waitBudgetMs
|
|
512
551
|
});
|
|
552
|
+
const { nodes: eligibleNodes, anchors } = graph;
|
|
553
|
+
const searchIndex = getHarmonicSearchIndex(graph);
|
|
513
554
|
const candidates = /* @__PURE__ */ new Map();
|
|
514
|
-
for (const node of eligibleNodes) {
|
|
555
|
+
for (const [nodeIndexPos, node] of eligibleNodes.entries()) {
|
|
515
556
|
throwIfAborted(options.abortSignal, "harmonic retrieval aborted");
|
|
516
|
-
const
|
|
557
|
+
const tokens = searchIndex.nodeTokens[nodeIndexPos];
|
|
558
|
+
const { score, matchedFields } = scoreNode(tokens, queryTokens);
|
|
517
559
|
if (score <= 0) continue;
|
|
518
560
|
candidates.set(node.nodeId, {
|
|
519
561
|
node,
|
|
@@ -525,16 +567,14 @@ async function searchHarmonicRetrieval(options) {
|
|
|
525
567
|
}
|
|
526
568
|
if (options.anchorsEnabled) {
|
|
527
569
|
throwIfAborted(options.abortSignal, "harmonic retrieval aborted");
|
|
528
|
-
const
|
|
529
|
-
for (const anchor of anchors) {
|
|
570
|
+
for (const [anchorIndex, anchor] of anchors.entries()) {
|
|
530
571
|
throwIfAborted(options.abortSignal, "harmonic retrieval aborted");
|
|
531
572
|
const eligibleNodeRefs = anchor.nodeRefs;
|
|
532
|
-
const
|
|
533
|
-
const
|
|
534
|
-
const { score, matchedFields } = scoreAnchor(anchor, queryTokens, eligibleAnchorTags);
|
|
573
|
+
const anchorTokens = searchIndex.anchorTokens[anchorIndex];
|
|
574
|
+
const { score, matchedFields } = scoreAnchor(anchorTokens, queryTokens);
|
|
535
575
|
if (score <= 0) continue;
|
|
536
576
|
for (const nodeRef of eligibleNodeRefs) {
|
|
537
|
-
const node =
|
|
577
|
+
const node = searchIndex.nodesById.get(nodeRef);
|
|
538
578
|
if (!node) continue;
|
|
539
579
|
const existing = candidates.get(nodeRef) ?? {
|
|
540
580
|
node,
|
|
@@ -574,6 +614,7 @@ async function searchHarmonicRetrieval(options) {
|
|
|
574
614
|
}
|
|
575
615
|
|
|
576
616
|
export {
|
|
617
|
+
harmonicSearchIndexStats,
|
|
577
618
|
readAbstractionNodes,
|
|
578
619
|
readCueAnchors,
|
|
579
620
|
harmonicGraphCacheStats,
|
|
@@ -585,4 +626,4 @@ export {
|
|
|
585
626
|
readProjectedHarmonicGraph,
|
|
586
627
|
searchHarmonicRetrieval
|
|
587
628
|
};
|
|
588
|
-
//# sourceMappingURL=chunk-
|
|
629
|
+
//# sourceMappingURL=chunk-5Y3UVK6S.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/harmonic-retrieval.ts"],"sourcesContent":["import path from \"node:path\";\nimport { realpath } from \"node:fs/promises\";\nimport { listJsonFilesStrict, readJsonFile } from \"./json-store.js\";\nimport { raceAbort, throwIfAborted } from \"./abort-error.js\";\nimport { log } from \"./logger.js\";\nimport { readHarmonicGraphStamp } from \"./harmonic-graph-version.js\";\nimport { inferMemoryStatus, toMemoryPathRel } from \"./memory-lifecycle-ledger-utils.js\";\n import {\n HARMONIC_SOURCE_MEMORY_INSERTED_AT_KEY,\n resolveAbstractionNodeStoreDir,\n validateAbstractionNode,\n type AbstractionNode,\n } from \"./abstraction-nodes.js\";\nimport { resolveCueAnchorStoreDir, validateCueAnchor, type CueAnchor, type CueAnchorType } from \"./cue-anchors.js\";\nimport { compareDeterministicStrings } from \"./deterministic-order.js\";\nimport { normalizeRecallTokenSet, normalizeRecallTokens } from \"./recall-tokenization.js\";\nimport { stripAttributesSuffix } from \"./structured-attributes.js\";\nimport { isValidityExpiredNow } from \"./temporal-validity.js\";\nimport { assertSafePathSegment, isRecord } from \"./store-contract.js\";\nimport { isSupportPassportPrivateMemory } from \"./support-passport/card-projection.js\";\nimport type { MemoryFile } from \"./types.js\";\nimport { readProjectedMemoryStates } from \"./memory-projection-batch.js\";\nimport { SecureStoreLockedError } from \"./secure-store/secure-fs.js\";\nimport { StorageManager } from \"./storage.js\";\nimport { RECALL_FALLBACK_DIRS } from \"./utils/category-dir.js\";\nimport { readHarmonicSourceMemory, readUnresolvedHarmonicSources } from \"./harmonic-source-lookup.js\";\nimport { mapInBatches } from \"./map-in-batches.js\";\n\n\ntype SourceMemoryMap = Map<string, MemoryFile>;\n\n\n// An index older than this is treated as unusable: the date window needed to\n// cover \"created since the last rebuild\" would stop being cheap.\nconst INDEX_MAX_AGE_MS = 7 * 86_400_000;\nconst DAY_MS = 86_400_000;\n\nfunction utcDaysSince(rebuiltMs: number, nowMs: number): string[] {\n const days: string[] = [];\n for (let day = Math.floor((rebuiltMs - DAY_MS) / DAY_MS) * DAY_MS; day <= nowMs; day += DAY_MS) {\n days.push(new Date(day).toISOString().slice(0, 10));\n }\n return days;\n}\n\n\n// Memories the projection has no row for were written after its last rebuild, so\n// their dated directory is normally one of `days`. Hot and cold tiers are probed\n// by exact path. Only recall-corpus categories are probed: `questions/` is a queue\n// and `artifacts/` is outside the recall surface, so neither can be a source.\nfunction unprojectedCandidatePaths(memoryDir: string, id: string, days: string[]): string[] {\n const paths: string[] = [];\n for (const root of [memoryDir, path.join(memoryDir, \"cold\")]) {\n for (const dir of RECALL_FALLBACK_DIRS) {\n paths.push(path.join(root, dir, `${id}.md`));\n for (const day of days) paths.push(path.join(root, dir, day, `${id}.md`));\n }\n }\n return paths;\n}\n\n/** Resolve indexed sources first, then use the durable unresolved-id path cache. */\nasync function readIndexedSourceMemories(options: {\n memoryDir: string;\n abortSignal?: AbortSignal;\n sourceMemoryIds: string[];\n nowMs: number;\n}): Promise<SourceMemoryMap | null> {\n // The ids go to SQL as bound parameters, so any id the projection holds is safe to look up.\n const batch = readProjectedMemoryStates(options.memoryDir, options.sourceMemoryIds);\n const rebuiltMs = Date.parse(batch?.rebuiltAt ?? \"\");\n if (!batch?.complete || !batch.rebuiltAt || !Number.isFinite(rebuiltMs) || options.nowMs - rebuiltMs > INDEX_MAX_AGE_MS) return null;\n const rootReal = await realpath(options.memoryDir).catch(() => null);\n if (rootReal === null) return null;\n\n const storage = new StorageManager(options.memoryDir);\n const days = utcDaysSince(rebuiltMs, options.nowMs);\n const sourceMemories: SourceMemoryMap = new Map();\n const pending: string[] = [];\n const resolved = await mapInBatches(options.sourceMemoryIds, async (id) => {\n const state = batch.states.get(id);\n // An id is only ever joined into a path when it is a single safe segment.\n let safeId = true;\n try {\n assertSafePathSegment(id, \"sourceMemoryId\");\n } catch {\n safeId = false;\n }\n // state.path was containment-checked by the projection reader.\n const candidates = state\n ? [state.path, path.join(options.memoryDir, \"cold\", state.pathRel)]\n : safeId ? unprojectedCandidatePaths(options.memoryDir, id, days) : [];\n for (const candidate of candidates) {\n const memory = await readHarmonicSourceMemory(storage, rootReal, candidate, options.abortSignal);\n if (memory?.frontmatter.id !== id) continue;\n return { id, memory };\n }\n return { id, memory: undefined };\n });\n for (const { id, memory } of resolved) {\n if (memory) sourceMemories.set(id, memory);\n else pending.push(id);\n }\n if (pending.length === 0) return sourceMemories;\n\n const unresolved = await readUnresolvedHarmonicSources({\n storage, rootReal, rebuiltAt: batch.rebuiltAt, sourceMemoryIds: pending,\n nowMs: options.nowMs, abortSignal: options.abortSignal,\n });\n for (const [id, memory] of unresolved) sourceMemories.set(id, memory);\n return sourceMemories;\n}\n\nasync function readCorpusSourceMemories(options: {\n memoryDir: string;\n abortSignal?: AbortSignal;\n}): Promise<SourceMemoryMap> {\n const sourceMemories: SourceMemoryMap = new Map();\n try {\n const storage = new StorageManager(options.memoryDir);\n const [hotMemories, coldMemories] = await Promise.all([\n storage.readAllMemories({ abortSignal: options.abortSignal }),\n storage.readAllColdMemories({ abortSignal: options.abortSignal }),\n ]);\n for (const memory of [...hotMemories, ...coldMemories]) {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n sourceMemories.set(memory.frontmatter.id, memory);\n }\n } catch (err) {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n if (err instanceof SecureStoreLockedError) return new Map();\n // Source validation fails closed when the authorized memory directory is\n // unreadable. Source-less nodes remain eligible for retrieval.\n sourceMemories.clear();\n }\n return sourceMemories;\n}\n\nasync function readSourceMemories(options: {\n memoryDir: string;\n abortSignal?: AbortSignal;\n sourceMemoryIds: string[];\n nowMs?: number;\n}): Promise<SourceMemoryMap> {\n try {\n const indexed = await readIndexedSourceMemories({\n memoryDir: options.memoryDir,\n abortSignal: options.abortSignal,\n sourceMemoryIds: options.sourceMemoryIds,\n nowMs: options.nowMs ?? Date.now(),\n });\n if (indexed) return indexed;\n } catch (err) {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n if (err instanceof SecureStoreLockedError) return new Map();\n }\n return readCorpusSourceMemories(options);\n}\n\nfunction parseSourceMemoryInsertedAt(node: AbstractionNode): Map<string, string> {\n const insertedAtById = new Map<string, string>();\n const insertedAtRaw = node.metadata?.[HARMONIC_SOURCE_MEMORY_INSERTED_AT_KEY];\n if (!insertedAtRaw) return insertedAtById;\n try {\n const parsed = JSON.parse(insertedAtRaw) as unknown;\n if (!isRecord(parsed)) return insertedAtById;\n for (const [memoryId, value] of Object.entries(parsed)) {\n if (typeof value === \"string\") insertedAtById.set(memoryId, value);\n }\n } catch {\n // Malformed insertion metadata leaves ordering on the recordedAt fallback.\n }\n return insertedAtById;\n}\n\n/**\n * Whether a source memory can back a projected node at all. Shared with `earliestInvalidAtMs`, so the cache\n * deadline only follows a source that the projection would use.\n * #2332: a private support-passport record leaves the eligible set the same way a rejected one does — a node\n * title or anchor attribution rebuilt from it would leak governed metadata into the deep-recall frontier (and\n * every other graph reader) before any content check runs.\n */\nfunction isEligibleSourceMemory(memory: MemoryFile, memoryDir: string): boolean {\n return (\n !isSupportPassportPrivateMemory(memory) &&\n inferMemoryStatus(memory.frontmatter, toMemoryPathRel(memoryDir, memory.path)) === \"active\"\n );\n}\n\nfunction projectSourceBackedNode(\n node: AbstractionNode,\n sourceMemories: SourceMemoryMap,\n memoryDir: string,\n temporalExpiredInInjection: boolean,\n nowMs: number\n): AbstractionNode | null {\n const sourceMemoryIds = node.sourceMemoryIds ?? [];\n if (sourceMemoryIds.length === 0) return node;\n\n const activeSourceMemoryIds = sourceMemoryIds.filter((memoryId) => {\n const memory = sourceMemories.get(memoryId);\n return (\n memory !== undefined &&\n isEligibleSourceMemory(memory, memoryDir) &&\n (temporalExpiredInInjection || !isValidityExpiredNow(memory.frontmatter, nowMs))\n );\n });\n if (activeSourceMemoryIds.length === 0) return null;\n\n // Newest-first source order keeps the projected title and summary on the most\n // recently inserted facts. Equal or missing timestamps fall back to ascending\n // id order, which matches the stored sourceMemoryIds order.\n const insertedAtById = parseSourceMemoryInsertedAt(node);\n const insertedAtMs = (memoryId: string): number => {\n const parsedMs = Date.parse(insertedAtById.get(memoryId) ?? \"\");\n return Number.isFinite(parsedMs) ? parsedMs : Date.parse(node.recordedAt);\n };\n activeSourceMemoryIds.sort(\n (left, right) =>\n insertedAtMs(right) - insertedAtMs(left) || compareDeterministicStrings(left, right)\n );\n\n const activeMemories = activeSourceMemoryIds.flatMap((memoryId) => {\n const memory = sourceMemories.get(memoryId);\n return memory ? [memory] : [];\n });\n const activeContents = activeMemories.map((memory) =>\n memory.frontmatter.structuredAttributes ? stripAttributesSuffix(memory.content) : memory.content\n );\n let metadata: Record<string, string> | undefined;\n const activeInsertedAt = activeSourceMemoryIds.flatMap((memoryId) => {\n const value = insertedAtById.get(memoryId);\n return typeof value === \"string\" ? [[memoryId, value] as const] : [];\n });\n if (activeInsertedAt.length > 0) {\n metadata = {\n [HARMONIC_SOURCE_MEMORY_INSERTED_AT_KEY]: JSON.stringify(Object.fromEntries(activeInsertedAt)),\n };\n }\n\n return {\n ...node,\n sourceMemoryIds: activeSourceMemoryIds,\n title: activeContents[0]?.slice(0, 80) ?? node.title,\n summary: activeContents.slice(0, 3).join(\"; \").slice(0, 400),\n tags: [...new Set(activeMemories.flatMap((memory) => memory.frontmatter.tags))].sort(compareDeterministicStrings),\n entityRefs: [\n ...new Set(\n activeMemories.flatMap((memory) =>\n typeof memory.frontmatter.entityRef === \"string\" ? [memory.frontmatter.entityRef] : []\n )\n ),\n ].sort(compareDeterministicStrings),\n metadata,\n };\n}\n\nfunction anchorMatchesProjectedNode(\n anchor: CueAnchor,\n nodeRef: string,\n node: AbstractionNode,\n allowLegacyAttribution: boolean\n): boolean {\n const activeSourceMemoryIds = node.sourceMemoryIds ?? [];\n if (activeSourceMemoryIds.length === 0) return true;\n if (!anchor.sourceMemoryIdsByNodeRef) return allowLegacyAttribution;\n const anchorSourceMemoryIds = anchor.sourceMemoryIdsByNodeRef[nodeRef] ?? [];\n return anchorSourceMemoryIds.some((sourceMemoryId) => activeSourceMemoryIds.includes(sourceMemoryId));\n}\n\nexport interface HarmonicMatchedAnchor {\n anchorId: string;\n anchorType: CueAnchorType;\n anchorValue: string;\n}\n\nexport interface HarmonicRetrievalResult {\n node: AbstractionNode;\n score: number;\n nodeScore: number;\n anchorScore: number;\n matchedFields: string[];\n matchedAnchors: HarmonicMatchedAnchor[];\n}\n\ninterface HarmonicCandidate {\n node: AbstractionNode;\n nodeScore: number;\n anchorScore: number;\n matchedFields: Set<string>;\n matchedAnchors: Map<string, HarmonicMatchedAnchor>;\n}\n\nfunction tokenOverlap(queryTokens: Set<string>, fieldTokens: ReadonlySet<string>): number {\n let matches = 0;\n for (const token of queryTokens) {\n if (fieldTokens.has(token)) matches += 1;\n }\n return matches;\n}\n\ninterface HarmonicNodeTokens {\n title: ReadonlySet<string>;\n summary: ReadonlySet<string>;\n tags: ReadonlySet<string>;\n entities: ReadonlySet<string>;\n kind: ReadonlySet<string>;\n}\n\ninterface HarmonicAnchorTokens {\n value: ReadonlySet<string>;\n normalized: ReadonlySet<string>;\n type: ReadonlySet<string>;\n eligibleTags: ReadonlySet<string>;\n}\n\ninterface HarmonicSearchIndex {\n nodesById: Map<string, AbstractionNode>;\n nodeTokens: HarmonicNodeTokens[];\n anchorTokens: HarmonicAnchorTokens[];\n}\n\nexport const harmonicSearchIndexStats = { builds: 0 };\n\n/**\n * Per-graph scoring index, keyed on the frozen graph object itself. Scoring a\n * recall tokenizes every node's title/summary/tags/entities/kind and every\n * anchor's value/cue/type/eligible tags; on a cache hit that repeated the\n * whole normalization for each recall (~0.75 s on a ~2.5k node, ~10k anchor\n * corpus, issue #3450). The sets are identical to what `countRecallTokenOverlap`\n * computed from the raw fields, so scores and matchedFields are unchanged.\n * For an uncached graph the index is built per call — the same work the old\n * code did inline.\n */\nconst harmonicSearchIndexes = new WeakMap<ProjectedHarmonicGraph, HarmonicSearchIndex>();\n\nfunction getHarmonicSearchIndex(graph: ProjectedHarmonicGraph): HarmonicSearchIndex {\n const cached = harmonicSearchIndexes.get(graph);\n if (cached) return cached;\n harmonicSearchIndexStats.builds += 1;\n const nodesById = new Map(graph.nodes.map((node) => [node.nodeId, node]));\n // Node ids are only unique per record day (nodes/<day>/<nodeId>.json), so\n // tokens are indexed by position in graph.nodes.\n const nodeTokens = graph.nodes.map((node) => ({\n title: normalizeRecallTokenSet(node.title ?? \"\"),\n summary: normalizeRecallTokenSet(node.summary ?? \"\"),\n tags: normalizeRecallTokenSet(node.tags?.join(\" \") ?? \"\"),\n entities: normalizeRecallTokenSet(node.entityRefs?.join(\" \") ?? \"\"),\n kind: normalizeRecallTokenSet(`${node.kind} ${node.abstractionLevel}`),\n }));\n // Anchor ids are only unique per anchorType (cue-anchors dedups by\n // type+id), so tokens are indexed by position in graph.anchors.\n const anchorTokens = graph.anchors.map((anchor) => {\n const eligibleNodeTags = new Set(anchor.nodeRefs.flatMap((nodeRef) => nodesById.get(nodeRef)?.tags ?? []));\n const eligibleAnchorTags = anchor.tags?.filter((tag) => eligibleNodeTags.has(tag)) ?? [];\n return {\n value: normalizeRecallTokenSet(anchor.anchorValue ?? \"\"),\n normalized: normalizeRecallTokenSet(anchor.normalizedCue ?? \"\"),\n type: normalizeRecallTokenSet(anchor.anchorType),\n eligibleTags: normalizeRecallTokenSet(eligibleAnchorTags.join(\" \")),\n };\n });\n const index: HarmonicSearchIndex = { nodesById, nodeTokens, anchorTokens };\n harmonicSearchIndexes.set(graph, index);\n return index;\n}\n\nfunction scoreNode(tokens: HarmonicNodeTokens, queryTokens: Set<string>): { score: number; matchedFields: string[] } {\n const matchedFields: string[] = [];\n let score = 0;\n\n const titleMatches = tokenOverlap(queryTokens, tokens.title);\n if (titleMatches > 0) {\n score += titleMatches * 3;\n matchedFields.push(\"title\");\n }\n\n const summaryMatches = tokenOverlap(queryTokens, tokens.summary);\n if (summaryMatches > 0) {\n score += summaryMatches * 3;\n matchedFields.push(\"summary\");\n }\n\n const tagMatches = tokenOverlap(queryTokens, tokens.tags);\n if (tagMatches > 0) {\n score += tagMatches * 2;\n matchedFields.push(\"tags\");\n }\n\n const entityMatches = tokenOverlap(queryTokens, tokens.entities);\n if (entityMatches > 0) {\n score += entityMatches * 2;\n matchedFields.push(\"entityRefs\");\n }\n\n const kindMatches = tokenOverlap(queryTokens, tokens.kind);\n if (kindMatches > 0) {\n score += kindMatches;\n matchedFields.push(\"kind\");\n }\n\n return { score, matchedFields };\n}\n\nfunction scoreAnchor(tokens: HarmonicAnchorTokens, queryTokens: Set<string>): { score: number; matchedFields: string[] } {\n const matchedFields: string[] = [];\n let score = 0;\n\n const valueMatches = tokenOverlap(queryTokens, tokens.value);\n const normalizedMatches = tokenOverlap(queryTokens, tokens.normalized);\n const cueMatches = Math.max(valueMatches, normalizedMatches);\n if (cueMatches > 0) {\n score += cueMatches * 4;\n if (valueMatches > 0) matchedFields.push(\"anchorValue\");\n if (normalizedMatches > 0) matchedFields.push(\"anchor\");\n }\n\n const typeMatches = tokenOverlap(queryTokens, tokens.type);\n if (typeMatches > 0) {\n score += typeMatches;\n matchedFields.push(\"anchorType\");\n }\n\n const tagMatches = tokenOverlap(queryTokens, tokens.eligibleTags);\n if (tagMatches > 0) {\n score += tagMatches * 2;\n matchedFields.push(\"anchorTags\");\n }\n\n return { score, matchedFields };\n}\n\nexport async function readAbstractionNodes(options: {\n memoryDir: string;\n abstractionNodeStoreDir?: string;\n}): Promise<AbstractionNode[]> {\n const rootDir = resolveAbstractionNodeStoreDir(options.memoryDir, options.abstractionNodeStoreDir);\n const files = await listJsonFilesStrict(path.join(rootDir, \"nodes\"), { allowMissingDirectory: true });\n const parsed = await mapInBatches(files, async (filePath) => {\n try {\n return validateAbstractionNode(await readJsonFile(filePath));\n } catch {\n // fail-open: invalid artifacts stay visible via status tooling instead of recall\n return null;\n }\n });\n return parsed.filter((node): node is AbstractionNode => node !== null);\n}\n\nexport async function readCueAnchors(options: {\n memoryDir: string;\n abstractionNodeStoreDir?: string;\n}): Promise<CueAnchor[]> {\n const abstractionRoot = resolveAbstractionNodeStoreDir(options.memoryDir, options.abstractionNodeStoreDir);\n const rootDir = resolveCueAnchorStoreDir(abstractionRoot);\n const files = await listJsonFilesStrict(rootDir, { allowMissingDirectory: true });\n const parsed = await mapInBatches(files, async (filePath) => {\n try {\n return validateCueAnchor(await readJsonFile(filePath));\n } catch {\n // fail-open: invalid artifacts stay visible via status tooling instead of recall\n return null;\n }\n });\n return parsed.filter((anchor): anchor is CueAnchor => anchor !== null);\n}\n\nexport interface ProjectedHarmonicGraph {\n nodes: AbstractionNode[];\n anchors: CueAnchor[];\n}\n\n/**\n * Read nodes + anchors and project BOTH against the namespace's current active\n * memories. This is the single projection every graph reader shares: a raw\n * `readAbstractionNodes` / `readCueAnchors` pair still carries the stored title,\n * summary, tags, and anchor attribution of a memory that was later rejected,\n * quarantined, or otherwise moved out of the active set, so a second reader\n * that skipped the projection could leak governed metadata even when the\n * memory itself is excluded from the final results.\n *\n * - A node whose every source memory left the active set is dropped.\n * - A surviving node's title/summary/tags/entityRefs are rebuilt from its\n * active sources only.\n * - An anchor keeps a node reference only while its attribution runs through\n * one of that node's surviving active sources, and is dropped once no\n * reference survives.\n */\ninterface ExpiringHarmonicGraph extends ProjectedHarmonicGraph {\n /** First instant a source memory's `invalid_at` passes: from then on the graph is wrong without any write. */\n validUntilMs: number;\n}\n\nfunction earliestInvalidAtMs(sourceMemories: SourceMemoryMap, memoryDir: string, nowMs: number): number {\n let earliest = Number.POSITIVE_INFINITY;\n for (const memory of sourceMemories.values()) {\n // An ineligible source drops out of the projection whatever its `invalid_at`, so its deadline changes nothing.\n if (!isEligibleSourceMemory(memory, memoryDir)) continue;\n const invalidAtMs = Date.parse(memory.frontmatter.invalid_at?.trim() ?? \"\");\n if (Number.isFinite(invalidAtMs) && invalidAtMs > nowMs && invalidAtMs < earliest) earliest = invalidAtMs;\n }\n return earliest;\n}\n\nasync function buildProjectedHarmonicGraph(options: {\n memoryDir: string;\n abstractionNodeStoreDir?: string;\n anchorsEnabled: boolean;\n abortSignal?: AbortSignal;\n temporalExpiredInInjection?: boolean;\n nowMs?: number;\n}): Promise<ProjectedHarmonicGraph> {\n const { nodes, anchors } = await buildExpiringHarmonicGraph(options);\n return { nodes, anchors };\n}\n\nasync function buildExpiringHarmonicGraph(options: {\n memoryDir: string;\n abstractionNodeStoreDir?: string;\n anchorsEnabled: boolean;\n abortSignal?: AbortSignal;\n temporalExpiredInInjection?: boolean;\n nowMs?: number;\n}): Promise<ExpiringHarmonicGraph> {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n const buildDelayMs = harmonicGraphBuildTestHooks?.buildDelayMs;\n if (buildDelayMs !== undefined && buildDelayMs > 0) {\n await new Promise((resolve) => setTimeout(resolve, buildDelayMs));\n }\n const nodes = await readAbstractionNodes(options);\n const sourceMemoryIds = [...new Set(nodes.flatMap((node) => node.sourceMemoryIds ?? []))];\n const sourceMemories: SourceMemoryMap = sourceMemoryIds.length > 0\n ? await readSourceMemories({\n memoryDir: options.memoryDir,\n abortSignal: options.abortSignal,\n sourceMemoryIds,\n nowMs: options.nowMs,\n })\n : new Map();\n const nowMs = options.nowMs ?? Date.now();\n // With temporalExpiredInInjection the validity filter is off, so no `invalid_at` can age the graph.\n const validUntilMs = options.temporalExpiredInInjection === true\n ? Number.POSITIVE_INFINITY\n : earliestInvalidAtMs(sourceMemories, options.memoryDir, nowMs);\n // A node whose full stored source set survived projection keeps legacy\n // anchor attribution (an anchor written before per-node source ids existed).\n const legacyCompatibleNodeRefs = new Set<string>();\n const projectedNodes = nodes.flatMap((node) => {\n const projected = projectSourceBackedNode(\n node,\n sourceMemories,\n options.memoryDir,\n options.temporalExpiredInInjection === true,\n nowMs\n );\n if (\n projected &&\n (node.sourceMemoryIds?.length ?? 0) > 0 &&\n projected.sourceMemoryIds?.length === node.sourceMemoryIds?.length\n ) {\n legacyCompatibleNodeRefs.add(node.nodeId);\n }\n return projected ? [projected] : [];\n });\n if (!options.anchorsEnabled) return { nodes: projectedNodes, anchors: [], validUntilMs };\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n const nodeIndex = new Map(projectedNodes.map((node) => [node.nodeId, node]));\n const anchors = (await readCueAnchors(options)).flatMap((anchor) => {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n const nodeRefs = anchor.nodeRefs.filter((nodeRef) => {\n const node = nodeIndex.get(nodeRef);\n return (\n node !== undefined &&\n anchorMatchesProjectedNode(anchor, nodeRef, node, legacyCompatibleNodeRefs.has(nodeRef))\n );\n });\n return nodeRefs.length > 0 ? [{ ...anchor, nodeRefs }] : [];\n });\n return { nodes: projectedNodes, anchors, validUntilMs };\n}\n\nconst GRAPH_CACHE_TTL_MS = 30_000;\n/**\n * Past the TTL a graph whose stamp is unchanged is still served while a refresh runs behind it, so no\n * recall waits for a rebuild just because the TTL lapsed. This is how long past the TTL; after it the graph is rebuilt first.\n */\nconst GRAPH_CACHE_MAX_STALE_MS = 300_000;\nconst GRAPH_CACHE_MAX_ENTRIES = 8;\n\ninterface GraphCacheEntry {\n stamp: string;\n /** When the build finished, so the TTL measures how long the graph has been available. */\n builtAtMs: number;\n validUntilMs: number;\n graph: ProjectedHarmonicGraph;\n}\n\ninterface GraphBuild {\n stamp: string;\n promise: Promise<ProjectedHarmonicGraph>;\n /** Cancels the build's source scan; fired when no caller is waiting for it. */\n controller: AbortController;\n /** Callers currently waiting for this build. */\n waiting: number;\n}\n\nconst graphCache = new Map<string, GraphCacheEntry>();\n/** One build per cache key at a time: every recall that lands on a miss waits for the same build. */\nconst graphBuilds = new Map<string, GraphBuild>();\n/** When a background refresh last failed, per key: stale reads retry at most once per TTL. Capped like the cache. */\nconst refreshFailedAtMs = new Map<string, number>();\n\nfunction rememberRefreshFailure(key: string): void {\n refreshFailedAtMs.delete(key);\n refreshFailedAtMs.set(key, Date.now());\n while (refreshFailedAtMs.size > GRAPH_CACHE_MAX_ENTRIES) {\n const oldest = refreshFailedAtMs.keys().next().value;\n if (oldest === undefined) break;\n refreshFailedAtMs.delete(oldest);\n }\n}\n\n/**\n * A source's `invalid_at` can pass while the build is still reading anchors, which would hand every caller\n * that joined this build a graph that is already expired. Rebuild until the graph is unexpired at completion.\n * Each round drops the sources that expired, so the set of future deadlines shrinks and the loop ends.\n */\nasync function buildUnexpiredHarmonicGraph(options: GraphReadOptions, abortSignal: AbortSignal): Promise<ExpiringHarmonicGraph> {\n for (;;) {\n const built = await buildExpiringHarmonicGraph({\n memoryDir: options.memoryDir,\n abstractionNodeStoreDir: options.abstractionNodeStoreDir,\n anchorsEnabled: options.anchorsEnabled,\n temporalExpiredInInjection: options.temporalExpiredInInjection,\n abortSignal,\n });\n if (Date.now() < built.validUntilMs) return built;\n }\n}\n/** Counters for tests and diagnostics. `stale` hits also count as `hits`. */\nexport const harmonicGraphCacheStats = { hits: 0, misses: 0, stale: 0, shared: 0, deadlineExits: 0 };\n\n/** Default per-caller bound on waiting for a shared graph build (see `waitBudgetMs`). */\nexport const HARMONIC_GRAPH_WAIT_BUDGET_MS = 5_000;\n\nconst HARMONIC_GRAPH_WAIT_DEADLINE_MESSAGE = \"harmonic graph wait deadline exceeded\";\n\nexport class HarmonicGraphWaitDeadlineError extends Error {\n constructor() {\n super(HARMONIC_GRAPH_WAIT_DEADLINE_MESSAGE);\n this.name = \"HarmonicGraphWaitDeadlineError\";\n }\n}\n\ninterface HarmonicGraphBuildTestHooks {\n /** Extra delay inside every build, for wait-budget tests. */\n buildDelayMs?: number;\n}\nlet harmonicGraphBuildTestHooks: HarmonicGraphBuildTestHooks | null = null;\nexport function setHarmonicGraphBuildTestHooks(hooks: HarmonicGraphBuildTestHooks | null): void {\n harmonicGraphBuildTestHooks = hooks;\n}\n\n/** Freeze records and their nested arrays/objects so a caller cannot corrupt the shared cache. */\nfunction deepFreeze<T extends object>(value: T): T {\n // isFrozen is true for primitives and null, and a frozen value is not revisited, so this ends on cycles too.\n if (Object.isFrozen(value)) return value;\n Object.freeze(value);\n for (const child of Object.values(value)) deepFreeze(child);\n return value;\n}\n\nexport function clearHarmonicGraphCache(): void {\n graphCache.clear();\n graphBuilds.clear();\n refreshFailedAtMs.clear();\n}\n\n/**\n * Resolves once every build running now has settled, and after the failure bookkeeping of a background\n * refresh (that handler was attached when the refresh started, so it runs first). For tests: a time-based\n * wait races a slow build.\n */\nexport async function settleHarmonicGraphBuilds(): Promise<void> {\n await Promise.allSettled([...graphBuilds.values()].map((build) => build.promise));\n}\n\ntype GraphReadOptions = Parameters<typeof buildProjectedHarmonicGraph>[0];\n\n/**\n * Start the one build for `key`. The build owns an abort controller instead of using one caller's signal,\n * so a caller that leaves does not cancel it for the others; `joinGraphBuild` cancels it when the last caller leaves.\n */\nfunction startGraphBuild(key: string, stamp: string, options: GraphReadOptions): GraphBuild {\n harmonicGraphCacheStats.misses++;\n const controller = new AbortController();\n const promise: Promise<ProjectedHarmonicGraph> = buildUnexpiredHarmonicGraph(options, controller.signal)\n .then((built) => {\n const graph = { nodes: deepFreeze(built.nodes), anchors: deepFreeze(built.anchors) };\n // A cleared cache or a newer build for this key has replaced this one: do not store a stale graph.\n if (graphBuilds.get(key)?.promise !== promise) return graph;\n refreshFailedAtMs.delete(key);\n graphCache.delete(key);\n graphCache.set(key, { stamp, builtAtMs: Date.now(), validUntilMs: built.validUntilMs, graph });\n while (graphCache.size > GRAPH_CACHE_MAX_ENTRIES) {\n const oldest = graphCache.keys().next().value;\n if (oldest === undefined) break;\n graphCache.delete(oldest);\n }\n return graph;\n })\n .finally(() => {\n if (graphBuilds.get(key)?.promise === promise) graphBuilds.delete(key);\n });\n const build: GraphBuild = { stamp, promise, controller, waiting: 0 };\n graphBuilds.set(key, build);\n return build;\n}\n\n/**\n * Wait for `build` on behalf of one caller. The caller's own signal ends only its own wait. When the last\n * waiting caller has left, the build is cancelled and dropped, so abandoned recalls do not leave full scans running\n * (cancelling a build that already finished does nothing). A caller that leaves on `waitBudgetMs` is the exception:\n * the build keeps running so its completed graph warms the cache for the next caller.\n */\nfunction joinGraphBuild(\n key: string,\n build: GraphBuild,\n signal: AbortSignal | undefined,\n waitBudgetMs?: number,\n): Promise<ProjectedHarmonicGraph> {\n build.waiting++;\n let timedOut = false;\n let timer: NodeJS.Timeout | undefined;\n const waited =\n waitBudgetMs === undefined || waitBudgetMs <= 0\n ? raceAbort(build.promise, signal, \"harmonic retrieval aborted\")\n : Promise.race([\n raceAbort(build.promise, signal, \"harmonic retrieval aborted\"),\n new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n timedOut = true;\n reject(new HarmonicGraphWaitDeadlineError());\n }, waitBudgetMs);\n }),\n ]);\n return waited.finally(() => {\n if (timer) clearTimeout(timer);\n build.waiting--;\n // A caller that left on the wait budget does not cancel the build: it keeps\n // running and stores the fresh graph, so the next caller gets a cache hit\n // instead of restarting the scan a write storm keeps invalidating.\n if (timedOut) harmonicGraphCacheStats.deadlineExits++;\n if (build.waiting > 0 || timedOut) return;\n if (graphBuilds.get(key) === build) graphBuilds.delete(key);\n build.controller.abort();\n });\n}\n\n/**\n * `readProjectedHarmonicGraph` with an opt-in in-memory cache. Every recall used\n * to re-read all nodes, anchors and source memories from disk (about 4.7 s on a\n * 2107 node, 9199 anchor, 4105 source graph). With `useCache` a completed graph is\n * reused while the stamp below is unchanged: the memory corpus, memory status and\n * cold-write version sentinels (bumped by every memory write, in any process) and\n * the graph version sentinel (bumped by node and anchor writes). A stamp read is\n * four stats, not a scan of the memories. The TTL bounds the one input a sentinel\n * cannot see, which is wall-clock validity expiry; past it the stale graph is served\n * while one refresh runs (up to GRAPH_CACHE_MAX_STALE_MS). A changed stamp always\n * waits for a fresh build, because a stale graph could carry governed metadata of a\n * memory that left the active set. Concurrent misses share one build. An explicit\n * `nowMs` bypasses the cache so tests stay deterministic. The cached arrays are\n * frozen: callers must not mutate them.\n */\nexport async function readProjectedHarmonicGraph(options: {\n memoryDir: string;\n abstractionNodeStoreDir?: string;\n anchorsEnabled: boolean;\n abortSignal?: AbortSignal;\n temporalExpiredInInjection?: boolean;\n nowMs?: number;\n useCache?: boolean;\n /** Per-caller bound on joining a shared build, in ms. On expiry the caller\n * leaves with a HarmonicGraphWaitDeadlineError while the build keeps running.\n * `0` or unset waits without a bound. Applies only on the cached path. */\n waitBudgetMs?: number;\n}): Promise<ProjectedHarmonicGraph> {\n if (options.useCache !== true || options.nowMs !== undefined) return buildProjectedHarmonicGraph(options);\n // Same cancellation contract as the builder: a cache hit must not mask an aborted signal.\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n const nodeStoreDir = resolveAbstractionNodeStoreDir(options.memoryDir, options.abstractionNodeStoreDir);\n const key = JSON.stringify([\n options.memoryDir,\n nodeStoreDir,\n options.anchorsEnabled === true,\n options.temporalExpiredInInjection === true,\n ]);\n // The stamp is read BEFORE the build, so a write that lands mid-build leaves the\n // entry stale and the next call rebuilds.\n const stamp = readHarmonicGraphStamp(options.memoryDir, nodeStoreDir);\n const nowMs = Date.now();\n const hit = graphCache.get(key);\n // A source's `invalid_at` passing changes the projection without bumping the stamp, so it ends the entry\n // at the exact instant, however fresh the entry is.\n if (hit && hit.stamp === stamp && nowMs < hit.validUntilMs && nowMs - hit.builtAtMs < GRAPH_CACHE_TTL_MS + GRAPH_CACHE_MAX_STALE_MS) {\n harmonicGraphCacheStats.hits++;\n graphCache.delete(key);\n graphCache.set(key, hit);\n if (nowMs - hit.builtAtMs >= GRAPH_CACHE_TTL_MS) {\n harmonicGraphCacheStats.stale++;\n const failedAtMs = refreshFailedAtMs.get(key);\n const backingOff = failedAtMs !== undefined && nowMs - failedAtMs < GRAPH_CACHE_TTL_MS;\n if (graphBuilds.get(key)?.stamp !== stamp && !backingOff) {\n startGraphBuild(key, stamp, options).promise.catch((err) => {\n rememberRefreshFailure(key);\n log.debug(`harmonic graph refresh failed: ${err}`);\n });\n }\n }\n return hit.graph;\n }\n const running = graphBuilds.get(key);\n if (running?.stamp === stamp) {\n harmonicGraphCacheStats.shared++;\n return joinGraphBuild(key, running, options.abortSignal, options.waitBudgetMs);\n }\n return joinGraphBuild(key, startGraphBuild(key, stamp, options), options.abortSignal, options.waitBudgetMs);\n}\n\nexport async function searchHarmonicRetrieval(options: {\n memoryDir: string;\n abstractionNodeStoreDir?: string;\n query: string;\n maxResults: number;\n sessionKey?: string;\n anchorsEnabled: boolean;\n abortSignal?: AbortSignal;\n temporalExpiredInInjection?: boolean;\n /** Share one projected graph between recalls until a write bumps a version sentinel (see readProjectedHarmonicGraph). */\n useGraphCache?: boolean;\n /** Bound on waiting for a shared graph build, in ms. Past it the search\n * rejects with a HarmonicGraphWaitDeadlineError so a recall fails open\n * instead of blocking on a rebuild a write storm keeps invalidating.\n * `0` waits without a bound. Defaults to HARMONIC_GRAPH_WAIT_BUDGET_MS. */\n waitBudgetMs?: number;\n}): Promise<HarmonicRetrievalResult[]> {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n const queryTokens = new Set(normalizeRecallTokens(options.query, [\"what\", \"which\"]));\n if (queryTokens.size === 0 || options.maxResults <= 0) return [];\n\n // One projection for every graph reader: nodes and anchors both arrive\n // already narrowed to the namespace's current active memories.\n const graph = await readProjectedHarmonicGraph({\n ...options,\n useCache: options.useGraphCache === true,\n waitBudgetMs:\n options.waitBudgetMs === undefined ? HARMONIC_GRAPH_WAIT_BUDGET_MS : options.waitBudgetMs,\n });\n const { nodes: eligibleNodes, anchors } = graph;\n const searchIndex = getHarmonicSearchIndex(graph);\n const candidates = new Map<string, HarmonicCandidate>();\n\n for (const [nodeIndexPos, node] of eligibleNodes.entries()) {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n const tokens = searchIndex.nodeTokens[nodeIndexPos];\n const { score, matchedFields } = scoreNode(tokens, queryTokens);\n if (score <= 0) continue;\n candidates.set(node.nodeId, {\n node,\n nodeScore: score,\n anchorScore: 0,\n matchedFields: new Set(matchedFields),\n matchedAnchors: new Map(),\n });\n }\n\n if (options.anchorsEnabled) {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n for (const [anchorIndex, anchor] of anchors.entries()) {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n // `nodeRefs` are the projection's surviving references already.\n const eligibleNodeRefs = anchor.nodeRefs;\n const anchorTokens = searchIndex.anchorTokens[anchorIndex];\n const { score, matchedFields } = scoreAnchor(anchorTokens, queryTokens);\n if (score <= 0) continue;\n for (const nodeRef of eligibleNodeRefs) {\n const node = searchIndex.nodesById.get(nodeRef);\n if (!node) continue;\n const existing = candidates.get(nodeRef) ?? {\n node,\n nodeScore: 0,\n anchorScore: 0,\n matchedFields: new Set<string>(),\n matchedAnchors: new Map<string, HarmonicMatchedAnchor>(),\n };\n existing.anchorScore += score;\n existing.matchedFields.add(\"anchor\");\n for (const field of matchedFields) existing.matchedFields.add(field);\n existing.matchedAnchors.set(anchor.anchorId, {\n anchorId: anchor.anchorId,\n anchorType: anchor.anchorType,\n anchorValue: anchor.anchorValue,\n });\n candidates.set(nodeRef, existing);\n }\n }\n }\n\n return [...candidates.values()]\n .map((candidate) => {\n let score = candidate.nodeScore + candidate.anchorScore;\n if (options.sessionKey && candidate.node.sessionKey === options.sessionKey) score += 0.5;\n return {\n node: candidate.node,\n score,\n nodeScore: candidate.nodeScore,\n anchorScore: candidate.anchorScore,\n matchedFields: [...candidate.matchedFields].sort(),\n matchedAnchors: [...candidate.matchedAnchors.values()].sort(\n (left, right) =>\n left.anchorType.localeCompare(right.anchorType) || left.anchorValue.localeCompare(right.anchorValue)\n ),\n };\n })\n .filter((result) => result.nodeScore > 0 || result.anchorScore > 0)\n .sort(\n (left, right) =>\n right.score - left.score ||\n right.anchorScore - left.anchorScore ||\n right.node.recordedAt.localeCompare(left.node.recordedAt)\n )\n .slice(0, options.maxResults);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,UAAU;AACjB,SAAS,gBAAgB;AAiCzB,IAAM,mBAAmB,IAAI;AAC7B,IAAM,SAAS;AAEf,SAAS,aAAa,WAAmB,OAAyB;AAChE,QAAM,OAAiB,CAAC;AACxB,WAAS,MAAM,KAAK,OAAO,YAAY,UAAU,MAAM,IAAI,QAAQ,OAAO,OAAO,OAAO,QAAQ;AAC9F,SAAK,KAAK,IAAI,KAAK,GAAG,EAAE,YAAY,EAAE,MAAM,GAAG,EAAE,CAAC;AAAA,EACpD;AACA,SAAO;AACT;AAOA,SAAS,0BAA0B,WAAmB,IAAY,MAA0B;AAC1F,QAAM,QAAkB,CAAC;AACzB,aAAW,QAAQ,CAAC,WAAW,KAAK,KAAK,WAAW,MAAM,CAAC,GAAG;AAC5D,eAAW,OAAO,sBAAsB;AACtC,YAAM,KAAK,KAAK,KAAK,MAAM,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Y,KAAK,OAAO,cAAc,CAAC,EACjE;AAAA,IACC,CAAC,MAAM,UACL,MAAM,QAAQ,KAAK,SACnB,MAAM,cAAc,KAAK,eACzB,MAAM,KAAK,WAAW,cAAc,KAAK,KAAK,UAAU;AAAA,EAC5D,EACC,MAAM,GAAG,QAAQ,UAAU;AAChC;","names":[]}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
resolveDefaultNamespaceRoot
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-T266H3RJ.js";
|
|
4
4
|
import {
|
|
5
5
|
StorageManager
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-NQ2WFFPQ.js";
|
|
7
7
|
import {
|
|
8
8
|
composeLocationDayBody,
|
|
9
9
|
composeLocationDayMeta,
|
|
@@ -779,4 +779,4 @@ export {
|
|
|
779
779
|
LOCATION_SYNC_DEFAULT_INTERVAL_MS,
|
|
780
780
|
startLocationAutoSync
|
|
781
781
|
};
|
|
782
|
-
//# sourceMappingURL=chunk-
|
|
782
|
+
//# sourceMappingURL=chunk-6ENFCUYH.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
parseEntityFile
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-NQ2WFFPQ.js";
|
|
4
4
|
import {
|
|
5
5
|
inferMemoryStatus
|
|
6
6
|
} from "./chunk-7RJUVTVF.js";
|
|
@@ -253,4 +253,4 @@ export {
|
|
|
253
253
|
WHO_KNOWS_MCP_TOOLS,
|
|
254
254
|
handleWhoKnowsHttpQuery
|
|
255
255
|
};
|
|
256
|
-
//# sourceMappingURL=chunk-
|
|
256
|
+
//# sourceMappingURL=chunk-6M3VJJON.js.map
|
|
@@ -36,7 +36,7 @@ import {
|
|
|
36
36
|
} from "./chunk-2DQ2XREU.js";
|
|
37
37
|
import {
|
|
38
38
|
compareEntityTimestamps
|
|
39
|
-
} from "./chunk-
|
|
39
|
+
} from "./chunk-NQ2WFFPQ.js";
|
|
40
40
|
import {
|
|
41
41
|
normalizeEntityText,
|
|
42
42
|
resolveRequestedEntitySectionKeys
|
|
@@ -877,4 +877,4 @@ export {
|
|
|
877
877
|
entityIndexVersion,
|
|
878
878
|
entityRecentTranscriptLookbackHours
|
|
879
879
|
};
|
|
880
|
-
//# sourceMappingURL=chunk-
|
|
880
|
+
//# sourceMappingURL=chunk-ALNINIUB.js.map
|
|
@@ -3,7 +3,7 @@ import {
|
|
|
3
3
|
} from "./chunk-B7RWBZXW.js";
|
|
4
4
|
import {
|
|
5
5
|
StorageManager
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-NQ2WFFPQ.js";
|
|
7
7
|
import {
|
|
8
8
|
countRecallTokenOverlap,
|
|
9
9
|
normalizeRecallTokens
|
|
@@ -109,4 +109,4 @@ export {
|
|
|
109
109
|
compareVerifiedEpisodeResults,
|
|
110
110
|
searchVerifiedEpisodes
|
|
111
111
|
};
|
|
112
|
-
//# sourceMappingURL=chunk-
|
|
112
|
+
//# sourceMappingURL=chunk-AMPTUYKS.js.map
|
|
@@ -8,11 +8,11 @@ import {
|
|
|
8
8
|
} from "./chunk-5CO5G4MN.js";
|
|
9
9
|
import {
|
|
10
10
|
resolveDefaultNamespaceRoot
|
|
11
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-T266H3RJ.js";
|
|
12
12
|
import {
|
|
13
13
|
StorageManager,
|
|
14
14
|
readRawMemoryDocument
|
|
15
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-NQ2WFFPQ.js";
|
|
16
16
|
import {
|
|
17
17
|
parseContinuityImprovementLoops
|
|
18
18
|
} from "./chunk-LDXUBPMO.js";
|
|
@@ -1869,4 +1869,4 @@ export {
|
|
|
1869
1869
|
defaultTierMigrationCycleBudget,
|
|
1870
1870
|
CompoundingEngine
|
|
1871
1871
|
};
|
|
1872
|
-
//# sourceMappingURL=chunk-
|
|
1872
|
+
//# sourceMappingURL=chunk-CAFF45W4.js.map
|
|
@@ -3,7 +3,7 @@ import {
|
|
|
3
3
|
} from "./chunk-TBBDFYXW.js";
|
|
4
4
|
import {
|
|
5
5
|
StorageManager
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-NQ2WFFPQ.js";
|
|
7
7
|
import {
|
|
8
8
|
requestEntityCanonicalIdReconcile
|
|
9
9
|
} from "./chunk-UUSL22HE.js";
|
|
@@ -769,4 +769,4 @@ export {
|
|
|
769
769
|
listMemoryGovernanceRuns,
|
|
770
770
|
readMemoryGovernanceRunArtifact
|
|
771
771
|
};
|
|
772
|
-
//# sourceMappingURL=chunk-
|
|
772
|
+
//# sourceMappingURL=chunk-DPF7TX3D.js.map
|
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
WHO_KNOWS_DEFAULT_LIMIT,
|
|
3
3
|
WHO_KNOWS_MAX_LIMIT,
|
|
4
4
|
validateWhoKnowsInput
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-6M3VJJON.js";
|
|
6
6
|
|
|
7
7
|
// src/who-knows-cli.ts
|
|
8
8
|
function extractWhoKnowsRawArgs(rest) {
|
|
@@ -74,4 +74,4 @@ export {
|
|
|
74
74
|
renderWhoKnowsText,
|
|
75
75
|
renderWhoKnows
|
|
76
76
|
};
|
|
77
|
-
//# sourceMappingURL=chunk-
|
|
77
|
+
//# sourceMappingURL=chunk-EK3GC76D.js.map
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
NamespaceStorageRouter
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-T266H3RJ.js";
|
|
4
4
|
import {
|
|
5
5
|
namespaceCollectionName
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-272GJCTZ.js";
|
|
7
7
|
import {
|
|
8
8
|
isSafeRouteNamespace
|
|
9
9
|
} from "./chunk-PCXDUHQH.js";
|
|
@@ -213,4 +213,4 @@ export {
|
|
|
213
213
|
verifyNamespaces,
|
|
214
214
|
runNamespaceMigration
|
|
215
215
|
};
|
|
216
|
-
//# sourceMappingURL=chunk-
|
|
216
|
+
//# sourceMappingURL=chunk-EUIWWY2F.js.map
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
readProjectedMemoryPaths
|
|
3
3
|
} from "./chunk-AZEZSQ5R.js";
|
|
4
|
+
import {
|
|
5
|
+
mapInBatches
|
|
6
|
+
} from "./chunk-JA2GJCOS.js";
|
|
4
7
|
import {
|
|
5
8
|
throwIfAborted
|
|
6
9
|
} from "./chunk-R2MBW2S4.js";
|
|
@@ -73,19 +76,18 @@ async function readUnresolvedHarmonicSources(options) {
|
|
|
73
76
|
const cache = safeCache ? await readPathCache(cachePath, rebuiltAt, corpusVersion, nowMs) : /* @__PURE__ */ new Map();
|
|
74
77
|
const found = /* @__PURE__ */ new Map();
|
|
75
78
|
const pending = /* @__PURE__ */ new Set();
|
|
76
|
-
|
|
79
|
+
const probed = await mapInBatches(options.sourceMemoryIds, async (id) => {
|
|
77
80
|
throwIfAborted(abortSignal, "harmonic retrieval aborted");
|
|
78
81
|
const entry = cache.get(id);
|
|
79
|
-
if (entry?.path === null)
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
pending.add(id);
|
|
82
|
+
if (entry?.path === null || !entry?.path) return { id, memory: null, skip: entry?.path === null };
|
|
83
|
+
const candidate = path.resolve(storage.dir, entry.path);
|
|
84
|
+
const memory = isCorpusPath(storage.dir, candidate) ? await readHarmonicSourceMemory(storage, rootReal, candidate, abortSignal) : null;
|
|
85
|
+
return { id, memory: memory?.frontmatter.id === id ? memory : null, skip: false };
|
|
86
|
+
});
|
|
87
|
+
for (const { id, memory, skip } of probed) {
|
|
88
|
+
if (skip) continue;
|
|
89
|
+
if (memory) found.set(id, memory);
|
|
90
|
+
else pending.add(id);
|
|
89
91
|
}
|
|
90
92
|
if (pending.size === 0) return found;
|
|
91
93
|
const inspectProjected = [...pending].some((id) => !isSafeLegacyPathSegment(id));
|
|
@@ -94,10 +96,17 @@ async function readUnresolvedHarmonicSources(options) {
|
|
|
94
96
|
...await storage.collectActiveMemoryPaths({ abortSignal, propagateReadErrors: true }),
|
|
95
97
|
...await storage.collectColdMemoryPaths({ abortSignal, propagateReadErrors: true })
|
|
96
98
|
];
|
|
97
|
-
|
|
99
|
+
const toRead = walked.filter((filePath) => (
|
|
100
|
+
// Existing projected files need no parse unless their filename names a wanted id.
|
|
101
|
+
// New/imported files must be keyed by frontmatter id, not their basename (#3188).
|
|
102
|
+
inspectProjected || pending.has(path.basename(filePath, ".md")) || !projectedPaths?.has(filePath)
|
|
103
|
+
));
|
|
104
|
+
const read = await mapInBatches(toRead, async (filePath) => {
|
|
98
105
|
throwIfAborted(abortSignal, "harmonic retrieval aborted");
|
|
99
|
-
if (!inspectProjected && !pending.has(path.basename(filePath, ".md")) && projectedPaths?.has(filePath)) continue;
|
|
100
106
|
const memory = await readHarmonicSourceMemory(storage, rootReal, filePath, abortSignal);
|
|
107
|
+
return { filePath, memory: memory !== null && pending.has(memory.frontmatter.id) ? memory : null };
|
|
108
|
+
});
|
|
109
|
+
for (const { filePath, memory } of read) {
|
|
101
110
|
if (!memory) continue;
|
|
102
111
|
const id = memory.frontmatter.id;
|
|
103
112
|
if (pending.has(id)) {
|
|
@@ -131,4 +140,4 @@ export {
|
|
|
131
140
|
readHarmonicSourceMemory,
|
|
132
141
|
readUnresolvedHarmonicSources
|
|
133
142
|
};
|
|
134
|
-
//# sourceMappingURL=chunk-
|
|
143
|
+
//# sourceMappingURL=chunk-GXL52YZA.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/harmonic-source-lookup.ts"],"sourcesContent":["import path from \"node:path\";\nimport { existsSync } from \"node:fs\";\nimport { mkdir, realpath } from \"node:fs/promises\";\nimport { throwIfAborted } from \"./abort-error.js\";\nimport { readJsonFile, writeJsonFileAtomic } from \"./json-store.js\";\nimport { mapInBatches } from \"./map-in-batches.js\";\nimport { readProjectedMemoryPaths } from \"./memory-projection-batch.js\";\nimport { SecureStoreLockedError } from \"./secure-store/secure-fs.js\";\nimport { isPathInsideStorageRoot, isSafeLegacyPathSegment } from \"./storage-paths.js\";\nimport { isRecord } from \"./store-contract.js\";\nimport type { StorageManager } from \"./storage.js\";\nimport type { MemoryFile } from \"./types.js\";\nimport { RECALL_FALLBACK_DIRS } from \"./utils/category-dir.js\";\n\nconst LOOKUP_TTL_MS = 10 * 60_000;\nconst MAX_CACHE_ENTRIES = 4096;\ntype PathEntry = { path: string | null; expiresAt: number };\n\n/** Direct and cached probes must retain the walk's realpath containment check. */\nexport async function readHarmonicSourceMemory(\n storage: StorageManager,\n rootReal: string,\n filePath: string,\n abortSignal?: AbortSignal,\n): Promise<MemoryFile | null> {\n throwIfAborted(abortSignal, \"harmonic retrieval aborted\");\n if (!existsSync(filePath)) return null;\n try {\n if (!isPathInsideStorageRoot(rootReal, await realpath(filePath))) return null;\n return await storage.readMemoryByPath(filePath);\n } catch (err) {\n throwIfAborted(abortSignal, \"harmonic retrieval aborted\");\n if (err instanceof SecureStoreLockedError) throw err;\n return null;\n }\n}\n\nfunction isCorpusPath(memoryDir: string, filePath: string): boolean {\n if (!isPathInsideStorageRoot(memoryDir, filePath)) return false;\n const [dir] = path.relative(memoryDir, filePath).split(path.sep);\n return dir === \"cold\" || RECALL_FALLBACK_DIRS.includes(dir);\n}\n\n/** A cache miss is not authoritative: unreadable/invalid cache state keeps the walk. */\nasync function readPathCache(\n filePath: string, rebuiltAt: string, corpusVersion: string, nowMs: number,\n): Promise<Map<string, PathEntry>> {\n try {\n const raw = await readJsonFile(filePath);\n if (!isRecord(raw) || raw.rebuiltAt !== rebuiltAt || raw.corpusVersion !== corpusVersion || !Array.isArray(raw.entries)) return new Map();\n const entries = new Map<string, PathEntry>();\n for (const row of raw.entries) {\n if (!Array.isArray(row) || row.length !== 3) continue;\n const [id, storedPath, expiresAt] = row;\n if (typeof id !== \"string\" || (storedPath !== null && typeof storedPath !== \"string\")) continue;\n if (typeof expiresAt !== \"number\" || !Number.isFinite(expiresAt) || expiresAt <= nowMs || expiresAt > nowMs + LOOKUP_TTL_MS) continue;\n entries.set(id, { path: storedPath, expiresAt });\n }\n return entries;\n } catch {\n return new Map();\n }\n}\n\n/** Resolve only unresolved ids; persist paths/absence, never memory content. */\nexport async function readUnresolvedHarmonicSources(options: {\n storage: StorageManager;\n rootReal: string;\n rebuiltAt: string;\n sourceMemoryIds: string[];\n nowMs: number;\n abortSignal?: AbortSignal;\n}): Promise<Map<string, MemoryFile>> {\n const { storage, rootReal, rebuiltAt, nowMs, abortSignal } = options;\n throwIfAborted(abortSignal, \"harmonic retrieval aborted\");\n const corpusVersion = storage.getCorpusScanVersion();\n const stateDir = path.join(storage.dir, \"state\");\n const cachePath = path.join(stateDir, \"harmonic-source-paths.json\");\n const stateReal = await realpath(stateDir).catch(() => null);\n const safeCache = stateReal !== null && isPathInsideStorageRoot(rootReal, stateReal);\n const cache = safeCache ? await readPathCache(cachePath, rebuiltAt, corpusVersion, nowMs) : new Map<string, PathEntry>();\n const found = new Map<string, MemoryFile>();\n const pending = new Set<string>();\n const probed = await mapInBatches(options.sourceMemoryIds, async (id) => {\n throwIfAborted(abortSignal, \"harmonic retrieval aborted\");\n const entry = cache.get(id);\n if (entry?.path === null || !entry?.path) return { id, memory: null, skip: entry?.path === null };\n const candidate = path.resolve(storage.dir, entry.path);\n const memory = isCorpusPath(storage.dir, candidate)\n ? await readHarmonicSourceMemory(storage, rootReal, candidate, abortSignal) : null;\n return { id, memory: memory?.frontmatter.id === id ? memory : null, skip: false };\n });\n for (const { id, memory, skip } of probed) {\n if (skip) continue;\n if (memory) found.set(id, memory);\n else pending.add(id);\n }\n if (pending.size === 0) return found;\n\n // Opaque legacy ids previously used the full scan, including edited projected files.\n const inspectProjected = [...pending].some((id) => !isSafeLegacyPathSegment(id));\n const projectedPaths = readProjectedMemoryPaths(storage.dir);\n const walked = [\n ...(await storage.collectActiveMemoryPaths({ abortSignal, propagateReadErrors: true })),\n ...(await storage.collectColdMemoryPaths({ abortSignal, propagateReadErrors: true })),\n ];\n const toRead = walked.filter((filePath) =>\n // Existing projected files need no parse unless their filename names a wanted id.\n // New/imported files must be keyed by frontmatter id, not their basename (#3188).\n inspectProjected || pending.has(path.basename(filePath, \".md\")) || !projectedPaths?.has(filePath));\n const read = await mapInBatches(toRead, async (filePath) => {\n throwIfAborted(abortSignal, \"harmonic retrieval aborted\");\n const memory = await readHarmonicSourceMemory(storage, rootReal, filePath, abortSignal);\n // Drop non-matching parses inside the batch so a full-corpus walk does not\n // hold every MemoryFile until the last batch resolves.\n return { filePath, memory: memory !== null && pending.has(memory.frontmatter.id) ? memory : null };\n });\n for (const { filePath, memory } of read) {\n if (!memory) continue;\n const id = memory.frontmatter.id;\n if (pending.has(id)) {\n found.set(id, memory);\n cache.set(id, { path: path.relative(storage.dir, filePath), expiresAt: nowMs + LOOKUP_TTL_MS });\n }\n }\n for (const id of pending) {\n if (!found.has(id)) cache.set(id, { path: null, expiresAt: nowMs + LOOKUP_TTL_MS });\n }\n throwIfAborted(abortSignal, \"harmonic retrieval aborted\");\n // A concurrent mutation must not publish absence for a different corpus epoch.\n if (storage.getCorpusScanVersion() === corpusVersion) {\n try {\n await mkdir(stateDir, { recursive: true });\n if (isPathInsideStorageRoot(rootReal, await realpath(stateDir))) {\n throwIfAborted(abortSignal, \"harmonic retrieval aborted\");\n // ponytail: atomic last-writer-wins cache; contention can repeat a walk, not lose sources.\n await writeJsonFileAtomic(cachePath, {\n rebuiltAt, corpusVersion,\n entries: [...cache].slice(-MAX_CACHE_ENTRIES).map(([id, entry]) => [id, entry.path, entry.expiresAt]),\n });\n }\n } catch {\n throwIfAborted(abortSignal, \"harmonic retrieval aborted\");\n // Cache publication is optional; resolved memories remain usable on a read-only store.\n }\n }\n return found;\n}\n"],"mappings":";;;;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AC;AAAA,EACpF;AACA,iBAAe,aAAa,4BAA4B;AAExD,MAAI,QAAQ,qBAAqB,MAAM,eAAe;AACpD,QAAI;AACF,YAAM,MAAM,UAAU,EAAE,WAAW,KAAK,CAAC;AACzC,UAAI,wBAAwB,UAAU,MAAM,SAAS,QAAQ,CAAC,GAAG;AAC/D,uBAAe,aAAa,4BAA4B;AAExD,cAAM,oBAAoB,WAAW;AAAA,UACnC;AAAA,UAAW;AAAA,UACX,SAAS,CAAC,GAAG,KAAK,EAAE,MAAM,CAAC,iBAAiB,EAAE,IAAI,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC,IAAI,MAAM,MAAM,MAAM,SAAS,CAAC;AAAA,QACtG,CAAC;AAAA,MACH;AAAA,IACF,QAAQ;AACN,qBAAe,aAAa,4BAA4B;AAAA,IAE1D;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
resolveDefaultNamespaceRoot,
|
|
3
3
|
resolveNamespaceStorageRoot
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-T266H3RJ.js";
|
|
5
5
|
import {
|
|
6
6
|
getConfiguredNamespaces
|
|
7
7
|
} from "./chunk-UPWOMMVU.js";
|
|
@@ -2308,4 +2308,4 @@ export {
|
|
|
2308
2308
|
runNamespaceMaintenancePlan,
|
|
2309
2309
|
runNamespaceMaintenanceBatchPlan
|
|
2310
2310
|
};
|
|
2311
|
-
//# sourceMappingURL=chunk-
|
|
2311
|
+
//# sourceMappingURL=chunk-HAEMXLHX.js.map
|