@remnic/core 9.47.1 → 9.48.0
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.d.ts +6 -5
- package/dist/access-admin-ops-surface.js +27 -25
- package/dist/access-audit.js +2 -2
- package/dist/access-authorization-probe.d.ts +6 -5
- package/dist/access-authorization-probe.js +28 -26
- package/dist/access-boundary.d.ts +6 -5
- package/dist/access-boundary.js +27 -25
- package/dist/access-cli.js +87 -85
- package/dist/access-cli.js.map +1 -1
- package/dist/access-extraction-force-flush.d.ts +6 -5
- package/dist/access-extraction-force-flush.js +27 -25
- package/dist/access-http-lcm-compaction.d.ts +6 -5
- package/dist/access-http-lifecycle-flush.d.ts +6 -5
- package/dist/access-http-offline-stream.d.ts +6 -5
- package/dist/access-http-query.js +27 -25
- package/dist/access-http.d.ts +6 -5
- package/dist/access-http.js +36 -34
- package/dist/access-identity-continuity-surface.d.ts +5 -4
- package/dist/access-identity-continuity-surface.js +27 -25
- package/dist/access-lcm-surface.d.ts +6 -5
- package/dist/access-lcm-surface.js +27 -25
- package/dist/access-mcp.d.ts +6 -5
- package/dist/access-mcp.js +32 -30
- package/dist/access-namespace-preflight.js +27 -25
- package/dist/access-observe-write-surface.d.ts +6 -5
- package/dist/access-observe-write-surface.js +27 -25
- package/dist/access-offline-manifest.d.ts +5 -4
- package/dist/access-offline-manifest.js +4 -4
- package/dist/access-operations-batch.js +29 -27
- package/dist/access-operations.d.ts +6 -5
- package/dist/access-operations.js +31 -29
- package/dist/access-recall-concurrency.d.ts +6 -5
- package/dist/access-recall-concurrency.js +27 -25
- package/dist/access-recall-response.d.ts +6 -5
- package/dist/access-recall-response.js +27 -25
- package/dist/access-recall-surface.d.ts +11 -10
- package/dist/access-recall-surface.js +27 -25
- package/dist/access-schema.d.ts +2 -2
- package/dist/{access-service-DNBYHK33.d.ts → access-service-andNjwfD.d.ts} +3 -3
- package/dist/access-service-helpers.d.ts +6 -5
- package/dist/access-service.d.ts +10 -9
- package/dist/access-service.js +27 -25
- package/dist/access-surface-catalog.d.ts +6 -5
- package/dist/access-wearables-meetings-surface.d.ts +3 -2
- package/dist/adapters/index.js +4 -4
- package/dist/adapters/registry.js +2 -2
- package/dist/artifact-search.d.ts +37 -0
- package/dist/artifact-search.js +13 -0
- package/dist/artifact-search.js.map +1 -0
- package/dist/bootstrap.d.ts +5 -4
- package/dist/briefing.d.ts +2 -1
- package/dist/briefing.js +10 -7
- package/dist/buffer.d.ts +2 -1
- package/dist/buffer.js +4 -4
- package/dist/causal-consolidation.js +11 -8
- package/dist/causal-consolidation.js.map +1 -1
- package/dist/{chunk-T6JRMVOV.js → chunk-2EJNXE53.js} +2 -2
- package/dist/{chunk-SIP5DBDN.js → chunk-2P3GQVM2.js} +152 -130
- package/dist/chunk-2P3GQVM2.js.map +1 -0
- package/dist/{chunk-64BHFFKZ.js → chunk-2RPJ4NEE.js} +2 -2
- package/dist/{chunk-JFO5QZ7N.js → chunk-3JUYWPFJ.js} +2 -2
- package/dist/{chunk-L7G72WY4.js → chunk-3NDN5P55.js} +2 -2
- package/dist/{chunk-IXH2U2QT.js → chunk-45OTV7FZ.js} +19 -19
- package/dist/chunk-4O4TKIXQ.js +171 -0
- package/dist/chunk-4O4TKIXQ.js.map +1 -0
- package/dist/{chunk-BDNL34CT.js → chunk-4WBGZYZZ.js} +33 -8
- package/dist/chunk-4WBGZYZZ.js.map +1 -0
- package/dist/{chunk-U6JGQ37L.js → chunk-52I3YZZ6.js} +3 -3
- package/dist/{chunk-IZQ5TDFT.js → chunk-53AJILXF.js} +3 -3
- package/dist/chunk-5AUY5Z5E.js +34 -0
- package/dist/chunk-5AUY5Z5E.js.map +1 -0
- package/dist/{chunk-YWCOJOUI.js → chunk-5L7PTX2Q.js} +2 -2
- package/dist/{chunk-ELIL2A37.js → chunk-7FGL6CGA.js} +5 -5
- package/dist/{chunk-TVVEYCNW.js → chunk-7K5Q6COX.js} +4 -4
- package/dist/{chunk-HXXTXLKA.js → chunk-A2TFK5PG.js} +2 -2
- package/dist/{chunk-LI7OE7G6.js → chunk-ANCC3JJH.js} +2 -2
- package/dist/{chunk-ILBLZ5Y5.js → chunk-D5NGH2EW.js} +2 -2
- package/dist/{chunk-ST5IEK3H.js → chunk-DUEEQCTT.js} +2 -2
- package/dist/{chunk-QISYTKG4.js → chunk-EZNXW27Q.js} +6 -6
- package/dist/{chunk-47J4EDGR.js → chunk-FJ2ND6CZ.js} +2 -2
- package/dist/{chunk-FQU3HTQM.js → chunk-FMCHFSZF.js} +6 -6
- package/dist/{chunk-FULKGK7P.js → chunk-G2RBWVFQ.js} +2 -2
- package/dist/{chunk-W2ZSNIBP.js → chunk-GD7UPIBG.js} +2 -2
- package/dist/{chunk-Z54EM5YZ.js → chunk-GF22HWS2.js} +4 -4
- package/dist/{chunk-ZDAYWJV6.js → chunk-GVX3NAUU.js} +2 -2
- package/dist/{chunk-M2INOSTA.js → chunk-GWHPQOUC.js} +2 -2
- package/dist/{chunk-N5XULCU3.js → chunk-HIDEBEAN.js} +9 -9
- package/dist/{chunk-74HN5QUH.js → chunk-HRMEYQRO.js} +2 -2
- package/dist/{chunk-VFZS2HAA.js → chunk-IP3DHDU2.js} +2 -2
- package/dist/{chunk-RKNJBZ55.js → chunk-JBPKEARU.js} +4 -4
- package/dist/{chunk-PFJXPOD4.js → chunk-JYPO7L3G.js} +2 -2
- package/dist/{chunk-G2L5IZV4.js → chunk-KSGEGHYA.js} +44 -44
- package/dist/{chunk-PKCLQ7KM.js → chunk-LZGCJSQR.js} +5 -5
- package/dist/{chunk-WOC6DXP5.js → chunk-M4DMO67I.js} +4 -4
- package/dist/{chunk-JCNJIXZN.js → chunk-NXUJRXSF.js} +2 -2
- package/dist/{chunk-5VQPZ4GV.js → chunk-PELT6ADC.js} +3 -3
- package/dist/{chunk-IDE5AR5W.js → chunk-PLCZD3LG.js} +28 -66
- package/dist/chunk-PLCZD3LG.js.map +1 -0
- package/dist/{chunk-KMWYZTIE.js → chunk-PRVJH7CY.js} +2 -2
- package/dist/{chunk-RVO6TCTU.js → chunk-QCECHYZL.js} +6 -6
- package/dist/{chunk-KA47C7BF.js → chunk-RSPSHRZA.js} +2 -2
- package/dist/{chunk-E4FOAENZ.js → chunk-S55OAS5P.js} +5 -5
- package/dist/{chunk-BIPBQQFI.js → chunk-UMOO7IY7.js} +2 -2
- package/dist/{chunk-5U7ID3EZ.js → chunk-UTVZKHJK.js} +2 -2
- package/dist/{chunk-V5FE3UAI.js → chunk-WOEVJKKQ.js} +2 -2
- package/dist/{chunk-N3LL5NEU.js → chunk-WQIHRA5F.js} +2 -2
- package/dist/chunk-Z7L72ZHL.js +75 -0
- package/dist/chunk-Z7L72ZHL.js.map +1 -0
- package/dist/{cli-BWXSPxB9.d.ts → cli-p_WmVo2h.d.ts} +3 -3
- package/dist/cli.d.ts +7 -6
- package/dist/cli.js +55 -53
- package/dist/compounding/engine.d.ts +2 -1
- package/dist/compounding/engine.js +10 -7
- package/dist/connectors/codex-materialize-runner.js +10 -7
- package/dist/connectors/index.js +10 -7
- package/dist/consolidation-provenance-check.d.ts +2 -1
- package/dist/consolidation-undo.d.ts +2 -1
- package/dist/contradiction/index.d.ts +7 -6
- package/dist/convergence-refresh.d.ts +2 -1
- package/dist/convergence-refresh.js +12 -9
- package/dist/corpus-watermark.js +15 -13
- package/dist/entity-recall-cancellation.d.ts +36 -0
- package/dist/entity-recall-cancellation.js +19 -0
- package/dist/entity-recall-cancellation.js.map +1 -0
- package/dist/entity-retrieval.d.ts +14 -6
- package/dist/entity-retrieval.js +11 -7
- package/dist/explicit-capture.d.ts +5 -4
- package/dist/external-wiki-access.d.ts +6 -5
- package/dist/external-wiki-access.js +28 -26
- package/dist/external-wiki-mcp-tools.d.ts +6 -5
- package/dist/extraction.js +15 -13
- package/dist/index.d.ts +11 -10
- package/dist/index.js +114 -112
- package/dist/lcm/engine.js +2 -2
- package/dist/lcm/index.js +7 -7
- package/dist/maintenance/memory-governance.js +10 -7
- package/dist/maintenance/rebuild-memory-lifecycle-ledger.d.ts +7 -6
- package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +10 -7
- package/dist/maintenance/rebuild-memory-projection.d.ts +2 -1
- package/dist/maintenance/rebuild-memory-projection.js +11 -8
- package/dist/{maintenance-DQrL93Uu.d.ts → maintenance-BfcuwfJS.d.ts} +1 -1
- package/dist/mcp-memory-inspector-app.d.ts +6 -5
- package/dist/memory-worth-outcomes.d.ts +2 -1
- package/dist/namespaces/migrate.d.ts +2 -1
- package/dist/namespaces/migrate.js +14 -12
- package/dist/namespaces/search.js +4 -4
- package/dist/namespaces/storage.d.ts +7 -6
- package/dist/namespaces/storage.js +10 -7
- package/dist/offline-sync-impression-drain.js +3 -3
- package/dist/operator-doctor-corpus.js +16 -14
- package/dist/operator-toolkit.d.ts +2 -1
- package/dist/operator-toolkit.js +20 -18
- package/dist/orchestration/compression-guideline-coordinator.d.ts +2 -1
- package/dist/orchestration/maintenance.d.ts +3 -2
- package/dist/orchestration/maintenance.js +14 -12
- package/dist/{orchestrator-CRR-6sVB.d.ts → orchestrator-B7nLo4z1.d.ts} +3 -3
- package/dist/orchestrator.d.ts +5 -4
- package/dist/orchestrator.js +89 -87
- package/dist/qmd.js +4 -4
- package/dist/recall-qos.d.ts +109 -2
- package/dist/recall-qos.js +12 -3
- package/dist/search/factory.js +3 -3
- package/dist/search/index.js +3 -3
- package/dist/semantic-consolidation.js +11 -8
- package/dist/semantic-rule-promotion.js +10 -7
- package/dist/semantic-rule-verifier.js +10 -7
- package/dist/{service-DJ0LDyuN.d.ts → service-B5W5IYCx.d.ts} +1 -1
- package/dist/source-agent-qualifier.js +13 -11
- package/dist/{storage-y340tYKb.d.ts → storage-COL907QF.d.ts} +2 -1
- package/dist/storage.d.ts +2 -1
- package/dist/storage.js +9 -6
- package/dist/temporal-supersession.d.ts +2 -1
- package/dist/tier-migration.d.ts +2 -1
- package/dist/verified-recall.js +10 -7
- package/package.json +2 -2
- package/src/artifact-search.test.ts +110 -0
- package/src/artifact-search.ts +115 -0
- package/src/entity-recall-cancellation.ts +58 -0
- package/src/entity-retrieval.ts +58 -4
- package/src/orchestration/namespace-read-fanout.ts +4 -1
- package/src/orchestration/recall-internal-deps.ts +2 -0
- package/src/orchestration/recall-internal.ts +76 -55
- package/src/orchestration/recall-search-pipeline.ts +9 -1
- package/src/orchestration/recall-search-prefilter.ts +18 -1
- package/src/orchestrator.ts +5 -6
- package/src/recall-qos.test.ts +289 -0
- package/src/recall-qos.ts +238 -1
- package/src/storage.ts +12 -56
- package/dist/chunk-BDNL34CT.js.map +0 -1
- package/dist/chunk-C3AKM55W.js +0 -59
- package/dist/chunk-C3AKM55W.js.map +0 -1
- package/dist/chunk-IDE5AR5W.js.map +0 -1
- package/dist/chunk-SIP5DBDN.js.map +0 -1
- /package/dist/{chunk-T6JRMVOV.js.map → chunk-2EJNXE53.js.map} +0 -0
- /package/dist/{chunk-64BHFFKZ.js.map → chunk-2RPJ4NEE.js.map} +0 -0
- /package/dist/{chunk-JFO5QZ7N.js.map → chunk-3JUYWPFJ.js.map} +0 -0
- /package/dist/{chunk-L7G72WY4.js.map → chunk-3NDN5P55.js.map} +0 -0
- /package/dist/{chunk-IXH2U2QT.js.map → chunk-45OTV7FZ.js.map} +0 -0
- /package/dist/{chunk-U6JGQ37L.js.map → chunk-52I3YZZ6.js.map} +0 -0
- /package/dist/{chunk-IZQ5TDFT.js.map → chunk-53AJILXF.js.map} +0 -0
- /package/dist/{chunk-YWCOJOUI.js.map → chunk-5L7PTX2Q.js.map} +0 -0
- /package/dist/{chunk-ELIL2A37.js.map → chunk-7FGL6CGA.js.map} +0 -0
- /package/dist/{chunk-TVVEYCNW.js.map → chunk-7K5Q6COX.js.map} +0 -0
- /package/dist/{chunk-HXXTXLKA.js.map → chunk-A2TFK5PG.js.map} +0 -0
- /package/dist/{chunk-LI7OE7G6.js.map → chunk-ANCC3JJH.js.map} +0 -0
- /package/dist/{chunk-ILBLZ5Y5.js.map → chunk-D5NGH2EW.js.map} +0 -0
- /package/dist/{chunk-ST5IEK3H.js.map → chunk-DUEEQCTT.js.map} +0 -0
- /package/dist/{chunk-QISYTKG4.js.map → chunk-EZNXW27Q.js.map} +0 -0
- /package/dist/{chunk-47J4EDGR.js.map → chunk-FJ2ND6CZ.js.map} +0 -0
- /package/dist/{chunk-FQU3HTQM.js.map → chunk-FMCHFSZF.js.map} +0 -0
- /package/dist/{chunk-FULKGK7P.js.map → chunk-G2RBWVFQ.js.map} +0 -0
- /package/dist/{chunk-W2ZSNIBP.js.map → chunk-GD7UPIBG.js.map} +0 -0
- /package/dist/{chunk-Z54EM5YZ.js.map → chunk-GF22HWS2.js.map} +0 -0
- /package/dist/{chunk-ZDAYWJV6.js.map → chunk-GVX3NAUU.js.map} +0 -0
- /package/dist/{chunk-M2INOSTA.js.map → chunk-GWHPQOUC.js.map} +0 -0
- /package/dist/{chunk-N5XULCU3.js.map → chunk-HIDEBEAN.js.map} +0 -0
- /package/dist/{chunk-74HN5QUH.js.map → chunk-HRMEYQRO.js.map} +0 -0
- /package/dist/{chunk-VFZS2HAA.js.map → chunk-IP3DHDU2.js.map} +0 -0
- /package/dist/{chunk-RKNJBZ55.js.map → chunk-JBPKEARU.js.map} +0 -0
- /package/dist/{chunk-PFJXPOD4.js.map → chunk-JYPO7L3G.js.map} +0 -0
- /package/dist/{chunk-G2L5IZV4.js.map → chunk-KSGEGHYA.js.map} +0 -0
- /package/dist/{chunk-PKCLQ7KM.js.map → chunk-LZGCJSQR.js.map} +0 -0
- /package/dist/{chunk-WOC6DXP5.js.map → chunk-M4DMO67I.js.map} +0 -0
- /package/dist/{chunk-JCNJIXZN.js.map → chunk-NXUJRXSF.js.map} +0 -0
- /package/dist/{chunk-5VQPZ4GV.js.map → chunk-PELT6ADC.js.map} +0 -0
- /package/dist/{chunk-KMWYZTIE.js.map → chunk-PRVJH7CY.js.map} +0 -0
- /package/dist/{chunk-RVO6TCTU.js.map → chunk-QCECHYZL.js.map} +0 -0
- /package/dist/{chunk-KA47C7BF.js.map → chunk-RSPSHRZA.js.map} +0 -0
- /package/dist/{chunk-E4FOAENZ.js.map → chunk-S55OAS5P.js.map} +0 -0
- /package/dist/{chunk-BIPBQQFI.js.map → chunk-UMOO7IY7.js.map} +0 -0
- /package/dist/{chunk-5U7ID3EZ.js.map → chunk-UTVZKHJK.js.map} +0 -0
- /package/dist/{chunk-V5FE3UAI.js.map → chunk-WOEVJKKQ.js.map} +0 -0
- /package/dist/{chunk-N3LL5NEU.js.map → chunk-WQIHRA5F.js.map} +0 -0
package/src/recall-qos.ts
CHANGED
|
@@ -1,7 +1,29 @@
|
|
|
1
|
+
import { abortError, isAbortError } from "./abort-error.js";
|
|
1
2
|
import { log, type LoggerBackend } from "./logger.js";
|
|
2
3
|
|
|
4
|
+
/**
|
|
5
|
+
* Hand the event loop one macrotask.
|
|
6
|
+
*
|
|
7
|
+
* A recall section deadline is a timer, and a timer cannot fire while a
|
|
8
|
+
* synchronous scan holds the loop — so a provider that iterates the whole corpus
|
|
9
|
+
* must call this periodically or its budget is unenforceable (issue #2291).
|
|
10
|
+
* `setImmediate` (check phase) is used rather than a `0ms` timer so the yield
|
|
11
|
+
* cannot be starved by the timer queue it exists to let run.
|
|
12
|
+
*/
|
|
13
|
+
export function yieldToEventLoop(): Promise<void> {
|
|
14
|
+
const { promise, resolve } = Promise.withResolvers<void>();
|
|
15
|
+
setImmediate(resolve);
|
|
16
|
+
return promise;
|
|
17
|
+
}
|
|
18
|
+
|
|
3
19
|
export type RecallSectionPriority = "core" | "enrichment";
|
|
4
|
-
|
|
20
|
+
/**
|
|
21
|
+
* `timeout` records a section that started, exceeded its deadline, and was
|
|
22
|
+
* degraded to its neutral value (issue #2291). It is distinct from `skip`
|
|
23
|
+
* (never ran: disabled or zero-limit) so operators can tell a configuration
|
|
24
|
+
* choice from a budget breach in the section metric log.
|
|
25
|
+
*/
|
|
26
|
+
export type RecallSectionSource = "fresh" | "stale" | "skip" | "timeout";
|
|
5
27
|
|
|
6
28
|
export interface RecallSectionMetric {
|
|
7
29
|
section: string;
|
|
@@ -31,6 +53,9 @@ function defaultTiming(metric: RecallSectionMetric): string {
|
|
|
31
53
|
if (typeof metric.timing === "string" && metric.timing.length > 0) {
|
|
32
54
|
return metric.timing;
|
|
33
55
|
}
|
|
56
|
+
if (metric.source === "timeout") {
|
|
57
|
+
return `timeout(${Math.max(0, Math.round(metric.durationMs))}ms)`;
|
|
58
|
+
}
|
|
34
59
|
if (metric.source === "skip") {
|
|
35
60
|
return "skip";
|
|
36
61
|
}
|
|
@@ -80,3 +105,215 @@ export function createRecallSectionMetricRecorder(options: {
|
|
|
80
105
|
return entry;
|
|
81
106
|
};
|
|
82
107
|
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Fraction of the request's REMAINING budget that a single core section may
|
|
111
|
+
* consume. The remainder is what makes degradation possible at all: time to
|
|
112
|
+
* assemble and return the sections that did arrive before the outer timeout
|
|
113
|
+
* kills the request outright.
|
|
114
|
+
*/
|
|
115
|
+
const CORE_SECTION_MAX_SHARE_OF_REQUEST = 0.8;
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Effective per-section deadline for optional core recall providers.
|
|
119
|
+
*
|
|
120
|
+
* Two things make the configured value unusable as-is (issue #2291):
|
|
121
|
+
*
|
|
122
|
+
* - `recallCoreDeadlineMs` and `recallOuterTimeoutMs` both default to 75s, so a
|
|
123
|
+
* section budget taken at face value can never fire before the request ceiling
|
|
124
|
+
* that cancels everything — the caller loses the whole recall rather than one
|
|
125
|
+
* section.
|
|
126
|
+
* - Sections start *after* planning, namespace resolution, and mode selection.
|
|
127
|
+
* Capping against the original ceiling would let a section that starts 20s in
|
|
128
|
+
* still be running when the request is aborted, which is the same failure.
|
|
129
|
+
*
|
|
130
|
+
* So the cap is taken against `remainingOuterMs` — the request budget left when
|
|
131
|
+
* the section actually starts. An operator who lowers `recallCoreDeadlineMs`
|
|
132
|
+
* below that still gets exactly what they asked for.
|
|
133
|
+
*
|
|
134
|
+
* `remainingOuterMs === null` means the request is unbounded and there is nothing
|
|
135
|
+
* to reserve headroom against. A non-positive remainder means the request is
|
|
136
|
+
* already over budget, so the section degrades immediately rather than starting
|
|
137
|
+
* work that cannot be delivered.
|
|
138
|
+
*/
|
|
139
|
+
export function resolveRecallCoreSectionDeadlineMs(options: {
|
|
140
|
+
configuredCoreDeadlineMs: number;
|
|
141
|
+
remainingOuterMs: number | null;
|
|
142
|
+
}): number {
|
|
143
|
+
const configured = options.configuredCoreDeadlineMs;
|
|
144
|
+
if (!Number.isFinite(configured) || configured <= 0) return configured;
|
|
145
|
+
const remaining = options.remainingOuterMs;
|
|
146
|
+
if (remaining === null || !Number.isFinite(remaining)) return configured;
|
|
147
|
+
if (remaining <= 0) return 1;
|
|
148
|
+
return Math.min(
|
|
149
|
+
configured,
|
|
150
|
+
Math.max(1, Math.floor(remaining * CORE_SECTION_MAX_SHARE_OF_REQUEST)),
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export interface RecallSectionDeadlineOutcome<T> {
|
|
155
|
+
/** The section's value, or `fallback` when the deadline was exceeded. */
|
|
156
|
+
value: T;
|
|
157
|
+
timedOut: boolean;
|
|
158
|
+
durationMs: number;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Run one recall section under a deadline, degrading to `fallback` instead of
|
|
163
|
+
* blocking the phase it belongs to (issue #2291).
|
|
164
|
+
*
|
|
165
|
+
* Before this existed, `deadlineMs` was recorded in the section metric but
|
|
166
|
+
* never enforced for core sections: a provider doing a multi-minute scan on a
|
|
167
|
+
* slow filesystem blocked the whole phase-one `Promise.all`, and kept scanning
|
|
168
|
+
* after the caller aborted. Two guarantees fix that:
|
|
169
|
+
*
|
|
170
|
+
* 1. The returned promise settles within `deadlineMs`, with `timedOut: true`
|
|
171
|
+
* and the caller's neutral value, so one slow optional provider degrades
|
|
172
|
+
* independently rather than holding the response.
|
|
173
|
+
* 2. `run` receives a signal that fires on the deadline AND on the caller's
|
|
174
|
+
* abort, so the section can stop its own work at its next checkpoint.
|
|
175
|
+
*
|
|
176
|
+
* `deadlineMs <= 0` (or non-finite) means unbounded, matching the config
|
|
177
|
+
* contract that a zero budget disables the limit. The section signal is still
|
|
178
|
+
* created and still tracks the parent, so cancellation propagates either way.
|
|
179
|
+
*/
|
|
180
|
+
export async function runRecallSectionWithinDeadline<T>(options: {
|
|
181
|
+
deadlineMs: number;
|
|
182
|
+
fallback: T;
|
|
183
|
+
parentSignal?: AbortSignal;
|
|
184
|
+
run: (sectionSignal: AbortSignal) => Promise<T>;
|
|
185
|
+
now?: () => number;
|
|
186
|
+
}): Promise<RecallSectionDeadlineOutcome<T>> {
|
|
187
|
+
const now = options.now ?? Date.now;
|
|
188
|
+
const startedAtMs = now();
|
|
189
|
+
const controller = new AbortController();
|
|
190
|
+
const parentSignal = options.parentSignal;
|
|
191
|
+
const onParentAbort = () => controller.abort();
|
|
192
|
+
if (parentSignal?.aborted) {
|
|
193
|
+
controller.abort();
|
|
194
|
+
} else if (parentSignal) {
|
|
195
|
+
parentSignal.addEventListener("abort", onParentAbort, { once: true });
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const bounded = Number.isFinite(options.deadlineMs) && options.deadlineMs > 0;
|
|
199
|
+
let timer: NodeJS.Timeout | undefined;
|
|
200
|
+
|
|
201
|
+
try {
|
|
202
|
+
// Wrap in a tagged result rather than racing raw values against a sentinel:
|
|
203
|
+
// T is caller-chosen and must never be mistaken for the timeout marker.
|
|
204
|
+
const work = options.run(controller.signal).then(
|
|
205
|
+
(value) => ({ kind: "value" as const, value }),
|
|
206
|
+
);
|
|
207
|
+
if (!bounded) {
|
|
208
|
+
const settled = await work;
|
|
209
|
+
return { value: settled.value, timedOut: false, durationMs: now() - startedAtMs };
|
|
210
|
+
}
|
|
211
|
+
const deadline = Promise.withResolvers<{ kind: "timeout" }>();
|
|
212
|
+
// Deliberately NOT unref'd: the caller is awaiting this bound, so the timer
|
|
213
|
+
// must keep the loop alive until it fires or `finally` clears it.
|
|
214
|
+
timer = setTimeout(() => deadline.resolve({ kind: "timeout" }), options.deadlineMs);
|
|
215
|
+
const settled = await Promise.race([work, deadline.promise]);
|
|
216
|
+
if (settled.kind === "timeout") {
|
|
217
|
+
controller.abort(abortError("recall section deadline exceeded"));
|
|
218
|
+
// The abandoned work outlives this call; swallow its settlement so a
|
|
219
|
+
// late rejection is not reported as unhandled.
|
|
220
|
+
void work.catch(() => {});
|
|
221
|
+
return { value: options.fallback, timedOut: true, durationMs: now() - startedAtMs };
|
|
222
|
+
}
|
|
223
|
+
return { value: settled.value, timedOut: false, durationMs: now() - startedAtMs };
|
|
224
|
+
} finally {
|
|
225
|
+
clearTimeout(timer);
|
|
226
|
+
parentSignal?.removeEventListener("abort", onParentAbort);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Runs one *optional* core recall section, bounded and accounted for.
|
|
232
|
+
*
|
|
233
|
+
* Binds a section's deadline, the caller's abort signal, and the QoS recorder
|
|
234
|
+
* once so each provider is one call (issue #2291). A breach degrades the
|
|
235
|
+
* section to `fallback`, warns with the section name and budget, and records the
|
|
236
|
+
* section as `timeout` — so a slow provider costs its own section, not the
|
|
237
|
+
* response.
|
|
238
|
+
*
|
|
239
|
+
* The budget is resolved when each section STARTS, against the request budget
|
|
240
|
+
* still left at that moment (`outerDeadlineAtMs`), not against the original
|
|
241
|
+
* configured ceiling: sections begin after planning and namespace resolution, and
|
|
242
|
+
* a section sized to the full request would otherwise still be running when the
|
|
243
|
+
* request itself is aborted.
|
|
244
|
+
*
|
|
245
|
+
* Cancellation degrades too, and must: the section signal fires on the caller's
|
|
246
|
+
* abort, and the phase this section belongs to is awaited through a race that the
|
|
247
|
+
* caller's abort also wins. A rejection here would therefore land on a promise
|
|
248
|
+
* nobody is awaiting any more — an unhandled rejection rather than a signal. The
|
|
249
|
+
* caller learns of its own abort from that race, not from a section result.
|
|
250
|
+
*
|
|
251
|
+
* Only sections whose absence leaves recall coherent belong here: the fallback
|
|
252
|
+
* IS the degraded contract.
|
|
253
|
+
*/
|
|
254
|
+
export function createBoundedCoreSectionRunner(options: {
|
|
255
|
+
configuredDeadlineMs: number;
|
|
256
|
+
/** Absolute time the whole request is aborted, or null when unbounded. */
|
|
257
|
+
outerDeadlineAtMs: number | null;
|
|
258
|
+
parentSignal?: AbortSignal;
|
|
259
|
+
record: (metric: RecallSectionMetric) => unknown;
|
|
260
|
+
logger?: Pick<LoggerBackend, "warn">;
|
|
261
|
+
now?: () => number;
|
|
262
|
+
}): <T>(
|
|
263
|
+
section: string,
|
|
264
|
+
fallback: T,
|
|
265
|
+
run: (sectionSignal: AbortSignal) => Promise<T>,
|
|
266
|
+
) => Promise<T> {
|
|
267
|
+
const logger = options.logger ?? log;
|
|
268
|
+
const now = options.now ?? Date.now;
|
|
269
|
+
return async <T>(
|
|
270
|
+
section: string,
|
|
271
|
+
fallback: T,
|
|
272
|
+
run: (sectionSignal: AbortSignal) => Promise<T>,
|
|
273
|
+
): Promise<T> => {
|
|
274
|
+
const startedAtMs = now();
|
|
275
|
+
const deadlineMs = resolveRecallCoreSectionDeadlineMs({
|
|
276
|
+
configuredCoreDeadlineMs: options.configuredDeadlineMs,
|
|
277
|
+
remainingOuterMs:
|
|
278
|
+
options.outerDeadlineAtMs === null ? null : options.outerDeadlineAtMs - startedAtMs,
|
|
279
|
+
});
|
|
280
|
+
let outcome: RecallSectionDeadlineOutcome<T>;
|
|
281
|
+
try {
|
|
282
|
+
outcome = await runRecallSectionWithinDeadline({
|
|
283
|
+
deadlineMs,
|
|
284
|
+
fallback,
|
|
285
|
+
parentSignal: options.parentSignal,
|
|
286
|
+
run,
|
|
287
|
+
now,
|
|
288
|
+
});
|
|
289
|
+
} catch (err) {
|
|
290
|
+
if (!isAbortError(err)) throw err;
|
|
291
|
+
const durationMs = now() - startedAtMs;
|
|
292
|
+
options.record({
|
|
293
|
+
section,
|
|
294
|
+
priority: "core",
|
|
295
|
+
durationMs,
|
|
296
|
+
deadlineMs,
|
|
297
|
+
source: "skip",
|
|
298
|
+
success: false,
|
|
299
|
+
timing: `cancelled(${durationMs}ms)`,
|
|
300
|
+
});
|
|
301
|
+
return fallback;
|
|
302
|
+
}
|
|
303
|
+
if (outcome.timedOut) {
|
|
304
|
+
logger.warn(
|
|
305
|
+
`recall section [${section}] exceeded its ${deadlineMs}ms core deadline ` +
|
|
306
|
+
`after ${outcome.durationMs}ms; recall continues without it`,
|
|
307
|
+
);
|
|
308
|
+
}
|
|
309
|
+
options.record({
|
|
310
|
+
section,
|
|
311
|
+
priority: "core",
|
|
312
|
+
durationMs: outcome.durationMs,
|
|
313
|
+
deadlineMs,
|
|
314
|
+
source: outcome.timedOut ? "timeout" : "fresh",
|
|
315
|
+
success: !outcome.timedOut,
|
|
316
|
+
});
|
|
317
|
+
return outcome.value;
|
|
318
|
+
};
|
|
319
|
+
}
|
package/src/storage.ts
CHANGED
|
@@ -16,6 +16,7 @@ import {
|
|
|
16
16
|
import { appendFileSync, createReadStream, mkdirSync, readFileSync, statSync, type Dirent } from "node:fs";
|
|
17
17
|
import { createHash, randomUUID } from "node:crypto";
|
|
18
18
|
import { normalizeContent, computeContentHash } from "./content-hash.js";
|
|
19
|
+
import { selectArtifactMatches, type ArtifactSearchOptions } from "./artifact-search.js";
|
|
19
20
|
import path from "node:path";
|
|
20
21
|
import { log } from "./logger.js";
|
|
21
22
|
import { createMemorySnapshot } from "./memory-snapshot.js";
|
|
@@ -235,36 +236,6 @@ import {
|
|
|
235
236
|
// stripCitation import removed: legacy rebuild fallback was replaced by a
|
|
236
237
|
// skip-with-warning strategy (Finding 1 — Uhol). See ensureFactHashIndexAuthoritative.
|
|
237
238
|
|
|
238
|
-
const ARTIFACT_SEARCH_STOPWORDS = new Set([
|
|
239
|
-
"a",
|
|
240
|
-
"an",
|
|
241
|
-
"and",
|
|
242
|
-
"are",
|
|
243
|
-
"as",
|
|
244
|
-
"at",
|
|
245
|
-
"be",
|
|
246
|
-
"but",
|
|
247
|
-
"by",
|
|
248
|
-
"for",
|
|
249
|
-
"from",
|
|
250
|
-
"has",
|
|
251
|
-
"have",
|
|
252
|
-
"i",
|
|
253
|
-
"in",
|
|
254
|
-
"is",
|
|
255
|
-
"it",
|
|
256
|
-
"of",
|
|
257
|
-
"on",
|
|
258
|
-
"or",
|
|
259
|
-
"that",
|
|
260
|
-
"the",
|
|
261
|
-
"this",
|
|
262
|
-
"to",
|
|
263
|
-
"was",
|
|
264
|
-
"were",
|
|
265
|
-
"with",
|
|
266
|
-
]);
|
|
267
|
-
|
|
268
239
|
type SharedVersionKind = "memory-status" | "artifact-write" | "cold-write" | "memory-corpus" | "entity-mutation";
|
|
269
240
|
|
|
270
241
|
type OfflineSyncDigestCacheEntry = {
|
|
@@ -323,15 +294,6 @@ export interface MemoryLifecycleEventWriteOptions {
|
|
|
323
294
|
correlationId?: string;
|
|
324
295
|
}
|
|
325
296
|
|
|
326
|
-
function tokenizeArtifactSearchText(input: string): string[] {
|
|
327
|
-
return input
|
|
328
|
-
.toLowerCase()
|
|
329
|
-
.split(/[^a-z0-9]+/i)
|
|
330
|
-
.map((t) => t.trim())
|
|
331
|
-
.filter((t) => t.length >= 2)
|
|
332
|
-
.filter((t) => !ARTIFACT_SEARCH_STOPWORDS.has(t));
|
|
333
|
-
}
|
|
334
|
-
|
|
335
297
|
/**
|
|
336
298
|
* Validate a Memory Worth counter (`mw_success` / `mw_fail`) before we persist
|
|
337
299
|
* it. Rejects non-finite, non-integer, and negative values rather than silently
|
|
@@ -4389,23 +4351,17 @@ export class StorageManager extends TombstoneBlockedCaptureIndexHost {
|
|
|
4389
4351
|
return this.memoryReadStore.readAllArtifactsCached();
|
|
4390
4352
|
}
|
|
4391
4353
|
|
|
4392
|
-
async searchArtifacts(
|
|
4393
|
-
|
|
4394
|
-
|
|
4395
|
-
|
|
4396
|
-
|
|
4397
|
-
|
|
4398
|
-
|
|
4399
|
-
|
|
4400
|
-
|
|
4401
|
-
|
|
4402
|
-
|
|
4403
|
-
if (score > 0) {
|
|
4404
|
-
hits.push({ score, memory });
|
|
4405
|
-
}
|
|
4406
|
-
}
|
|
4407
|
-
hits.sort((a, b) => b.score - a.score);
|
|
4408
|
-
return hits.slice(0, maxResults).map((h) => h.memory);
|
|
4354
|
+
async searchArtifacts(
|
|
4355
|
+
query: string,
|
|
4356
|
+
maxResults: number,
|
|
4357
|
+
options: ArtifactSearchOptions = {},
|
|
4358
|
+
): Promise<MemoryFile[]> {
|
|
4359
|
+
return selectArtifactMatches(
|
|
4360
|
+
() => this.readAllArtifactsCached(),
|
|
4361
|
+
query,
|
|
4362
|
+
maxResults,
|
|
4363
|
+
options,
|
|
4364
|
+
);
|
|
4409
4365
|
}
|
|
4410
4366
|
|
|
4411
4367
|
async writeEntity(
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/entity-retrieval.ts"],"sourcesContent":["import { resolveNamespaceCapabilities } from \"./capabilities.js\";\nimport { createHash } from \"node:crypto\";\nimport { sanitizeMemoryContent } from \"./sanitize.js\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { collectNativeKnowledgeChunks, type NativeKnowledgeChunk } from \"./native-knowledge.js\";\nimport { compareEntityTimestamps, normalizeEntityName, type StorageManager } from \"./storage.js\";\nimport { normalizeEntityText, resolveRequestedEntitySectionKeys } from \"./entity-schema.js\";\nimport type { EntityStructuredSection, MemoryFile, PluginConfig, TranscriptEntry } from \"./types.js\";\nimport { containsPhrase } from \"./entity-retrieval-boundaries.js\";\n\nconst ENTITY_INDEX_VERSION = 3;\nconst RECENT_TRANSCRIPT_LOOKBACK_HOURS = 24;\nconst INSTRUCTION_LIKE_RE = /\\b(always|never|must|should|remember to|do not|don't|process|workflow|template|checklist|instruction)\\b/i;\nconst METADATA_WRAPPER_RE = /^(source|context|metadata|notes?):/i;\nconst ENTITY_PRONOUN_RE = /\\b(he|him|his|she|her|they|them|their|it|its)\\b/i;\nconst BELIEF_LEDGER_SECTION_KEY = \"belief_ledger\";\nconst BELIEF_LEDGER_FACT_RE = /^claim=([^;]+);\\s*status=([^;]+);\\s*updatedAt=([^;]+);\\s*(.+)$/;\n\ntype EntityQueryMode = \"direct\" | \"timeline\" | \"follow_up\";\n\ntype EntityMentionIndexEntry = {\n canonicalId: string;\n name: string;\n type: string;\n aliases: string[];\n summary?: string;\n facts: string[];\n timelineFacts: string[];\n structuredSections: EntityStructuredSection[];\n timeline: Array<{\n timestamp: string;\n text: string;\n source?: string;\n sessionKey?: string;\n principal?: string;\n }>;\n relationships: Array<{ target: string; label: string }>;\n activity: Array<{ date: string; note: string }>;\n factCount: number;\n memorySnippets: string[];\n nativeChunks: Array<{\n chunkId: string;\n title: string;\n sourceKind: NativeKnowledgeChunk[\"sourceKind\"];\n sourcePath: string;\n snippet: string;\n derivedDate?: string;\n }>;\n};\n\ntype EntityMentionIndex = {\n version: number;\n updatedAt: string;\n entityStatusVersion?: number;\n entities: EntityMentionIndexEntry[];\n};\n\ntype EntityCandidate = {\n entry: EntityMentionIndexEntry;\n alias: string;\n score: number;\n source: \"query\" | \"recent_turn\";\n};\n\ntype EntityHintSnippet = {\n text: string;\n score: number;\n kind: \"summary\" | \"fact\" | \"section\" | \"relationship\" | \"activity\" | \"memory\" | \"native\";\n};\n\nexport interface BuildEntityRecallSectionOptions {\n config: PluginConfig;\n storage: StorageManager;\n namespaceStorage?: (namespace: string) => Promise<StorageManager>;\n query: string;\n recallNamespaces?: string[];\n recentTurns: number;\n maxHints: number;\n maxSupportingFacts: number;\n maxRelatedEntities: number;\n maxChars: number;\n transcriptEntries: TranscriptEntry[];\n}\n\nfunction tokenize(value: string): string[] {\n return normalizeEntityText(value).split(/\\s+/).filter((token) => token.length >= 2);\n}\n\nfunction uniqueStrings(values: string[]): string[] {\n return [...new Set(values.map((value) => value.trim()).filter((value) => value.length > 0))];\n}\n\nfunction compactLine(value: string, maxLength: number = 220): string {\n const normalized = value.replace(/\\s+/g, \" \").trim();\n if (normalized.length <= maxLength) return normalized;\n return `${normalized.slice(0, Math.max(0, maxLength - 1)).trimEnd()}…`;\n}\n\nfunction dedupeHintSnippetsByText(snippets: EntityHintSnippet[]): EntityHintSnippet[] {\n const seen = new Set<string>();\n const result: EntityHintSnippet[] = [];\n for (const snippet of snippets) {\n const key = normalizeEntityText(snippet.text);\n if (seen.has(key)) continue;\n seen.add(key);\n result.push(snippet);\n }\n return result;\n}\n\nfunction isBeliefLedgerSection(section: Pick<EntityStructuredSection, \"key\">): boolean {\n return normalizeEntityText(section.key).replace(/\\s+/g, \"_\") === BELIEF_LEDGER_SECTION_KEY;\n}\n\nfunction beliefLedgerFactKeys(sections: EntityStructuredSection[]): Set<string> {\n const keys = new Set<string>();\n for (const section of sections) {\n if (!isBeliefLedgerSection(section)) continue;\n for (const fact of section.facts) {\n keys.add(normalizeEntityText(fact));\n }\n }\n return keys;\n}\n\nfunction recallFactsForStructuredSection(section: EntityStructuredSection): string[] {\n if (!isBeliefLedgerSection(section)) return section.facts;\n return currentActiveBeliefLedgerFactTexts(section.facts);\n}\n\nfunction currentActiveBeliefLedgerFactTexts(facts: string[]): string[] {\n const byClaim = new Map<string, { status: string; updatedAtMs: number; texts: string[] }>();\n for (const fact of facts) {\n const match = BELIEF_LEDGER_FACT_RE.exec(fact.trim());\n if (!match) continue;\n const [, claimId, status, updatedAt, text] = match;\n const updatedAtMs = Date.parse(updatedAt);\n if (!claimId?.trim() || !status?.trim() || !Number.isFinite(updatedAtMs) || !text?.trim()) continue;\n const normalizedStatus = status.trim().toLowerCase();\n const normalizedClaimId = claimId.trim();\n const current = byClaim.get(normalizedClaimId);\n const inactiveTieWins =\n current &&\n updatedAtMs === current.updatedAtMs &&\n current.status === \"active\" &&\n normalizedStatus !== \"active\";\n if (!current || updatedAtMs > current.updatedAtMs || inactiveTieWins) {\n byClaim.set(normalizedClaimId, { status: normalizedStatus, updatedAtMs, texts: [text.trim()] });\n continue;\n }\n if (updatedAtMs === current.updatedAtMs && current.status === normalizedStatus) {\n current.texts.push(text.trim());\n }\n }\n const result: string[] = [];\n for (const current of byClaim.values()) {\n if (current.status === \"active\") {\n result.push(...current.texts);\n }\n }\n return result;\n}\n\nfunction relationLine(entry: EntityMentionIndexEntry, relationship: { target: string; label: string }): string {\n const normalizedLabel = relationship.label.replace(/\\s+/g, \" \").trim();\n if (normalizedLabel.length === 0) return `${entry.name} is connected to ${relationship.target}`;\n return `${entry.name} ${normalizedLabel} ${relationship.target}`;\n}\n\nfunction detectEntityQueryMode(query: string): EntityQueryMode | null {\n const normalized = normalizeEntityText(query);\n if (!normalized) return null;\n if (\n /^(what about|and what about|how about|what happened (with|to) (he|him|his|she|her|they|them|their|it|its)|did (he|she|they|it)|is (he|she|they|it)|was (he|she|they|it))\\b/.test(normalized)\n ) {\n return \"follow_up\";\n }\n if (\n /^(who is|who s|what do we know about|what does|tell me about|what can you tell me about|what s new with|what happened with|what happened to|status of|where is|how is)\\b/.test(normalized)\n ) {\n if (/^what does\\b/.test(normalized)) {\n if (/^what does (?:this|that|it|the|a|an|my|our|your|their)\\b/.test(normalized)) {\n return null;\n }\n if (\n /^what does [a-z0-9-]+ (?:error|warning|exception|failure|stack|trace|code|message|log)\\b/.test(normalized)\n && /\\b(mean|means|indicate|indicates|imply|implies)\\b/.test(normalized)\n ) {\n return null;\n }\n }\n return /what happened|what s new|status of|how is|where is/.test(normalized) ? \"timeline\" : \"direct\";\n }\n if (ENTITY_PRONOUN_RE.test(normalized) && normalized.split(/\\s+/).length <= 8) {\n return \"follow_up\";\n }\n return null;\n}\n\nfunction scoreAliasMatch(query: string, alias: string): number {\n const normalizedQuery = normalizeEntityText(query);\n const normalizedAlias = normalizeEntityText(alias);\n if (!normalizedAlias) return 0;\n if (normalizedQuery === normalizedAlias) return 10;\n if (containsPhrase(normalizedQuery, normalizedAlias)) return 8 + Math.min(normalizedAlias.split(/\\s+/).length, 3);\n const queryTokens = new Set(tokenize(normalizedQuery));\n const aliasTokens = tokenize(normalizedAlias);\n if (aliasTokens.length === 0) return 0;\n const overlap = aliasTokens.filter((token) => queryTokens.has(token)).length;\n if (overlap === 0) return 0;\n // Cross-entity contamination guard (#682 PR 2/3 R-2). For multi-token\n // aliases, partial-token overlap that hits ONLY shared common tokens\n // (like \"person\" in \"Person-A1\" / \"Person-B1\") would surface every\n // similarly-prefixed entity for a query that named only one. Require\n // that the overlap include at least one DISTINCTIVE alias token —\n // i.e. a token that does not also appear in any other entity's\n // alias-token vocabulary. Since this function is pure / per-pair, we\n // approximate \"distinctive\" by requiring the overlap to include at\n // least one token that is not a substring-of common identifier\n // affixes. The aliasTokens with length > 1 must contribute at least\n // one non-affix overlap. \"Alice Example\" ([\"alice\", \"example\"])\n // matched by query \"Tell me about Alice\" → overlap = 1 on \"alice\",\n // and \"alice\" is not an affix → score = 1. \"Person-A1\" tokens\n // [\"person\", \"a1\"] matched by query \"Who is Person-B1?\" → overlap =\n // 1 on \"person\", and \"person\" IS an affix → score = 0.\n if (aliasTokens.length > 1) {\n const nonAffixOverlap = aliasTokens.filter(\n (token) => queryTokens.has(token) && !isAliasAffixToken(token),\n ).length;\n if (nonAffixOverlap === 0) return 0;\n }\n return overlap;\n}\n\n/**\n * Tokens that look like type prefixes / generic role identifiers and\n * therefore should not, on their own, count as evidence that a\n * multi-token alias matches a query (#682 PR 2/3 R-2).\n *\n * Kept as a small explicit list rather than a regex so additions are\n * deliberate. The list mirrors the entity types listed in\n * `entity-schema.ts` plus the most common generic role identifiers\n * that frequently appear as the leading token of a display name.\n */\nconst ALIAS_AFFIX_TOKENS = new Set<string>([\n \"person\", \"people\", \"user\", \"users\", \"team\", \"teams\",\n \"project\", \"projects\", \"topic\", \"topics\",\n \"org\", \"orgs\", \"organization\", \"organizations\", \"company\", \"companies\",\n \"place\", \"places\", \"tool\", \"tools\", \"service\", \"services\",\n \"system\", \"systems\", \"agent\", \"agents\", \"bot\", \"bots\",\n]);\n\nfunction isAliasAffixToken(token: string): boolean {\n return ALIAS_AFFIX_TOKENS.has(token);\n}\n\nfunction isLikelyInstructionLike(value: string): boolean {\n return INSTRUCTION_LIKE_RE.test(value) || METADATA_WRAPPER_RE.test(value);\n}\n\nfunction sanitizeEntityFact(fact: string): string {\n const sanitized = sanitizeMemoryContent(fact);\n const clean = sanitized.text.trim();\n if (!clean) return \"\";\n if (INSTRUCTION_LIKE_RE.test(clean) && clean.length > 100) return \"\";\n return clean;\n}\n\nfunction scoreHintSnippet(snippet: EntityHintSnippet, queryTokens: string[]): EntityHintSnippet | null {\n const normalized = normalizeEntityText(snippet.text);\n if (!normalized) return null;\n const scored = { ...snippet };\n if (isLikelyInstructionLike(scored.text) && scored.kind !== \"summary\") {\n scored.score -= 3;\n }\n const overlap = queryTokens.filter((token) => normalized.includes(token)).length;\n scored.score += overlap * 2;\n if (METADATA_WRAPPER_RE.test(scored.text)) scored.score -= 2;\n if (scored.text.length <= 160) scored.score += 1;\n return scored.score > 0 ? scored : null;\n}\n\nfunction sortTimelineEntriesDesc(\n left: EntityMentionIndexEntry[\"timeline\"][number],\n right: EntityMentionIndexEntry[\"timeline\"][number],\n): number {\n const timestampOrder = compareEntityTimestamps(right.timestamp, left.timestamp);\n if (timestampOrder !== 0) {\n return timestampOrder;\n }\n return right.text.localeCompare(left.text);\n}\n\nfunction jaccardSimilarity(a: string, b: string): number {\n const aTokens = new Set(tokenize(a));\n const bTokens = new Set(tokenize(b));\n if (aTokens.size === 0 || bTokens.size === 0) return 0;\n let intersection = 0;\n for (const token of aTokens) {\n if (bTokens.has(token)) intersection += 1;\n }\n const union = new Set([...aTokens, ...bTokens]).size;\n return union === 0 ? 0 : intersection / union;\n}\n\nfunction buildAliasIndex(entries: EntityMentionIndexEntry[]): Map<string, EntityMentionIndexEntry[]> {\n const index = new Map<string, EntityMentionIndexEntry[]>();\n for (const entry of entries) {\n const aliases = uniqueStrings([entry.name, ...entry.aliases]).map(normalizeEntityText).filter(Boolean);\n for (const alias of aliases) {\n const existing = index.get(alias) ?? [];\n existing.push(entry);\n index.set(alias, existing);\n }\n }\n return index;\n}\n\nasync function readNativeChunks(\n config: PluginConfig,\n recallNamespaces?: string[],\n): Promise<NativeKnowledgeChunk[]> {\n if (!config.nativeKnowledge?.enabled) return [];\n return collectNativeKnowledgeChunks({\n workspaceDir: config.workspaceDir,\n memoryDir: config.memoryDir,\n config: config.nativeKnowledge,\n recallNamespaces: resolveNamespaceCapabilities(config).namespaces ? recallNamespaces : undefined,\n defaultNamespace: config.defaultNamespace,\n }).catch(() => []);\n}\n\nasync function resolveEntityIndexStorages(\n storage: StorageManager,\n config: PluginConfig,\n recallNamespaces?: string[],\n namespaceStorage?: (namespace: string) => Promise<StorageManager>,\n): Promise<StorageManager[]> {\n if (\n !resolveNamespaceCapabilities(config).namespaces ||\n !namespaceStorage ||\n !recallNamespaces ||\n recallNamespaces.length === 0\n ) {\n return [storage];\n }\n\n const storages: StorageManager[] = [];\n const seenDirs = new Set<string>();\n for (const namespace of uniqueStrings(recallNamespaces)) {\n try {\n const scopedStorage = await namespaceStorage(namespace);\n const storageDir = path.resolve(scopedStorage.dir);\n if (seenDirs.has(storageDir)) continue;\n seenDirs.add(storageDir);\n storages.push(scopedStorage);\n } catch {\n continue;\n }\n }\n\n return storages.length > 0 ? storages : [storage];\n}\n\nfunction entityIndexStatePath(storage: StorageManager): string {\n return path.join(storage.dir, \"state\", \"entity-mention-index.json\");\n}\n\nasync function readEntityIndexState(storage: StorageManager): Promise<EntityMentionIndex | null> {\n const raw = await readFile(entityIndexStatePath(storage), \"utf-8\").catch(() => \"\");\n if (!raw) return null;\n try {\n const parsed = JSON.parse(raw) as Partial<EntityMentionIndex>;\n if (parsed.version !== ENTITY_INDEX_VERSION || !Array.isArray(parsed.entities)) return null;\n return parsed as EntityMentionIndex;\n } catch {\n return null;\n }\n}\n\n\nasync function readCurrentPersistedEntityIndex(\n storage: StorageManager,\n config: PluginConfig,\n recallNamespaces?: string[],\n namespaceStorage?: (namespace: string) => Promise<StorageManager>,\n): Promise<EntityMentionIndex | null> {\n if (\n resolveNamespaceCapabilities(config).namespaces &&\n namespaceStorage &&\n recallNamespaces &&\n recallNamespaces.length > 0\n ) {\n return null;\n }\n const index = await readEntityIndexState(storage);\n if (!index || index.entityStatusVersion !== storage.getMemoryStatusVersion()) {\n return null;\n }\n return index;\n}\nconst namespaceEntityIndexCache = new Map<string, EntityMentionIndex>();\nconst MAX_NAMESPACE_ENTITY_INDEX_CACHE_ENTRIES = 32;\n\nfunction nativeEntityIndexRevision(chunks: NativeKnowledgeChunk[]): string {\n const projection = chunks.map((chunk) => [\n chunk.chunkId,\n chunk.sourcePath,\n chunk.title,\n chunk.sourceKind,\n uniqueStrings(chunk.aliases ?? []),\n compactLine(chunk.content, 180),\n chunk.derivedDate ?? null,\n ]);\n return createHash(\"sha256\").update(JSON.stringify(projection)).digest(\"hex\");\n}\n\nfunction namespaceEntityIndexCacheKey(\n storages: StorageManager[],\n recallNamespaces: string[],\n nativeRevision: string,\n): string {\n const namespaceKey = uniqueStrings(recallNamespaces).join(\"\\u001f\");\n const storageKey = storages\n .map((scopedStorage) => {\n const aliases = Object.entries(scopedStorage.entityAliases)\n .sort(([left], [right]) => left.localeCompare(right));\n return (\n `${path.resolve(scopedStorage.dir)}@${scopedStorage.getMemoryStatusVersion()}` +\n `:${scopedStorage.getMemoryCorpusVersion()}:${scopedStorage.getEntityMutationVersion()}` +\n `:${scopedStorage.hotCacheKeyId()}:${JSON.stringify(aliases)}`\n );\n })\n .join(\"\\u001f\");\n return `${namespaceKey}\\u001e${storageKey}\\u001e${nativeRevision}`;\n}\n\nfunction rememberNamespaceEntityIndex(key: string, index: EntityMentionIndex): void {\n if (namespaceEntityIndexCache.size >= MAX_NAMESPACE_ENTITY_INDEX_CACHE_ENTRIES) {\n const oldestKey = namespaceEntityIndexCache.keys().next().value;\n if (typeof oldestKey === \"string\") namespaceEntityIndexCache.delete(oldestKey);\n }\n namespaceEntityIndexCache.set(key, index);\n}\n\nasync function writeEntityIndexState(storage: StorageManager, index: EntityMentionIndex): Promise<void> {\n const statePath = entityIndexStatePath(storage);\n await mkdir(path.dirname(statePath), { recursive: true });\n const nextContent = JSON.stringify(index, null, 2) + \"\\n\";\n const currentContent = await readFile(statePath, \"utf-8\").catch(() => \"\");\n if (currentContent === nextContent) return;\n await writeFile(statePath, nextContent, \"utf-8\");\n}\n\nfunction nativePseudoCanonicalId(chunk: NativeKnowledgeChunk): string {\n return `native:${createHash(\"sha256\").update(chunk.sourcePath).digest(\"hex\").slice(0, 12)}`;\n}\n\nfunction createPseudoNativeEntry(chunk: NativeKnowledgeChunk): EntityMentionIndexEntry {\n const canonicalId = nativePseudoCanonicalId(chunk);\n return {\n canonicalId,\n name: chunk.title,\n type: chunk.sourceKind,\n aliases: uniqueStrings(chunk.aliases ?? []),\n facts: [],\n structuredSections: [],\n timelineFacts: [],\n timeline: [],\n relationships: [],\n activity: [],\n factCount: 0,\n memorySnippets: [],\n nativeChunks: [\n {\n chunkId: chunk.chunkId,\n title: chunk.title,\n sourceKind: chunk.sourceKind,\n sourcePath: chunk.sourcePath,\n snippet: compactLine(chunk.content, 180),\n derivedDate: chunk.derivedDate,\n },\n ],\n };\n}\n\nfunction mergeNativeChunk(entry: EntityMentionIndexEntry, chunk: NativeKnowledgeChunk): void {\n const existing = entry.nativeChunks.find((item) => item.chunkId === chunk.chunkId);\n if (existing) return;\n entry.nativeChunks.push({\n chunkId: chunk.chunkId,\n title: chunk.title,\n sourceKind: chunk.sourceKind,\n sourcePath: chunk.sourcePath,\n snippet: compactLine(chunk.content, 180),\n derivedDate: chunk.derivedDate,\n });\n entry.aliases = uniqueStrings([...entry.aliases, ...(chunk.aliases ?? [])]);\n}\n\nfunction hasFreshNativeExplicitMention(\n index: EntityMentionIndex,\n nativeChunks: NativeKnowledgeChunk[],\n query: string,\n): boolean {\n if (nativeChunks.length === 0) return false;\n const nativeCanonicalIds = new Set(nativeChunks.map(nativePseudoCanonicalId));\n const freshNativeIndex: EntityMentionIndex = {\n ...index,\n entities: [\n ...index.entities.filter((entry) => !nativeCanonicalIds.has(entry.canonicalId)),\n ...nativeChunks.map(createPseudoNativeEntry),\n ],\n };\n return resolveLanguageIndependentExplicitCandidates(freshNativeIndex, query).length > 0;\n}\n\nasync function buildEntityMentionIndex(\n storage: StorageManager,\n config: PluginConfig,\n recallNamespaces?: string[],\n namespaceStorage?: (namespace: string) => Promise<StorageManager>,\n nativeChunksOverride?: NativeKnowledgeChunk[],\n resolvedStorages?: StorageManager[],\n): Promise<EntityMentionIndex> {\n const storages = resolvedStorages ?? await resolveEntityIndexStorages(\n storage,\n config,\n recallNamespaces,\n namespaceStorage,\n );\n const shouldPersistIndex =\n storages.length === 1 && path.resolve(storages[0]!.dir) === path.resolve(storage.dir);\n const entityStatusVersionBefore = shouldPersistIndex ? storage.getMemoryStatusVersion() : undefined;\n const [previousIndex, entityFileSets, memorySets, nativeChunks] = await Promise.all([\n shouldPersistIndex ? readEntityIndexState(storage) : Promise.resolve(null),\n Promise.all(storages.map((scopedStorage) => scopedStorage.readAllEntityFiles())),\n Promise.all(storages.map((scopedStorage) => scopedStorage.readAllMemories())),\n nativeChunksOverride ? Promise.resolve(nativeChunksOverride) : readNativeChunks(config, recallNamespaces),\n ]);\n // Pair each entity with the storage that owns it (#1534): canonical ids must\n // reflect that store's aliases and historical migration mappings, never another\n // namespace's.\n const entityRecords = entityFileSets.flatMap((set, index) =>\n set.map((entity) => ({ entity, storage: storages[index]! })),\n );\n const memories = memorySets.flat();\n\n const entities = new Map<string, EntityMentionIndexEntry>();\n for (const { entity, storage: entityStorage } of entityRecords) {\n const canonicalId =\n typeof entityStorage.normalizeEntityName === \"function\"\n ? entityStorage.normalizeEntityName(entity.name, entity.type)\n : normalizeEntityName(entity.name, entity.type, entityStorage.entityAliases);\n const rawStructuredSections = entity.structuredSections ?? [];\n const rawBeliefLedgerFactKeys = beliefLedgerFactKeys(rawStructuredSections);\n const sanitizedFacts = entity.facts\n .map((fact) => sanitizeEntityFact(fact))\n .filter(Boolean)\n .filter((fact) => !rawBeliefLedgerFactKeys.has(normalizeEntityText(fact)))\n .map((fact) => compactLine(fact, 180));\n const sanitizedTimelineFacts = entity.timeline\n .map((entry) => sanitizeEntityFact(entry.text))\n .filter(Boolean)\n .map((fact) => compactLine(fact, 180));\n entities.set(canonicalId, {\n canonicalId,\n name: entity.name,\n type: entity.type,\n aliases: uniqueStrings(entity.aliases),\n summary: entity.synthesis?.trim() || entity.summary?.trim() || undefined,\n facts: sanitizedFacts,\n timelineFacts: uniqueStrings(sanitizedTimelineFacts),\n structuredSections: rawStructuredSections.map((section) => ({\n key: section.key,\n title: section.title,\n facts: recallFactsForStructuredSection(section)\n .map((fact) => sanitizeEntityFact(fact))\n .filter(Boolean)\n .map((fact) => compactLine(fact, 180)),\n })).filter((section) => section.facts.length > 0),\n timeline: entity.timeline.map((entry) => ({ ...entry })),\n relationships: entity.relationships.map((relationship) => ({ ...relationship })),\n activity: entity.activity.map((activity) => ({ ...activity })),\n factCount: sanitizedFacts.length,\n memorySnippets: [],\n nativeChunks: [],\n });\n }\n\n for (const memory of memories) {\n const entityRef = typeof memory.frontmatter.entityRef === \"string\" ? memory.frontmatter.entityRef : \"\";\n if (!entityRef) continue;\n const entry = entities.get(entityRef);\n if (!entry) continue;\n const snippet = await readMemorySnippet(memory);\n if (!entry.memorySnippets.includes(snippet)) {\n entry.memorySnippets.push(snippet);\n }\n }\n\n const aliasIndex = buildAliasIndex([...entities.values()]);\n for (const chunk of nativeChunks) {\n const existingPseudo = entities.get(nativePseudoCanonicalId(chunk));\n if (existingPseudo) {\n mergeNativeChunk(existingPseudo, chunk);\n continue;\n }\n const candidateAliases = uniqueStrings([chunk.title, ...(chunk.aliases ?? [])]).map(normalizeEntityText).filter(Boolean);\n let matched = false;\n for (const alias of candidateAliases) {\n for (const entry of aliasIndex.get(alias) ?? []) {\n mergeNativeChunk(entry, chunk);\n matched = true;\n }\n }\n if (matched) continue;\n const pseudoEntry = createPseudoNativeEntry(chunk);\n entities.set(pseudoEntry.canonicalId, pseudoEntry);\n }\n\n const sortedEntities = [...entities.values()].sort((left, right) => left.name.localeCompare(right.name));\n const previousEntities = previousIndex ? JSON.stringify(previousIndex.entities) : \"\";\n const nextEntities = JSON.stringify(sortedEntities);\n const entityStatusVersionAfter = shouldPersistIndex ? storage.getMemoryStatusVersion() : undefined;\n const canPersistIndex = shouldPersistIndex && entityStatusVersionBefore === entityStatusVersionAfter;\n const index: EntityMentionIndex = {\n version: ENTITY_INDEX_VERSION,\n updatedAt:\n previousIndex && previousEntities === nextEntities\n ? previousIndex.updatedAt\n : new Date().toISOString(),\n entityStatusVersion: canPersistIndex ? entityStatusVersionAfter : undefined,\n entities: sortedEntities,\n };\n if (canPersistIndex) {\n await writeEntityIndexState(storage, index);\n }\n return index;\n}\n\nfunction resolveExplicitCandidates(\n index: EntityMentionIndex,\n query: string,\n): EntityCandidate[] {\n const candidates: EntityCandidate[] = [];\n for (const entry of index.entities) {\n const aliases = uniqueStrings([entry.name, ...entry.aliases]);\n let bestAlias = \"\";\n let bestScore = 0;\n for (const alias of aliases) {\n const score = scoreAliasMatch(query, alias);\n if (score > bestScore) {\n bestAlias = alias;\n bestScore = score;\n }\n }\n if (bestScore <= 0) continue;\n candidates.push({ entry, alias: bestAlias, score: bestScore, source: \"query\" });\n }\n return candidates.sort((left, right) => right.score - left.score);\n}\n\nconst EXPLICIT_ENTITY_MENTION_SCORE = 9;\n\nconst IMPLICIT_ENTITY_STOP_WORDS = new Set([\n \"a\",\n \"an\",\n \"and\",\n \"are\",\n \"as\",\n \"at\",\n \"be\",\n \"by\",\n \"can\",\n \"do\",\n \"for\",\n \"from\",\n \"has\",\n \"how\",\n \"i\",\n \"if\",\n \"in\",\n \"is\",\n \"it\",\n \"me\",\n \"my\",\n \"of\",\n \"on\",\n \"or\",\n \"the\",\n \"to\",\n \"was\",\n \"what\",\n \"when\",\n \"where\",\n \"who\",\n \"why\",\n \"with\",\n \"you\",\n \"your\",\n]);\n\nfunction isDistinctiveImplicitAlias(normalizedAlias: string): boolean {\n const tokens = normalizedAlias.split(/\\s+/).filter(Boolean);\n if (tokens.length > 1 && tokens.every((token) => IMPLICIT_ENTITY_STOP_WORDS.has(token))) return false;\n if (tokens.length !== 1) return true;\n const token = tokens[0]!;\n return Array.from(token).length > 1 && !IMPLICIT_ENTITY_STOP_WORDS.has(token);\n}\n\nfunction isShortLatinAlias(alias: string): boolean {\n return /^[A-Za-z]{2,3}$/.test(alias.trim());\n}\n\nfunction hasStrongShortLatinAliasMention(query: string, alias: string): boolean {\n const normalizedAlias = alias.trim();\n const titleCaseAlias = `${normalizedAlias[0]!.toUpperCase()}${normalizedAlias.slice(1).toLowerCase()}`;\n const forms = new Set([normalizedAlias, normalizedAlias.toUpperCase(), titleCaseAlias]);\n return [...forms].some((form) => {\n if (form === form.toLowerCase()) return false;\n const escaped = form.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n return new RegExp(`(?:^|[^A-Za-z0-9])${escaped}(?:$|[^A-Za-z0-9])`).test(query);\n });\n}\n\nfunction resolveLanguageIndependentExplicitCandidates(\n index: EntityMentionIndex,\n query: string,\n): EntityCandidate[] {\n const canonicalIdsByAlias = new Map<string, Set<string>>();\n for (const entry of index.entities) {\n for (const alias of uniqueStrings([entry.name, ...entry.aliases])) {\n const normalizedAlias = normalizeEntityText(alias);\n if (!normalizedAlias) continue;\n const canonicalIds = canonicalIdsByAlias.get(normalizedAlias) ?? new Set<string>();\n canonicalIds.add(entry.canonicalId);\n canonicalIdsByAlias.set(normalizedAlias, canonicalIds);\n }\n }\n\n const candidates: EntityCandidate[] = [];\n for (const entry of index.entities) {\n let bestAlias = \"\";\n let bestScore = 0;\n for (const alias of uniqueStrings([entry.name, ...entry.aliases])) {\n const normalizedAlias = normalizeEntityText(alias);\n const score = scoreAliasMatch(query, alias);\n if (\n !normalizedAlias ||\n !isDistinctiveImplicitAlias(normalizedAlias) ||\n (isShortLatinAlias(alias) && !hasStrongShortLatinAliasMention(query, alias)) ||\n canonicalIdsByAlias.get(normalizedAlias)?.size !== 1 ||\n score < EXPLICIT_ENTITY_MENTION_SCORE ||\n score <= bestScore\n ) {\n continue;\n }\n bestAlias = alias;\n bestScore = score;\n }\n if (bestAlias) {\n candidates.push({ entry, alias: bestAlias, score: bestScore, source: \"query\" });\n }\n }\n\n return candidates.sort(\n (left, right) => right.score - left.score || left.entry.name.localeCompare(right.entry.name),\n );\n}\n\nfunction resolveRecentTurnCandidates(\n index: EntityMentionIndex,\n transcriptEntries: TranscriptEntry[],\n recentTurns: number,\n): EntityCandidate[] {\n if (recentTurns <= 0 || transcriptEntries.length === 0) return [];\n const recentEntries = transcriptEntries.slice(-recentTurns);\n const candidates = new Map<string, EntityCandidate>();\n for (let indexOffset = recentEntries.length - 1; indexOffset >= 0; indexOffset -= 1) {\n const turn = recentEntries[indexOffset];\n const recencyBoost = recentEntries.length - indexOffset;\n const roleWeight = turn.role === \"user\" ? 2 : turn.role === \"assistant\" ? -1 : 0;\n for (const entry of index.entities) {\n const aliases = uniqueStrings([entry.name, ...entry.aliases]);\n for (const alias of aliases) {\n const score = scoreAliasMatch(turn.content, alias);\n if (score <= 0) continue;\n const current = candidates.get(entry.canonicalId);\n const weightedScore = score + Math.max(0, 6 - recencyBoost) + roleWeight;\n if (!current || weightedScore > current.score) {\n candidates.set(entry.canonicalId, {\n entry,\n alias,\n score: weightedScore,\n source: \"recent_turn\",\n });\n }\n }\n }\n }\n return [...candidates.values()].sort((left, right) => right.score - left.score);\n}\n\nasync function readMemorySnippet(memory: MemoryFile): Promise<string> {\n const content = memory.content.replace(/\\s+/g, \" \").trim();\n return compactLine(content, 180);\n}\n\nasync function buildHintSnippets(\n entry: EntityMentionIndexEntry,\n queryTokens: string[],\n mode: EntityQueryMode,\n maxSupportingFacts: number,\n requestedSectionKeys: Set<string>,\n): Promise<EntityHintSnippet[]> {\n const snippets: EntityHintSnippet[] = [];\n const aliasTokens = new Set(tokenize(uniqueStrings([entry.name, ...entry.aliases]).join(\" \")));\n if (entry.summary) {\n snippets.push({ text: compactLine(entry.summary, 180), score: 10, kind: \"summary\" });\n }\n\n if (requestedSectionKeys.size > 0) {\n for (const section of entry.structuredSections) {\n if (!requestedSectionKeys.has(normalizeEntityText(section.key).replace(/\\s+/g, \"_\"))) continue;\n for (const fact of section.facts) {\n snippets.push({ text: fact, score: mode === \"direct\" ? 8 : 9, kind: \"section\" });\n }\n }\n } else {\n for (const fact of entry.timelineFacts) {\n snippets.push({ text: fact, score: mode === \"direct\" ? 6 : 7, kind: \"fact\" });\n }\n for (const section of entry.structuredSections) {\n for (const fact of section.facts) {\n const normalizedFact = normalizeEntityText(fact);\n const hasNonAliasQueryOverlap = queryTokens.some((token) =>\n !aliasTokens.has(token) && normalizedFact.includes(token)\n );\n if (entry.timelineFacts.length > 0 && !hasNonAliasQueryOverlap) {\n continue;\n }\n snippets.push({ text: fact, score: mode === \"direct\" ? 6 : 7, kind: \"fact\" });\n }\n }\n if (entry.timelineFacts.length === 0 && entry.structuredSections.length === 0) {\n for (const fact of entry.facts) {\n if (!fact.trim()) continue;\n snippets.push({ text: fact, score: mode === \"direct\" ? 6 : 7, kind: \"fact\" });\n }\n }\n }\n\n if (requestedSectionKeys.size === 0) {\n for (const relationship of entry.relationships) {\n snippets.push({\n text: compactLine(relationLine(entry, relationship), 180),\n score: mode === \"direct\" && entry.type.toLowerCase() === \"person\" ? 6 : 4,\n kind: \"relationship\",\n });\n }\n\n for (const activity of entry.activity) {\n snippets.push({\n text: compactLine(`${activity.date}: ${activity.note}`, 180),\n score: 4,\n kind: \"activity\",\n });\n }\n\n for (const memorySnippet of entry.memorySnippets.slice(0, Math.min(maxSupportingFacts, 4))) {\n snippets.push({\n text: memorySnippet,\n score: 5,\n kind: \"memory\",\n });\n }\n\n for (const chunk of entry.nativeChunks) {\n snippets.push({\n text: compactLine(chunk.snippet, 180),\n score: 3,\n kind: \"native\",\n });\n }\n }\n\n const deduped = new Map<string, EntityHintSnippet>();\n for (const snippet of snippets) {\n const scored = scoreHintSnippet(snippet, queryTokens);\n if (!scored) continue;\n const normalized = normalizeEntityText(scored.text);\n const existing = deduped.get(normalized);\n if (!existing || scored.score > existing.score) deduped.set(normalized, scored);\n }\n\n return [...deduped.values()]\n .filter((snippet) => snippet.score > 0)\n .sort((left, right) => right.score - left.score)\n .slice(0, maxSupportingFacts);\n}\n\nfunction summarizeUncertainty(snippets: EntityHintSnippet[]): string | null {\n const direct = snippets.filter((snippet) =>\n snippet.kind === \"summary\"\n || snippet.kind === \"fact\"\n || snippet.kind === \"section\"\n || snippet.kind === \"memory\"\n );\n if (direct.length < 2) return null;\n for (let index = 0; index < direct.length; index += 1) {\n for (let compare = index + 1; compare < direct.length; compare += 1) {\n if (jaccardSimilarity(direct[index].text, direct[compare].text) < 0.2) {\n return \"Evidence is mixed across stored facts; treat the hints below as partial and verify before answering definitively.\";\n }\n }\n }\n return null;\n}\n\nfunction formatEntityHintSection(\n candidates: Array<{\n candidate: EntityCandidate;\n snippets: EntityHintSnippet[];\n uncertainty: string | null;\n }>,\n queryTokens: string[],\n mode: EntityQueryMode,\n maxRelatedEntities: number,\n maxChars: number,\n): string | null {\n if (candidates.length === 0) return null;\n const lines: string[] = [\"## entity_answer_hints\", \"\"];\n for (const { candidate, snippets, uncertainty } of candidates) {\n const hasSummary = Boolean(candidate.entry.summary?.trim());\n const preferredTopSnippets = hasSummary\n ? snippets.filter((snippet) => snippet.kind !== \"fact\")\n : snippets;\n let topSnippets = (\n preferredTopSnippets.length > 0 ? preferredTopSnippets : snippets\n ).slice(0, 3);\n const buildTimelineSnippets = (seedExcludedTexts: Set<string>): EntityHintSnippet[] => {\n const explicitTimelinePool = dedupeHintSnippetsByText(\n (candidate.entry.timeline ?? [])\n .slice()\n .sort(sortTimelineEntriesDesc)\n .map((entry) => sanitizeEntityFact(entry.text))\n .filter(Boolean)\n .map((text) => scoreHintSnippet({\n text: compactLine(text, 180),\n score: 7,\n kind: \"activity\" as const,\n }, queryTokens))\n .filter((snippet): snippet is EntityHintSnippet => snippet !== null)\n .filter((snippet) => !seedExcludedTexts.has(normalizeEntityText(snippet.text))),\n ).slice(0, 2);\n const activityTimelinePool = dedupeHintSnippetsByText(\n snippets\n .filter((snippet) => (\n snippet.kind === \"activity\" || snippet.kind === \"memory\"\n ) && !seedExcludedTexts.has(normalizeEntityText(snippet.text))),\n ).slice(0, 2);\n return explicitTimelinePool.length > 0\n ? explicitTimelinePool\n : activityTimelinePool.length > 0\n ? activityTimelinePool\n : dedupeHintSnippetsByText(\n snippets\n .filter((snippet) => (\n snippet.kind === \"fact\" || snippet.kind === \"summary\"\n ) && !seedExcludedTexts.has(normalizeEntityText(snippet.text))),\n ).slice(0, 2);\n };\n const baseTopSnippetTexts = new Set(topSnippets.map((snippet) => normalizeEntityText(snippet.text)));\n const timelinePool = mode !== \"direct\" ? buildTimelineSnippets(baseTopSnippetTexts) : [];\n if (mode !== \"direct\" && hasSummary && topSnippets.length < 2) {\n if (timelinePool.length > 0) {\n topSnippets = [...topSnippets, timelinePool[0]!].slice(0, 3);\n }\n }\n const topSnippetTexts = new Set(topSnippets.map((snippet) => normalizeEntityText(snippet.text)));\n lines.push(`- target: ${candidate.entry.name} (${candidate.entry.type})`);\n if (candidate.source === \"recent_turn\") {\n lines.push(`- resolution: carried forward from recent turns via alias \"${candidate.alias}\"`);\n } else {\n lines.push(`- resolution: matched alias \"${candidate.alias}\" in the query`);\n }\n if (uncertainty) lines.push(`- uncertainty: ${uncertainty}`);\n if (topSnippets.length > 0) {\n lines.push(\"- likely answer:\");\n for (const snippet of topSnippets) {\n lines.push(` - ${snippet.text}`);\n }\n }\n if (mode !== \"direct\") {\n const fallbackTimeline = timelinePool.filter(\n (snippet) => !topSnippetTexts.has(normalizeEntityText(snippet.text)),\n );\n if (fallbackTimeline.length > 0) {\n lines.push(\"- recent timeline:\");\n for (const snippet of fallbackTimeline) {\n lines.push(` - ${snippet.text}`);\n }\n }\n }\n const related = candidate.entry.relationships.slice(0, maxRelatedEntities).map((relationship) => relationship.target);\n if (related.length > 0) {\n lines.push(`- related entities: ${related.join(\", \")}`);\n }\n lines.push(`- support counts: facts=${candidate.entry.factCount}, memories=${candidate.entry.memorySnippets.length}, native=${candidate.entry.nativeChunks.length}`);\n lines.push(\"\");\n }\n\n let result = lines.join(\"\\n\");\n if (result.length > maxChars) {\n result = `${result.slice(0, Math.max(0, maxChars - 15)).trimEnd()}\\n\\n...(trimmed)\\n`;\n }\n return result.trim().length > 0 ? result.trimEnd() : null;\n}\n\nexport async function buildEntityRecallSection(options: BuildEntityRecallSectionOptions): Promise<string | null> {\n const prefixedMode = detectEntityQueryMode(options.query);\n const persistedIndex = prefixedMode\n ? null\n : await readCurrentPersistedEntityIndex(\n options.storage,\n options.config,\n options.recallNamespaces,\n options.namespaceStorage,\n );\n let nativeChunks: NativeKnowledgeChunk[] | undefined;\n if (\n !prefixedMode &&\n persistedIndex &&\n resolveLanguageIndependentExplicitCandidates(persistedIndex, options.query).length === 0\n ) {\n nativeChunks = await readNativeChunks(options.config, options.recallNamespaces);\n if (!hasFreshNativeExplicitMention(persistedIndex, nativeChunks, options.query)) {\n return null;\n }\n }\n const namespaceScoped =\n resolveNamespaceCapabilities(options.config).namespaces &&\n options.namespaceStorage !== undefined &&\n (options.recallNamespaces?.length ?? 0) > 0;\n if (namespaceScoped) {\n nativeChunks = await readNativeChunks(options.config, options.recallNamespaces);\n }\n const resolvedStorages = namespaceScoped\n ? await resolveEntityIndexStorages(\n options.storage,\n options.config,\n options.recallNamespaces,\n options.namespaceStorage,\n )\n : undefined;\n const namespaceCacheKey =\n resolvedStorages && options.recallNamespaces && nativeChunks\n ? namespaceEntityIndexCacheKey(\n resolvedStorages,\n options.recallNamespaces,\n nativeEntityIndexRevision(nativeChunks),\n )\n : undefined;\n let index: EntityMentionIndex | undefined = namespaceCacheKey\n ? namespaceEntityIndexCache.get(namespaceCacheKey)\n : undefined;\n if (!index) {\n index = await buildEntityMentionIndex(\n options.storage,\n options.config,\n options.recallNamespaces,\n options.namespaceStorage,\n nativeChunks,\n resolvedStorages,\n );\n if (namespaceCacheKey) rememberNamespaceEntityIndex(namespaceCacheKey, index);\n }\n const explicitCandidates = resolveExplicitCandidates(index, options.query);\n const queryCandidates = prefixedMode\n ? explicitCandidates\n : resolveLanguageIndependentExplicitCandidates(index, options.query);\n const mode = prefixedMode ?? (queryCandidates.length > 0 ? \"direct\" : null);\n if (!mode) return null;\n\n const candidates = queryCandidates.length > 0\n ? queryCandidates\n : resolveRecentTurnCandidates(index, options.transcriptEntries, options.recentTurns);\n\n if (candidates.length === 0) return null;\n\n const queryTokens = tokenize(options.query);\n const candidateLimit = queryCandidates.length === 0 && mode === \"follow_up\"\n ? 1\n : options.maxHints;\n const rankedCandidates = candidates.slice(0, candidateLimit);\n const enriched = await Promise.all(\n rankedCandidates.map(async (candidate) => {\n const requestedSectionKeys = new Set(\n resolveRequestedEntitySectionKeys(\n options.query,\n candidate.entry.type,\n candidate.entry.structuredSections,\n options.config.entitySchemas,\n ),\n );\n const snippets = await buildHintSnippets(\n candidate.entry,\n queryTokens,\n mode,\n options.maxSupportingFacts,\n requestedSectionKeys,\n );\n return {\n candidate,\n snippets,\n uncertainty: summarizeUncertainty(snippets),\n };\n }),\n );\n\n const section = formatEntityHintSection(enriched, queryTokens, mode, options.maxRelatedEntities, options.maxChars);\n if (!section) return null;\n return section;\n}\n\nexport async function readRecentEntityTranscriptEntries(\n transcriptEntriesPromise: Promise<TranscriptEntry[]>,\n recentTurns: number,\n): Promise<TranscriptEntry[]> {\n if (recentTurns <= 0) return [];\n const transcriptEntries = await transcriptEntriesPromise.catch(() => []);\n if (transcriptEntries.length === 0) return [];\n return transcriptEntries.slice(-Math.max(1, recentTurns * 2));\n}\n\nexport const entityIndexVersion = ENTITY_INDEX_VERSION;\nexport const entityRecentTranscriptLookbackHours = RECENT_TRANSCRIPT_LOOKBACK_HOURS;\n"],"mappings":";;;;;;;;;;;;;;;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sCAAsC;","names":["index","token"]}
|
package/dist/chunk-C3AKM55W.js
DELETED
|
@@ -1,59 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
log
|
|
3
|
-
} from "./chunk-3WCASNQZ.js";
|
|
4
|
-
|
|
5
|
-
// src/recall-qos.ts
|
|
6
|
-
function defaultTiming(metric) {
|
|
7
|
-
if (typeof metric.timing === "string" && metric.timing.length > 0) {
|
|
8
|
-
return metric.timing;
|
|
9
|
-
}
|
|
10
|
-
if (metric.source === "skip") {
|
|
11
|
-
return "skip";
|
|
12
|
-
}
|
|
13
|
-
return `${Math.max(0, Math.round(metric.durationMs))}ms`;
|
|
14
|
-
}
|
|
15
|
-
function formatRecallSectionMetric(metric) {
|
|
16
|
-
const payload = {
|
|
17
|
-
section: metric.section,
|
|
18
|
-
priority: metric.priority,
|
|
19
|
-
durationMs: metric.durationMs,
|
|
20
|
-
deadlineMs: metric.deadlineMs,
|
|
21
|
-
source: metric.source,
|
|
22
|
-
success: metric.success
|
|
23
|
-
};
|
|
24
|
-
return {
|
|
25
|
-
message: "recall section metric",
|
|
26
|
-
payload,
|
|
27
|
-
level: metric.priority === "core" && metric.success && metric.source !== "skip" ? "info" : "debug",
|
|
28
|
-
timing: defaultTiming(metric)
|
|
29
|
-
};
|
|
30
|
-
}
|
|
31
|
-
function createRecallSectionMetricRecorder(options = {}) {
|
|
32
|
-
const logger = options.logger ?? log;
|
|
33
|
-
return (metric) => {
|
|
34
|
-
const entry = formatRecallSectionMetric(metric);
|
|
35
|
-
if (options.timings) {
|
|
36
|
-
options.timings[metric.section] = entry.timing;
|
|
37
|
-
}
|
|
38
|
-
if (entry.level === "info") {
|
|
39
|
-
if (typeof logger.info === "function") {
|
|
40
|
-
logger.info(entry.message, entry.payload);
|
|
41
|
-
} else {
|
|
42
|
-
log.info(entry.message, entry.payload);
|
|
43
|
-
}
|
|
44
|
-
} else {
|
|
45
|
-
if (typeof logger.debug === "function") {
|
|
46
|
-
logger.debug(entry.message, entry.payload);
|
|
47
|
-
} else {
|
|
48
|
-
log.debug(entry.message, entry.payload);
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
return entry;
|
|
52
|
-
};
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
export {
|
|
56
|
-
formatRecallSectionMetric,
|
|
57
|
-
createRecallSectionMetricRecorder
|
|
58
|
-
};
|
|
59
|
-
//# sourceMappingURL=chunk-C3AKM55W.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/recall-qos.ts"],"sourcesContent":["import { log, type LoggerBackend } from \"./logger.js\";\n\nexport type RecallSectionPriority = \"core\" | \"enrichment\";\nexport type RecallSectionSource = \"fresh\" | \"stale\" | \"skip\";\n\nexport interface RecallSectionMetric {\n section: string;\n priority: RecallSectionPriority;\n durationMs: number;\n deadlineMs: number;\n source: RecallSectionSource;\n success: boolean;\n timing?: string;\n}\n\nexport interface RecallSectionMetricLog {\n message: string;\n payload: {\n section: string;\n priority: RecallSectionPriority;\n durationMs: number;\n deadlineMs: number;\n source: RecallSectionSource;\n success: boolean;\n };\n level: \"info\" | \"debug\";\n timing: string;\n}\n\nfunction defaultTiming(metric: RecallSectionMetric): string {\n if (typeof metric.timing === \"string\" && metric.timing.length > 0) {\n return metric.timing;\n }\n if (metric.source === \"skip\") {\n return \"skip\";\n }\n return `${Math.max(0, Math.round(metric.durationMs))}ms`;\n}\n\nexport function formatRecallSectionMetric(metric: RecallSectionMetric): RecallSectionMetricLog {\n const payload = {\n section: metric.section,\n priority: metric.priority,\n durationMs: metric.durationMs,\n deadlineMs: metric.deadlineMs,\n source: metric.source,\n success: metric.success,\n };\n return {\n message: \"recall section metric\",\n payload,\n level: metric.priority === \"core\" && metric.success && metric.source !== \"skip\" ? \"info\" : \"debug\",\n timing: defaultTiming(metric),\n };\n}\n\nexport function createRecallSectionMetricRecorder(options: {\n timings?: Record<string, string>;\n logger?: Pick<LoggerBackend, \"info\" | \"debug\">;\n} = {}) {\n const logger = options.logger ?? log;\n return (metric: RecallSectionMetric): RecallSectionMetricLog => {\n const entry = formatRecallSectionMetric(metric);\n if (options.timings) {\n options.timings[metric.section] = entry.timing;\n }\n if (entry.level === \"info\") {\n if (typeof logger.info === \"function\") {\n logger.info(entry.message, entry.payload);\n } else {\n log.info(entry.message, entry.payload);\n }\n } else {\n if (typeof logger.debug === \"function\") {\n logger.debug(entry.message, entry.payload);\n } else {\n log.debug(entry.message, entry.payload);\n }\n }\n return entry;\n };\n}\n"],"mappings":";;;;;AA6BA,SAAS,cAAc,QAAqC;AAC1D,MAAI,OAAO,OAAO,WAAW,YAAY,OAAO,OAAO,SAAS,GAAG;AACjE,WAAO,OAAO;AAAA,EAChB;AACA,MAAI,OAAO,WAAW,QAAQ;AAC5B,WAAO;AAAA,EACT;AACA,SAAO,GAAG,KAAK,IAAI,GAAG,KAAK,MAAM,OAAO,UAAU,CAAC,CAAC;AACtD;AAEO,SAAS,0BAA0B,QAAqD;AAC7F,QAAM,UAAU;AAAA,IACd,SAAS,OAAO;AAAA,IAChB,UAAU,OAAO;AAAA,IACjB,YAAY,OAAO;AAAA,IACnB,YAAY,OAAO;AAAA,IACnB,QAAQ,OAAO;AAAA,IACf,SAAS,OAAO;AAAA,EAClB;AACA,SAAO;AAAA,IACL,SAAS;AAAA,IACT;AAAA,IACA,OAAO,OAAO,aAAa,UAAU,OAAO,WAAW,OAAO,WAAW,SAAS,SAAS;AAAA,IAC3F,QAAQ,cAAc,MAAM;AAAA,EAC9B;AACF;AAEO,SAAS,kCAAkC,UAG9C,CAAC,GAAG;AACN,QAAM,SAAS,QAAQ,UAAU;AACjC,SAAO,CAAC,WAAwD;AAC9D,UAAM,QAAQ,0BAA0B,MAAM;AAC9C,QAAI,QAAQ,SAAS;AACnB,cAAQ,QAAQ,OAAO,OAAO,IAAI,MAAM;AAAA,IAC1C;AACA,QAAI,MAAM,UAAU,QAAQ;AAC1B,UAAI,OAAO,OAAO,SAAS,YAAY;AACrC,eAAO,KAAK,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