@onigeya/dsh-kanabo-memory 0.0.0-stage → 0.1.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.
@@ -0,0 +1,561 @@
1
+ /**
2
+ * 时间窗查询(P1 任务 15):给定 `video_id` 与闭区间 `[t0,t1]`,返回**覆盖该区间**的
3
+ * `VIDEO_CLIP`(按需加 `AUDIO_SEGMENT`),按「覆盖比例 × 年龄衰减」排序,每条都带证据指针。
4
+ * 它是**查询**而不是过滤器:排序在应用层完成,`limit` 只截断排序后的结果,`total` 永远是真值。
5
+ *
6
+ * 为什么查询长这样(实测,见 `docs/research/triviumdb.md` §一第 1 项与 `.omo/evidence/dsh-kanabo-platform/task-15.log`):
7
+ * 1. **时间区间过滤是引擎原生的**:`FIND {source_type: …, video_id: …, t0: {$lte: T1}, t1: {$gte: T0}}`
8
+ * 在同一对象里同时下两个区间条件,引擎两个都应用(实测只返回相交的节点)。
9
+ * 建了 `createOrderedIndex('t0')` 后 `EXPLAIN` 的访问路径从 `full_node_scan` 变成
10
+ * `ordered_property_index (t0)`;索引不存在时结果集完全相同,只是全扫。
11
+ * **索引的创建属于写入路径**(迁移/任务 16),本模块不建索引——`store-trivium.js` 的门面也没有这个操作,
12
+ * 而本任务不允许改门面。因此本模块保证谓词是「索引可用」的形状,并用 `EXPLAIN` 在证据里证明这一点。
13
+ * 2. **嵌套路径不能过滤**:`FIND {envelope.t0: …}` 直接 `TDB_QUERY_PARSE`(`Expected Colon, got Dot`),
14
+ * `FIND {envelope: {…}}` 也不行(`Expected $operator`)。所以时间窗要求**行本身就是信封**:
15
+ * `source_type` / `video_id`(或 `audio_id`)/ `t0` / `t1` / `ts` 必须是 payload 的**顶层字段**。
16
+ * 这正是设计文档 §4.2「视觉解析输出标准化为 Memory Envelope 结构体」的读法,也让 recall-trivium
17
+ * 的 `envelopeOf()`(平铺 payload 原样返回)继续可用。迁移写入的两层形状(`{kind, envelope: {…}}`)
18
+ * **无法被时间窗查询**,这是写侧契约,不是本模块可以绕过的。
19
+ * 3. **引擎没有衰减与融合算子**(`RETURN exp(…)` 在解析期被拒,见 §五第 4 项),所以排序在这里实现。
20
+ * 4. **文件级独占租约**:门面接受已打开的注入句柄(注入的绝不 close),或自己开一个(`close()` 时关)。
21
+ * 本模块不建进程级注册表——「一个工作区一个门面」是任务 16 的交付物。
22
+ *
23
+ * ## 边界语义(闭区间,两端都含)
24
+ *
25
+ * 记条目自身区间 `[a0,a1]`(契约保证 `a1 > a0`)、查询窗口 `[w0,w1]`(允许 `w0 == w1`,零长度)。
26
+ *
27
+ * - **相交判定**:`a1 >= w0 && a0 <= w1`。两个闭区间交集非空 ⟺ 这两个不等式同时成立;
28
+ * 端点相等算相交(`a1 == w0` 或 `a0 == w1` 时交集是一个点,条目**会被返回**)。
29
+ * - **返回的区间不被悄悄裁剪**:`item.bounds` 永远是条目自己的 `[a0,a1]`;窗口内那一段单独放在
30
+ * `item.overlap = { t0, t1, ms }`(`t0 = max(a0,w0)`、`t1 = min(a1,w1)`)。所以跨场景窗口会返回两条
31
+ * 各自完整的边界,而不是被窗口切过的「片段」。
32
+ * - **关系分类**(`item.relation`):
33
+ * | 值 | 含义 |
34
+ * | --- | --- |
35
+ * | `inside` | 条目整个在窗口内(端点相等也算) |
36
+ * | `contains` | 窗口整个在条目内 |
37
+ * | `overlap-left` | 条目从窗口左侧伸出(`a0 < w0 < a1 <= w1`) |
38
+ * | `overlap-right` | 条目向窗口右侧伸出(`w0 <= a0 < w1 < a1`) |
39
+ * | `touch-start` | 条目的终点正好落在窗口起点(交集是点 `{w0}`) |
40
+ * | `touch-end` | 条目的起点正好落在窗口终点(交集是点 `{w1}`) |
41
+ * | `point` | 零长度窗口落在条目内部(`a0 < w0 == w1 < a1`) |
42
+ *
43
+ * ## 排序公式(可手算)
44
+ *
45
+ * coverage = overlap.ms / (item.t1 - item.t0) // 条目被窗口覆盖的比例,0..1
46
+ * ageMs = max(0, now - item.ts) // 条目证据的时间戳
47
+ * decay = 2 ^ (-ageMs / halfLifeMs) // 半衰期衰减,默认 30 天
48
+ * score = (coverage + TIE_FLOOR) × decay // TIE_FLOOR = 1e-6
49
+ *
50
+ * `TIE_FLOOR` 只做一件事:让 `coverage == 0` 的「点接触」与零长度窗口仍有分数,于是这些条目之间
51
+ * 按**新旧**排序而不是掉到 id 并列规则里;它不给点接触任何特权(任何真实重叠的 coverage 都大于它)。
52
+ * 并列规则:`score` 降序 → `overlap.ms` 降序 → 条目 `t0` 升序 → `nodeId` 升序(给定 `now` 时逐位可复现)。
53
+ *
54
+ * ## 与语义召回组合(先窗后语义)
55
+ *
56
+ * `windowQuery` 返回 `nodeIds`(窗口内**全部**候选的节点 id,按排名)与 `ids`(信封 id),可直接作为
57
+ * recall-trivium 的 `seedIds`。传 `semanticQuery` 时本模块会调用它并**把结果裁到窗口内**:
58
+ *
59
+ * windowQuery({ videoId, t0, t1, query: '…', semanticQuery: (ctx) => recall.recall(ctx.query, …) })
60
+ * → result.semantic = { hits, excluded, … } // hits 只含窗口内节点;excluded 逐条给出窗口外原因
61
+ *
62
+ * 裁剪按节点 id 做(节点 id 是同一库内的真身份;信封 id 只在 payload 里)。所以「窗口真的约束了语义召回」
63
+ * 是可断言的事实,而不是靠调用方自觉。
64
+ */
65
+ import { EMBEDDING_DIM, SOURCE_TYPES } from './contract.js'
66
+ import { createTriviumStore } from './store-trivium.js'
67
+
68
+ /** 时间窗覆盖的两种信封类型:场景/片段与字幕/音轨切片。 */
69
+ export const CLIP_TYPE = 'VIDEO_CLIP'
70
+ export const AUDIO_TYPE = 'AUDIO_SEGMENT'
71
+ /** 边界口径:闭区间,两端都含。改这个常量就是改契约,必须同时改头注释与测试。 */
72
+ export const WINDOW_ENDPOINTS = 'inclusive'
73
+ /** 默认返回条数与上限(与 recall-trivium 的 limit 口径一致)。 */
74
+ export const DEFAULT_LIMIT = 20
75
+ export const MAX_LIMIT = 200
76
+ /** 年龄衰减半衰期:默认 30 天,与 recall-trivium 同值(引擎无原生衰减算子)。 */
77
+ export const DEFAULT_HALF_LIFE_MS = 30 * 24 * 60 * 60 * 1000
78
+ /** 覆盖率为 0 时的分数下限,只用于让点接触/零长度窗口仍按新旧排序。 */
79
+ export const TIE_FLOOR = 1e-6
80
+ /** 单次查询最多读入的候选行数:超出就按 t0 截断并**明示** `candidatesTruncated`,绝不静默。 */
81
+ export const DEFAULT_MAX_CANDIDATES = 5000
82
+
83
+ /** 带稳定 `code` 的错误,形状与 store.js / recall-trivium.js 的 `KANABO_*` 约定一致。 */
84
+ function windowError(code, message, extra = {}) {
85
+ const error = new Error(message, extra.cause === undefined ? undefined : { cause: extra.cause })
86
+ error.code = code
87
+ if (extra.details !== undefined) error.details = extra.details
88
+ return error
89
+ }
90
+
91
+ /** 契约里必须存在这两种类型名;契约改名时这里立刻报错,而不是悄悄查不到东西。 */
92
+ function assertContractTypes() {
93
+ for (const type of [CLIP_TYPE, AUDIO_TYPE]) {
94
+ if (!SOURCE_TYPES.includes(type)) {
95
+ throw windowError(
96
+ 'KANABO_WINDOW_CONTRACT',
97
+ `contract.js 的 SOURCE_TYPES 不含 ${type};时间窗查询依赖该类型名,契约变更必须同步本模块。`,
98
+ { details: { type, sourceTypes: [...SOURCE_TYPES] } })
99
+ }
100
+ }
101
+ }
102
+
103
+ /** ≥ 0 的有限毫秒数;负数、NaN、Infinity、字符串数字、超出安全整数的值都被拒。 */
104
+ function nonNegativeMs(value, field) {
105
+ const number = typeof value === 'number' ? value : NaN
106
+ if (!Number.isFinite(number) || number < 0 || number > Number.MAX_SAFE_INTEGER) {
107
+ throw windowError(
108
+ 'KANABO_WINDOW_RANGE',
109
+ `时间窗的 ${field} 必须是 0..${Number.MAX_SAFE_INTEGER} 之间的有限毫秒数(收到 ${String(value)})。`,
110
+ { details: { field, received: String(value) } })
111
+ }
112
+ return number
113
+ }
114
+
115
+ /** 校验并归一化窗口:`t1 < t0` 是错误;`t1 == t0` 是合法的零长度窗口。 */
116
+ export function normalizeWindow(t0, t1) {
117
+ const start = nonNegativeMs(t0, 't0')
118
+ const end = nonNegativeMs(t1, 't1')
119
+ if (end < start) {
120
+ throw windowError(
121
+ 'KANABO_WINDOW_RANGE',
122
+ `时间窗必须是 t1 >= t0(收到 t0=${start}, t1=${end});闭区间的两端顺序不可颠倒。`,
123
+ { details: { t0: start, t1: end } })
124
+ }
125
+ return { t0: start, t1: end, lengthMs: end - start, degenerate: end === start }
126
+ }
127
+
128
+ /** 只拼有限数字:`nonNegativeMs` 已把窗口限制在安全整数内,`String()` 不会给出指数形式,引擎可解析。 */
129
+ function tqlNumber(value) {
130
+ if (!Number.isFinite(value)) {
131
+ throw windowError('KANABO_WINDOW_RANGE', `只能把有限数字拼进 TQL(收到 ${String(value)})。`)
132
+ }
133
+ return String(value)
134
+ }
135
+
136
+ /**
137
+ * 相交判定 + 关系分类(纯函数,可单独测)。不相交返回 `null`。
138
+ *
139
+ * @param {{t0:number,t1:number}} bounds 条目自身区间(`t1 > t0`)
140
+ * @param {{t0:number,t1:number,lengthMs:number}} window 归一化后的窗口
141
+ */
142
+ export function classifyWindowOverlap(bounds, window) {
143
+ const { t0: a0, t1: a1 } = bounds
144
+ const { t0: w0, t1: w1, lengthMs } = window
145
+ // 闭区间:交集非空 ⟺ 条目终点不早于窗口起点且条目起点不晚于窗口终点。
146
+ if (a1 < w0 || a0 > w1) return null
147
+ const lo = Math.max(a0, w0)
148
+ const hi = Math.min(a1, w1)
149
+ const overlapMs = hi - lo
150
+ const clipLength = a1 - a0
151
+ let relation
152
+ if (overlapMs === 0) {
153
+ // 只剩「一个点」的情形:端点相接,或零长度窗口落在条目内部。
154
+ if (lengthMs === 0) relation = w0 === a1 ? 'touch-start' : w0 === a0 ? 'touch-end' : 'point'
155
+ else relation = a1 === w0 ? 'touch-start' : 'touch-end'
156
+ } else if (a0 >= w0 && a1 <= w1) relation = 'inside'
157
+ else if (a0 <= w0 && a1 >= w1) relation = 'contains'
158
+ else if (a0 < w0) relation = 'overlap-left'
159
+ else relation = 'overlap-right'
160
+ return {
161
+ relation,
162
+ overlap: { t0: lo, t1: hi, ms: overlapMs },
163
+ ratioOfClip: clipLength > 0 ? overlapMs / clipLength : 0,
164
+ ratioOfWindow: lengthMs > 0 ? overlapMs / lengthMs : 0,
165
+ }
166
+ }
167
+
168
+ /** 年龄衰减:`2 ^ (-age/halfLife)`;`age` 负值按 0(证据时间戳在未来时不放大分数)。 */
169
+ export function ageDecay(ts, now, halfLifeMs) {
170
+ const ageMs = Math.max(0, now - ts)
171
+ return { ageMs, decay: Math.pow(2, -ageMs / halfLifeMs) }
172
+ }
173
+
174
+ /** 引擎返回的 id 可能是数字或十进制字符串;超出安全整数就拒绝,而不是静默失真。 */
175
+ function nodeIdOf(value) {
176
+ const id = typeof value === 'number' ? value : Number(value)
177
+ return Number.isSafeInteger(id) && id >= 0 ? id : null
178
+ }
179
+
180
+ /** `RETURN _ AS node` 投影的是节点包装(`{ id, numEdges, payload }`),业务字段在里层。 */
181
+ function unwrapNode(value) {
182
+ if (value === null || typeof value !== 'object') return null
183
+ return value.payload !== null && typeof value.payload === 'object' ? value.payload : null
184
+ }
185
+
186
+ /** 证据指针里按类型携带的字段(契约 TYPE_FIELDS 的可读子集;缺的就不写,不造 null 字段)。 */
187
+ function typeEvidence(payload) {
188
+ if (payload?.source_type === CLIP_TYPE) {
189
+ const out = {}
190
+ for (const field of ['frame_id', 'keyframe_path', 'scene_description', 'app', 'activity']) {
191
+ if (typeof payload[field] === 'string') out[field] = payload[field]
192
+ }
193
+ if (typeof payload.video_id === 'string') out.video_id = payload.video_id
194
+ return out
195
+ }
196
+ const out = {}
197
+ for (const field of ['text', 'speaker', 'stem']) {
198
+ if (typeof payload[field] === 'string') out[field] = payload[field]
199
+ }
200
+ if (typeof payload.audio_id === 'string') out.audio_id = payload.audio_id
201
+ return out
202
+ }
203
+
204
+ /**
205
+ * 证据指针的唯一构造点。行缺字段时**返回 null**,由 `assertEvidence` 决定这是致命错误
206
+ * (这是刻意的两段式:构造与断言分开,负向对照只需打断构造就能看到断言开火)。
207
+ */
208
+ function buildEvidence(nodeId, payload) {
209
+ if (payload === null || payload === undefined) return null
210
+ const trace = payload.evidence_trace
211
+ return {
212
+ nodeId,
213
+ id: payload.id,
214
+ source_type: payload.source_type,
215
+ t0: payload.t0,
216
+ t1: payload.t1,
217
+ ts: payload.ts,
218
+ evidence_trace: trace === null || trace === undefined || typeof trace !== 'object'
219
+ ? null
220
+ : { kind: trace.kind ?? null, source: trace.source ?? null, detail: trace.detail ?? null },
221
+ ...typeEvidence(payload),
222
+ }
223
+ }
224
+
225
+ /**
226
+ * 结果的硬性不变量:**没有证据指针的条目不允许存在**。缺 nodeId / 信封 id / t0 / t1 / ts,
227
+ * 或 `t1` 不满足 `> t0`,都抛 `KANABO_WINDOW_EVIDENCE`——这是 bug(写侧写了不合契约的行),
228
+ * 不是可以只记一条警告然后继续的事。
229
+ */
230
+ function assertEvidence(evidence, nodeId) {
231
+ const missing = []
232
+ if (evidence === null || evidence === undefined) {
233
+ throw windowError(
234
+ 'KANABO_WINDOW_EVIDENCE',
235
+ `节点 ${String(nodeId)} 没有证据指针;时间窗结果不允许无证据条目。`,
236
+ { details: { nodeId, missing: ['evidence'] } })
237
+ }
238
+ if (!Number.isSafeInteger(evidence.nodeId) || evidence.nodeId < 0) missing.push('nodeId')
239
+ if (typeof evidence.id !== 'string' || evidence.id.length === 0) missing.push('id')
240
+ for (const field of ['t0', 't1', 'ts']) {
241
+ if (!Number.isFinite(evidence[field]) || evidence[field] < 0) missing.push(field)
242
+ }
243
+ if (!(evidence.t1 > evidence.t0)) missing.push('t1>t0')
244
+ if (missing.length > 0) {
245
+ throw windowError(
246
+ 'KANABO_WINDOW_EVIDENCE',
247
+ `节点 ${String(nodeId)} 的证据指针缺字段或不合法:${missing.join(', ')};时间窗结果不允许无证据条目。`,
248
+ { details: { nodeId, missing } })
249
+ }
250
+ return evidence
251
+ }
252
+
253
+ /** 一行 TQL 结果 → 排序前的条目。引擎谓词与这里的分类器是同一规则的两份实现,返回 null 表示两者分歧。 */
254
+ function toItem(row, window, options) {
255
+ const nodeId = nodeIdOf(row?.nodeId)
256
+ const payload = unwrapNode(row?.node)
257
+ const evidence = assertEvidence(buildEvidence(nodeId, payload), nodeId)
258
+ const overlap = classifyWindowOverlap({ t0: evidence.t0, t1: evidence.t1 }, window)
259
+ if (overlap === null) return null
260
+ const { ageMs, decay } = ageDecay(evidence.ts, options.now, options.halfLifeMs)
261
+ const score = (overlap.ratioOfClip + TIE_FLOOR) * decay
262
+ return {
263
+ id: evidence.id,
264
+ nodeId,
265
+ source_type: evidence.source_type,
266
+ bounds: { t0: evidence.t0, t1: evidence.t1 },
267
+ relation: overlap.relation,
268
+ overlap: { ...overlap.overlap, ratioOfClip: overlap.ratioOfClip, ratioOfWindow: overlap.ratioOfWindow },
269
+ ts: evidence.ts,
270
+ ageMs,
271
+ decay,
272
+ score,
273
+ evidence,
274
+ }
275
+ }
276
+
277
+ /** 并列规则:分数降序 → 重叠长度降序 → 条目起点升序 → nodeId 升序 → 信封 id。 */
278
+ function byRank(a, b) {
279
+ if (b.score !== a.score) return b.score - a.score
280
+ if (b.overlap.ms !== a.overlap.ms) return b.overlap.ms - a.overlap.ms
281
+ if (a.bounds.t0 !== b.bounds.t0) return a.bounds.t0 - b.bounds.t0
282
+ if (a.nodeId !== b.nodeId) return a.nodeId - b.nodeId
283
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0
284
+ }
285
+
286
+ /**
287
+ * 片段的 TQL:`source_type` + `video_id` + 两个区间条件(`t0 <= w1` 与 `t1 >= w0`),
288
+ * 顺序取 `t0` 以便候选截断稳定;`LIMIT cap` 的 `cap` 比上限多 1,用来发现「还有更多」。
289
+ */
290
+ function clipQuery(videoId, window, cap) {
291
+ return `FIND {source_type: ${JSON.stringify(CLIP_TYPE)}, video_id: ${JSON.stringify(videoId)}, `
292
+ + `t0: {$lte: ${tqlNumber(window.t1)}}, t1: {$gte: ${tqlNumber(window.t0)}}} `
293
+ + `RETURN _.id AS nodeId, _ AS node ORDER BY t0 ASC LIMIT ${cap}`
294
+ }
295
+
296
+ /** 音轨切片:契约里 `AUDIO_SEGMENT` 只有 `audio_id`(没有指回 video 的字段),所以必须显式给音轨 id。 */
297
+ function audioQuery(audioIds, window, cap) {
298
+ const list = audioIds.map((id) => JSON.stringify(id)).join(', ')
299
+ return `FIND {source_type: ${JSON.stringify(AUDIO_TYPE)}, audio_id: {$in: [${list}]}, `
300
+ + `t0: {$lte: ${tqlNumber(window.t1)}}, t1: {$gte: ${tqlNumber(window.t0)}}} `
301
+ + `RETURN _.id AS nodeId, _ AS node ORDER BY t0 ASC LIMIT ${cap}`
302
+ }
303
+
304
+ function clampInt(value, fallback, min, max) {
305
+ const number = Number(value)
306
+ if (!Number.isFinite(number)) return fallback
307
+ return Math.min(max, Math.max(min, Math.floor(number)))
308
+ }
309
+
310
+ function rowsOf(result) {
311
+ return Array.isArray(result?.rows) ? result.rows : []
312
+ }
313
+
314
+ /**
315
+ * 语义细化结果的窗口裁剪(纯函数):命中按**节点 id** 对窗口;窗口外的逐条进 `excluded`。
316
+ * 节点 id 是同一库内的真身份,信封 id 只在 payload 里,两者都认但节点 id 优先。
317
+ */
318
+ export function filterSemanticToWindow(recallResult, windowItems, queryText = '') {
319
+ const byNodeId = new Map(windowItems.map((item) => [item.nodeId, item]))
320
+ const byId = new Map(windowItems.map((item) => [item.id, item]))
321
+ const hits = []
322
+ const excluded = []
323
+ const list = Array.isArray(recallResult?.hits) ? recallResult.hits : []
324
+ for (const hit of list) {
325
+ const rawNodeId = hit?.nodeId
326
+ const hasNodeId = rawNodeId !== null && rawNodeId !== undefined && Number.isSafeInteger(Number(rawNodeId))
327
+ const item = hasNodeId ? byNodeId.get(Number(rawNodeId)) : byId.get(String(hit?.id ?? ''))
328
+ if (item === undefined) {
329
+ excluded.push({
330
+ id: hit?.id ?? null,
331
+ nodeId: hit?.nodeId ?? null,
332
+ reason: 'out_of_window',
333
+ text: typeof hit?.text === 'string' ? hit.text : '',
334
+ })
335
+ continue
336
+ }
337
+ hits.push({
338
+ ...hit,
339
+ window: {
340
+ relation: item.relation,
341
+ overlapMs: item.overlap.ms,
342
+ ratioOfClip: item.overlap.ratioOfClip,
343
+ windowScore: item.score,
344
+ },
345
+ })
346
+ }
347
+ return {
348
+ query: String(queryText ?? ''),
349
+ hits,
350
+ excluded,
351
+ returned: hits.length,
352
+ excludedCount: excluded.length,
353
+ recall: {
354
+ ranked: recallResult?.ranked ?? null,
355
+ candidates: recallResult?.candidates ?? null,
356
+ truncated: recallResult?.truncated ?? null,
357
+ arms: recallResult?.arms ?? null,
358
+ },
359
+ }
360
+ }
361
+
362
+ /**
363
+ * 门面工厂:`options.store` 已注入则绝不自建、也绝不 close;否则用 `createTriviumStore` 自建
364
+ * (默认向量维度取契约的 `EMBEDDING_DIM`,因为用错维度开库会被引擎以 `TDB_DIMENSION_MISMATCH` 拒绝)。
365
+ *
366
+ * @param {object} [options]
367
+ * @param {object} [options.store] 已打开的 TriviumDB 异步门面(注入时由调用方负责关闭)
368
+ * @param {string} [options.workspace] 自建门面时的分域键(`store.js` 的 `scopeOf` 口径)
369
+ * @param {string} [options.dir] 库目录(默认 `triviumDir()`,落在临时目录,绝不进仓库)
370
+ * @param {number} [options.dim] 自建门面时的向量维度,默认 `EMBEDDING_DIM`
371
+ * @param {number} [options.idleMs] 空闲退出阈值(透传门面)
372
+ * @param {number} [options.requestTimeoutMs] 单请求期限(透传门面)
373
+ */
374
+ export function createWindowQuery(options = {}) {
375
+ const ownsStore = options.store === undefined || options.store === null
376
+ let store = options.store ?? null
377
+ let opened = false
378
+ let closed = false
379
+ const counters = { queries: 0, semanticRefinements: 0 }
380
+
381
+ function ensureStore() {
382
+ if (store !== null) return store
383
+ if (ownsStore) {
384
+ if (typeof options.workspace !== 'string' || options.workspace === '') {
385
+ throw windowError('KANABO_WINDOW_WORKSPACE', '未注入 store 时必须提供非空的 workspace(分域键)。')
386
+ }
387
+ store = createTriviumStore({
388
+ workspace: options.workspace,
389
+ dir: options.dir,
390
+ dim: Number.isInteger(options.dim) && options.dim > 0 ? options.dim : EMBEDDING_DIM,
391
+ idleMs: options.idleMs,
392
+ requestTimeoutMs: options.requestTimeoutMs,
393
+ })
394
+ }
395
+ return store
396
+ }
397
+
398
+ async function open() {
399
+ const handle = ensureStore()
400
+ await handle.open()
401
+ opened = true
402
+ return handle
403
+ }
404
+
405
+ /**
406
+ * 时间窗查询入口。
407
+ *
408
+ * @param {object} params
409
+ * @param {string} params.videoId 视频 id(契约 `VIDEO_CLIP.video_id`)
410
+ * @param {number} params.t0 窗口起点(含),毫秒,≥ 0
411
+ * @param {number} params.t1 窗口终点(含),毫秒,≥ t0;`t1 == t0` 是零长度窗口
412
+ * @param {boolean} [params.includeAudio] 是否同时查 `AUDIO_SEGMENT`
413
+ * @param {string[]} [params.audioIds] `includeAudio: true` 时必填:要查的音轨 id(契约无 audio→video 字段)
414
+ * @param {number} [params.limit] 返回条数(默认 20,夹到 1..200)
415
+ * @param {number} [params.now] 计算衰减的「现在」(默认 `Date.now()`;给定则结果逐位可复现)
416
+ * @param {number} [params.halfLifeMs] 衰减半衰期(默认 30 天)
417
+ * @param {number} [params.maxCandidates] 候选行上限(默认 5000;超出按 t0 截断并明示)
418
+ * @param {string} [params.query] 传给 `semanticQuery` 的查询文本
419
+ * @param {(ctx: object) => Promise<object>} [params.semanticQuery] 语义细化;结果会被裁到窗口内
420
+ */
421
+ async function windowQuery(params = {}) {
422
+ if (closed) throw windowError('KANABO_WINDOW_CLOSED', '时间窗查询器已关闭。')
423
+ const started = performance.now()
424
+ const merged = { ...options, ...params }
425
+ assertContractTypes()
426
+
427
+ const { videoId } = merged
428
+ if (typeof videoId !== 'string' || videoId.trim() === '') {
429
+ throw windowError('KANABO_WINDOW_VIDEO', 'windowQuery 需要非空的 videoId(字符串)。')
430
+ }
431
+ const window = normalizeWindow(merged.t0, merged.t1)
432
+ const now = Number.isFinite(merged.now) ? merged.now : Date.now()
433
+ const halfLifeMs = Number.isFinite(merged.halfLifeMs) && merged.halfLifeMs > 0
434
+ ? merged.halfLifeMs
435
+ : DEFAULT_HALF_LIFE_MS
436
+ const limit = clampInt(merged.limit, DEFAULT_LIMIT, 1, MAX_LIMIT)
437
+ const maxCandidates = clampInt(merged.maxCandidates, DEFAULT_MAX_CANDIDATES, 1, 50_000)
438
+ const includeAudio = merged.includeAudio === true
439
+ let audioIds = []
440
+ if (includeAudio) {
441
+ if (!Array.isArray(merged.audioIds) || merged.audioIds.length === 0
442
+ || merged.audioIds.some((id) => typeof id !== 'string' || id.length === 0)) {
443
+ throw windowError(
444
+ 'KANABO_WINDOW_AUDIO',
445
+ 'includeAudio: true 需要非空的 audioIds(字符串数组):契约里 AUDIO_SEGMENT 只有 audio_id,'
446
+ + '没有指回 video 的字段,所以音轨必须显式点出。',
447
+ { details: { includeAudio, audioIds: merged.audioIds ?? null } })
448
+ }
449
+ audioIds = [...new Set(merged.audioIds)]
450
+ }
451
+ const semanticQuery = merged.semanticQuery
452
+ if (semanticQuery !== undefined && semanticQuery !== null && typeof semanticQuery !== 'function') {
453
+ throw windowError('KANABO_WINDOW_SEMANTIC', 'semanticQuery 必须是函数(接收窗口上下文,返回 recall 结果)。')
454
+ }
455
+
456
+ const handle = await open()
457
+ const cap = maxCandidates + 1
458
+ const rows = []
459
+ const dbAt = performance.now()
460
+ rows.push(...rowsOf(await handle.tql(clipQuery(videoId, window, cap))))
461
+ if (includeAudio) rows.push(...rowsOf(await handle.tql(audioQuery(audioIds, window, cap))))
462
+ const dbMs = Math.round((performance.now() - dbAt) * 10) / 10
463
+
464
+ const rankAt = performance.now()
465
+ const items = []
466
+ let predicateMismatches = 0
467
+ for (const row of rows) {
468
+ const item = toItem(row, window, { now, halfLifeMs })
469
+ if (item === null) {
470
+ predicateMismatches += 1
471
+ continue
472
+ }
473
+ items.push(item)
474
+ }
475
+ items.sort(byRank)
476
+ const candidatesTruncated = items.length > maxCandidates
477
+ const ranked = candidatesTruncated ? items.slice(0, maxCandidates) : items
478
+ const page = ranked.slice(0, limit)
479
+ const rankMs = Math.round((performance.now() - rankAt) * 10) / 10
480
+
481
+ const result = {
482
+ query: {
483
+ videoId,
484
+ audioIds,
485
+ window,
486
+ includeAudio,
487
+ endpoints: WINDOW_ENDPOINTS,
488
+ limit,
489
+ halfLifeMs,
490
+ now,
491
+ },
492
+ ranking: {
493
+ formula: '(coverage + 1e-6) × 2^(-age/halfLifeMs)',
494
+ coverage: 'overlap.ms / (item.t1 - item.t0)',
495
+ tieBreak: 'score desc, overlap.ms desc, item.t0 asc, nodeId asc',
496
+ tieFloor: TIE_FLOOR,
497
+ },
498
+ items: page,
499
+ /** 窗口内**全部**候选(按排名),供语义召回当 `seedIds` 或做集合运算;不受 `limit` 影响。 */
500
+ nodeIds: ranked.map((item) => item.nodeId),
501
+ ids: ranked.map((item) => item.id),
502
+ total: ranked.length,
503
+ returned: page.length,
504
+ truncated: ranked.length > page.length,
505
+ candidates: rows.length,
506
+ /** 引擎谓词与分类器分歧的行数;健康运行恒为 0,非 0 意味着两层对同一边界规则理解不一致。 */
507
+ predicateMismatches,
508
+ candidatesTruncated,
509
+ timings: { db: dbMs, rank: rankMs, total: Math.round((performance.now() - started) * 10) / 10 },
510
+ }
511
+
512
+ if (typeof semanticQuery === 'function') {
513
+ const semanticAt = performance.now()
514
+ const ctx = {
515
+ query: typeof merged.query === 'string' ? merged.query : '',
516
+ videoId,
517
+ window,
518
+ nodeIds: result.nodeIds,
519
+ ids: result.ids,
520
+ items: ranked,
521
+ total: result.total,
522
+ }
523
+ const recallResult = await semanticQuery(ctx)
524
+ result.semantic = filterSemanticToWindow(recallResult, ranked, ctx.query)
525
+ result.timings.semantic = Math.round((performance.now() - semanticAt) * 10) / 10
526
+ counters.semanticRefinements += 1
527
+ }
528
+ counters.queries += 1
529
+ return result
530
+ }
531
+
532
+ return {
533
+ windowQuery,
534
+ open,
535
+ /** 注入的门面由调用方关闭;自建的那一个在这里关(幂等)。 */
536
+ async close() {
537
+ closed = true
538
+ if (!ownsStore || store === null) return { closed: true, owned: false }
539
+ const result = await store.close()
540
+ return { ...result, owned: true }
541
+ },
542
+ stats() {
543
+ return { ...counters, opened, ownsStore, closed, dim: ownsStore ? (options.dim ?? EMBEDDING_DIM) : null }
544
+ },
545
+ }
546
+ }
547
+
548
+ /**
549
+ * 单次调用的便捷入口:自己开门面、查完关掉(注入 `store` 时不关)。
550
+ * 有复用需求时用 `createWindowQuery()`,别每次调用都付一次子进程冷启动。
551
+ */
552
+ export async function windowQuery(params = {}) {
553
+ const query = createWindowQuery(params)
554
+ try {
555
+ return await query.windowQuery(params)
556
+ } finally {
557
+ await query.close()
558
+ }
559
+ }
560
+
561
+ export default windowQuery