@aiwayds/dsh-topics-memory 0.21.0 → 0.23.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/README.md +5 -0
- package/README.zh.md +5 -0
- package/lib/commands.js +27 -11
- package/lib/config.d.ts +54 -1
- package/lib/config.js +38 -1
- package/lib/digest.d.ts +73 -0
- package/lib/digest.js +384 -0
- package/lib/distill.d.ts +39 -0
- package/lib/distill.js +250 -15
- package/lib/embedding.d.ts +113 -0
- package/lib/embedding.js +208 -0
- package/lib/ilog.d.ts +145 -0
- package/lib/ilog.js +236 -0
- package/lib/index.d.ts +8 -0
- package/lib/index.js +23 -6
- package/lib/pipeline-events.d.ts +36 -0
- package/lib/pipeline-events.js +121 -0
- package/lib/quality.d.ts +47 -7
- package/lib/quality.js +124 -20
- package/lib/retrieval.d.ts +119 -0
- package/lib/retrieval.js +290 -0
- package/lib/service.d.ts +60 -3
- package/lib/service.js +320 -44
- package/lib/store.d.ts +15 -12
- package/lib/store.js +43 -3
- package/lib/tools.js +6 -2
- package/package.json +2 -2
- package/src/commands.ts +35 -16
- package/src/config.ts +47 -1
- package/src/digest.ts +416 -0
- package/src/distill.ts +275 -14
- package/src/embedding.ts +294 -0
- package/src/ilog.ts +306 -0
- package/src/index.ts +23 -5
- package/src/pipeline-events.ts +132 -0
- package/src/quality.ts +145 -21
- package/src/retrieval.ts +357 -0
- package/src/service.ts +326 -52
- package/src/store.ts +46 -10
- package/src/tools.ts +6 -2
package/lib/digest.js
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
* @module digest
|
|
10
10
|
*/
|
|
11
11
|
import { sectionOf, firstParagraph, CONCLUSION_HEADING, RECOMMENDATIONS_HEADING } from "./okf.js";
|
|
12
|
+
import { tokenize } from "./retrieval.js";
|
|
12
13
|
/** Rough CJK-aware token estimate: ~0.75 token per CJK char, ~4 chars per latin token. */
|
|
13
14
|
export function estimateTokens(text) {
|
|
14
15
|
let cjk = 0;
|
|
@@ -180,3 +181,386 @@ export function assemblePointer(entries, cfg, slow) {
|
|
|
180
181
|
export function assembleInjection(entries, cfg, slow) {
|
|
181
182
|
return packInjection(entries, cfg, topicDigest, slow);
|
|
182
183
|
}
|
|
184
|
+
/** Total package cap — pinned, does not float with hit strength (A3 决议 3). */
|
|
185
|
+
export const PACKAGE_TOTAL = 600;
|
|
186
|
+
export const PACKAGE_DIRECT_MAX = 2;
|
|
187
|
+
export const PACKAGE_DIRECT_BUDGET = 120;
|
|
188
|
+
export const PACKAGE_NEIGHBOR_MAX = 3;
|
|
189
|
+
export const PACKAGE_NEIGHBOR_BUDGET = 40;
|
|
190
|
+
export const PACKAGE_WEAK_MAX = 2;
|
|
191
|
+
/**
|
|
192
|
+
* Padded-trivial arm of the downgrade guard (spec §2.3 名词实体口径, an
|
|
193
|
+
* implementation-time item per §11): after stripping whitespace, a query this
|
|
194
|
+
* short counts as 琐碎 even when the tokenizer expands CJK bigrams past 3
|
|
195
|
+
* tokens. Calibrated on the two named scenarios: 场景① ack query strips to
|
|
196
|
+
* 15 chars (downgrade), a real review query strips to 18 (kept).
|
|
197
|
+
*/
|
|
198
|
+
export const PACKAGE_TRIVIAL_QUERY_CHARS = 16;
|
|
199
|
+
const PACKAGE_WRAPPER_OPEN = '<topic-memory>';
|
|
200
|
+
const PACKAGE_WRAPPER_CLOSE = '</topic-memory>';
|
|
201
|
+
/** Edge/lane note for the why line / neighborhood annotation (A3 决议 2). */
|
|
202
|
+
function viaNote(via) {
|
|
203
|
+
if (via === undefined || via === '')
|
|
204
|
+
return null;
|
|
205
|
+
if (via.startsWith('depends'))
|
|
206
|
+
return '经 depends 关联';
|
|
207
|
+
if (via.startsWith('slow'))
|
|
208
|
+
return '慢道 pick';
|
|
209
|
+
if (via.startsWith('semantic'))
|
|
210
|
+
return '语义近邻';
|
|
211
|
+
return via;
|
|
212
|
+
}
|
|
213
|
+
/** Trigger reason → the trigger word when the caller carries it, `''` channel-only. */
|
|
214
|
+
function triggerWordOfReason(reason) {
|
|
215
|
+
const m = reason.match(/^triggers?[::](.*)$/);
|
|
216
|
+
if (m === null)
|
|
217
|
+
return undefined;
|
|
218
|
+
const v = m[1].trim();
|
|
219
|
+
return /^[\d.+-]+$/.test(v) ? '' : v;
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* slug/title 词面,含分隔符子词(`cs-geely-voice-agent` → `voice`/`agent`):
|
|
223
|
+
* query 里的连字符词(voice-agent)与 slug 复合词永远不相等,实体判定必须
|
|
224
|
+
* 下探到子词才有交集;CJK 已由 tokenize 的二元切分覆盖。
|
|
225
|
+
*/
|
|
226
|
+
function subtokenSurface(text) {
|
|
227
|
+
const out = new Set();
|
|
228
|
+
for (const t of tokenize(text)) {
|
|
229
|
+
out.add(t);
|
|
230
|
+
if (/[+#.-]/.test(t)) {
|
|
231
|
+
for (const sub of t.split(/[+#.-]+/))
|
|
232
|
+
if (sub.length >= 2)
|
|
233
|
+
out.add(sub);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
return out;
|
|
237
|
+
}
|
|
238
|
+
function tokenMatchesSurface(token, surface) {
|
|
239
|
+
const t = token.toLowerCase();
|
|
240
|
+
if (surface.has(t))
|
|
241
|
+
return true;
|
|
242
|
+
if (/[+#.-]/.test(t)) {
|
|
243
|
+
for (const sub of t.split(/[+#.-]+/))
|
|
244
|
+
if (sub.length >= 2 && surface.has(sub))
|
|
245
|
+
return true;
|
|
246
|
+
}
|
|
247
|
+
return false;
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Strict display matcher for why-line attribution: a compound query token
|
|
251
|
+
* counts as a title/weak word only when EVERY separator part ties to the
|
|
252
|
+
* surface — `voice-agent` matches `cs-geely-voice-agent`, but
|
|
253
|
+
* `cs-geely-alert-manager-api` must not match it via the shared `cs`.
|
|
254
|
+
*/
|
|
255
|
+
function tokenMatchesSurfaceStrict(token, surface) {
|
|
256
|
+
const t = token.toLowerCase();
|
|
257
|
+
if (surface.has(t))
|
|
258
|
+
return true;
|
|
259
|
+
if (!/[+#.-]/.test(t))
|
|
260
|
+
return false;
|
|
261
|
+
const subs = t.split(/[+#.-]+/).filter((s) => s.length >= 2);
|
|
262
|
+
return subs.length > 0 && subs.every((s) => surface.has(s));
|
|
263
|
+
}
|
|
264
|
+
/** Query tokens (original spelling, query order) with a词面 tie to the surface. */
|
|
265
|
+
function matchedQueryTokens(queryTokens, surfaceText) {
|
|
266
|
+
const surface = subtokenSurface(surfaceText);
|
|
267
|
+
const out = [];
|
|
268
|
+
for (const tok of queryTokens) {
|
|
269
|
+
if (!out.includes(tok) && tokenMatchesSurfaceStrict(tok, surface))
|
|
270
|
+
out.push(tok);
|
|
271
|
+
}
|
|
272
|
+
return out;
|
|
273
|
+
}
|
|
274
|
+
/** Entity-anchored candidate: its slug/title surface shares a query token
|
|
275
|
+
* (验证波次修正——A③ 场景实证:词法第 3 名恰是 query 点名实体时,≤2 席
|
|
276
|
+
* 会把任务对象整体剪掉;实体锚定者不受席帽约束,仍受总预算约束)。 */
|
|
277
|
+
function isEntityAnchored(queryTokens, c) {
|
|
278
|
+
if (queryTokens.length === 0)
|
|
279
|
+
return false;
|
|
280
|
+
const surface = subtokenSurface(`${c.slug} ${c.title}`);
|
|
281
|
+
for (const tok of queryTokens) {
|
|
282
|
+
if (tokenMatchesSurface(tok, surface))
|
|
283
|
+
return true;
|
|
284
|
+
}
|
|
285
|
+
return false;
|
|
286
|
+
}
|
|
287
|
+
function hasEntityOverlap(queryTokens, candidates) {
|
|
288
|
+
if (queryTokens.length === 0)
|
|
289
|
+
return false;
|
|
290
|
+
for (const c of candidates) {
|
|
291
|
+
const surface = subtokenSurface(`${c.slug} ${c.title}`);
|
|
292
|
+
for (const tok of queryTokens) {
|
|
293
|
+
if (tokenMatchesSurface(tok, surface))
|
|
294
|
+
return true;
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
return false;
|
|
298
|
+
}
|
|
299
|
+
function isTrivialQuery(query, queryTokens) {
|
|
300
|
+
if (queryTokens.length <= 3)
|
|
301
|
+
return true;
|
|
302
|
+
const stripped = query.replace(/\s+/g, '');
|
|
303
|
+
return stripped.length > 0 && stripped.length <= PACKAGE_TRIVIAL_QUERY_CHARS;
|
|
304
|
+
}
|
|
305
|
+
/** Stable within-layer order: score desc, then usage, then input order. */
|
|
306
|
+
function rankStable(list, usage) {
|
|
307
|
+
return list
|
|
308
|
+
.map((c, i) => ({ c, i, u: usage?.get(c.slug) ?? 0 }))
|
|
309
|
+
.sort((a, b) => b.c.score - a.c.score || b.u - a.u || a.i - b.i)
|
|
310
|
+
.map((x) => x.c);
|
|
311
|
+
}
|
|
312
|
+
/** Machine-assembled why line (A3 决议 2): hit channel + edge source + score. */
|
|
313
|
+
function packageWhyLine(c, queryTokens) {
|
|
314
|
+
const parts = [];
|
|
315
|
+
let triggerWord = null;
|
|
316
|
+
let triggerChannel = false;
|
|
317
|
+
let titleHit = false;
|
|
318
|
+
const fields = [];
|
|
319
|
+
for (const r of c.reasons) {
|
|
320
|
+
const tw = triggerWordOfReason(r);
|
|
321
|
+
if (tw !== undefined) {
|
|
322
|
+
if (tw === '')
|
|
323
|
+
triggerChannel = true;
|
|
324
|
+
else if (triggerWord === null)
|
|
325
|
+
triggerWord = tw;
|
|
326
|
+
continue;
|
|
327
|
+
}
|
|
328
|
+
if (r.startsWith('title:'))
|
|
329
|
+
titleHit = true;
|
|
330
|
+
else if (r.startsWith('tags:'))
|
|
331
|
+
fields.push('标签');
|
|
332
|
+
else if (r.startsWith('description:'))
|
|
333
|
+
fields.push('描述');
|
|
334
|
+
else if (r.startsWith('conclusion:'))
|
|
335
|
+
fields.push('正文');
|
|
336
|
+
else if (r.startsWith('slug:'))
|
|
337
|
+
fields.push('slug');
|
|
338
|
+
}
|
|
339
|
+
if (triggerWord !== null)
|
|
340
|
+
parts.push(`trigger「${triggerWord}」`);
|
|
341
|
+
else if (triggerChannel)
|
|
342
|
+
parts.push('trigger 命中');
|
|
343
|
+
if (titleHit) {
|
|
344
|
+
const words = matchedQueryTokens(queryTokens, `${c.slug} ${c.title}`);
|
|
345
|
+
parts.push(words.length > 0 ? `标题词「${words.slice(0, 2).join('」「')}」` : '标题词命中');
|
|
346
|
+
}
|
|
347
|
+
if (fields.length > 0)
|
|
348
|
+
parts.push(`${[...new Set(fields)].join('/')}词面命中`);
|
|
349
|
+
const via = viaNote(c.via);
|
|
350
|
+
if (via !== null)
|
|
351
|
+
parts.push(via);
|
|
352
|
+
if (parts.length === 0)
|
|
353
|
+
parts.push('词面命中');
|
|
354
|
+
return `命中: ${truncateToTokens(parts.join('、'), 32).text}(score:${c.score.toFixed(2)})`;
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* One direct-layer full entry (~120 tok): 标题+[status] + 一行实质 +
|
|
358
|
+
* 机器 why 行 + 指令式打开引导(预告源 description 优先,缺失回退结论行时
|
|
359
|
+
* 不再重复预告)。实质行是弹性段,超预算先截它(spec §2.4)。
|
|
360
|
+
*/
|
|
361
|
+
function directEntryText(c, queryTokens, budget) {
|
|
362
|
+
const head = `### ${c.title} [${c.status}]`;
|
|
363
|
+
const why = packageWhyLine(c, queryTokens);
|
|
364
|
+
const warn = c.reasons.includes('conflicted-demoted') ? '⚠ 此条存在未合并冲突,结论可能过期。' : null;
|
|
365
|
+
const openBase = `细节: topic_open "${c.slug}"`;
|
|
366
|
+
const conclusionLine = (c.conclusion ?? '').trim();
|
|
367
|
+
const substanceRaw = (conclusionLine !== '' ? conclusionLine : (c.description ?? '')).trim();
|
|
368
|
+
const previewRaw = (c.description ?? '').replace(/\s+/g, ' ').trim();
|
|
369
|
+
const lines = [head, why];
|
|
370
|
+
let substanceText = '';
|
|
371
|
+
if (substanceRaw !== '') {
|
|
372
|
+
const others = estimateTokens([head, why, openBase].join('\n')) + (warn !== null ? estimateTokens(warn) + 1 : 0);
|
|
373
|
+
const room = budget - others - 1;
|
|
374
|
+
if (room >= 8)
|
|
375
|
+
substanceText = truncateToTokens(substanceRaw, room).text;
|
|
376
|
+
}
|
|
377
|
+
if (substanceText !== '')
|
|
378
|
+
lines.push(substanceText);
|
|
379
|
+
if (warn !== null)
|
|
380
|
+
lines.push(warn);
|
|
381
|
+
let open = openBase;
|
|
382
|
+
if (previewRaw !== '' && previewRaw !== substanceText) {
|
|
383
|
+
const room = budget - estimateTokens([...lines, open].join('\n')) - 3;
|
|
384
|
+
if (room >= 6)
|
|
385
|
+
open = `${openBase},${truncateToTokens(previewRaw, room).text}`;
|
|
386
|
+
}
|
|
387
|
+
lines.push(open);
|
|
388
|
+
// Last resort for pathological heads (giant titles): shed elastic lines.
|
|
389
|
+
while (lines.length > 2 && estimateTokens(lines.join('\n')) > budget) {
|
|
390
|
+
const dropWarn = lines.indexOf(warn ?? '');
|
|
391
|
+
if (warn !== null && dropWarn !== -1)
|
|
392
|
+
lines.splice(dropWarn, 1);
|
|
393
|
+
else if (substanceText !== '' && lines.includes(substanceText))
|
|
394
|
+
lines.splice(lines.indexOf(substanceText), 1);
|
|
395
|
+
else
|
|
396
|
+
break;
|
|
397
|
+
}
|
|
398
|
+
const text = lines.join('\n');
|
|
399
|
+
return { text, usedTokens: estimateTokens(text) };
|
|
400
|
+
}
|
|
401
|
+
/** One neighborhood half-line (~40 tok): 标题 + slug + 边来源/通道标注. */
|
|
402
|
+
function neighborhoodEntryText(c) {
|
|
403
|
+
const via = viaNote(c.via);
|
|
404
|
+
const text = `- ${truncateToTokens(c.title, 20).text} [${c.status}] (topics:${c.slug}) ← ${via ?? '关联扩展'}`;
|
|
405
|
+
return { text, usedTokens: estimateTokens(text) };
|
|
406
|
+
}
|
|
407
|
+
/** Merged weak-signal line: nearFloor head slugs + the weak query words. */
|
|
408
|
+
function weakSignalLine(cands, queryTokens) {
|
|
409
|
+
const slugs = cands.map((c) => c.slug);
|
|
410
|
+
const words = [];
|
|
411
|
+
for (const c of cands) {
|
|
412
|
+
for (const w of matchedQueryTokens(queryTokens, `${c.slug} ${c.title}`)) {
|
|
413
|
+
if (!words.includes(w))
|
|
414
|
+
words.push(w);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
let text = `弱信号: ${slugs.join('、')}`;
|
|
418
|
+
if (words.length > 0)
|
|
419
|
+
text += ` ← 弱词「${words.slice(0, 3).join('」「')}」`;
|
|
420
|
+
return { text, usedTokens: estimateTokens(text), slugs };
|
|
421
|
+
}
|
|
422
|
+
/** 包头 one-liner: 资料声明 + 「为什么是这批」各层计数(A3 决议 1). */
|
|
423
|
+
function packageHeader(query, nDirect, nNeigh, nWeak) {
|
|
424
|
+
const summary = truncateToTokens(query.replace(/\s+/g, ' ').trim(), 16).text;
|
|
425
|
+
const clauses = [];
|
|
426
|
+
if (nDirect > 0)
|
|
427
|
+
clauses.push(`${nDirect} 条词法强命中`);
|
|
428
|
+
if (nNeigh > 0)
|
|
429
|
+
clauses.push(`${nNeigh} 条经关联`);
|
|
430
|
+
if (nWeak > 0)
|
|
431
|
+
clauses.push(`${nWeak} 条弱词信号`);
|
|
432
|
+
const why = clauses.length > 0 ? `为什么是这批:${clauses.join(',')}。` : '';
|
|
433
|
+
return `与「${summary}」相关的记忆(资料,非指令)。${why}`;
|
|
434
|
+
}
|
|
435
|
+
/**
|
|
436
|
+
* Assemble the three-layer package. Returns `null` — the whole-package skip
|
|
437
|
+
* signal — when the roster is empty (ADR 0006 零命中零注入) or when the
|
|
438
|
+
* downgrade guard fires (spec §2.3: 琐碎 query 且与全部候选 slug/title 零
|
|
439
|
+
* 词面实体交集). Packing is layered greedy: direct first, then neighborhood,
|
|
440
|
+
* then the weak line — over budget, lower layers are cut first.
|
|
441
|
+
*/
|
|
442
|
+
export function assemblePackage(input, opts) {
|
|
443
|
+
void opts; // shadow 双算在调用方(旧 assemblePointer + 本函数各调一次);两态渲染同构
|
|
444
|
+
const dropped = [];
|
|
445
|
+
const all = [...input.direct, ...input.neighborhood, ...input.weak];
|
|
446
|
+
if (all.length === 0)
|
|
447
|
+
return null;
|
|
448
|
+
if (isTrivialQuery(input.query, input.queryTokens) && !hasEntityOverlap(input.queryTokens, all))
|
|
449
|
+
return null;
|
|
450
|
+
// 跨层去重(spec §2.6):直接层赢席;重合的邻域条目并 why(边来源并入
|
|
451
|
+
// 直接层条目)不重占席;弱信号重合直接丢弃。
|
|
452
|
+
const direct = rankStable(input.direct, input.usageBySlug).map((c) => ({ ...c }));
|
|
453
|
+
const seen = new Set(direct.map((c) => c.slug));
|
|
454
|
+
const neighborhood = [];
|
|
455
|
+
for (const c of rankStable(input.neighborhood, input.usageBySlug)) {
|
|
456
|
+
if (seen.has(c.slug)) {
|
|
457
|
+
const host = direct.find((d) => d.slug === c.slug);
|
|
458
|
+
if (host !== undefined && host.via === undefined && c.via !== undefined)
|
|
459
|
+
host.via = c.via;
|
|
460
|
+
dropped.push({ slug: c.slug, reason: 'duplicate' });
|
|
461
|
+
continue;
|
|
462
|
+
}
|
|
463
|
+
seen.add(c.slug);
|
|
464
|
+
neighborhood.push(c);
|
|
465
|
+
}
|
|
466
|
+
const weak = [];
|
|
467
|
+
for (const c of rankStable(input.weak, input.usageBySlug)) {
|
|
468
|
+
if (seen.has(c.slug)) {
|
|
469
|
+
dropped.push({ slug: c.slug, reason: 'duplicate' });
|
|
470
|
+
continue;
|
|
471
|
+
}
|
|
472
|
+
seen.add(c.slug);
|
|
473
|
+
weak.push(c);
|
|
474
|
+
}
|
|
475
|
+
// Reserve with an upper-bound header (pre-cap counts); the final header is
|
|
476
|
+
// never longer, so the 600 cap holds after the swap.
|
|
477
|
+
let used = estimateTokens(`${PACKAGE_WRAPPER_OPEN}\n${packageHeader(input.query, direct.length, neighborhood.length, weak.length)}\n\n${PACKAGE_WRAPPER_CLOSE}`);
|
|
478
|
+
const layers = { direct: [], neighborhood: [], weak: [] };
|
|
479
|
+
const directBlocks = [];
|
|
480
|
+
for (const c of direct) {
|
|
481
|
+
if (directBlocks.length >= PACKAGE_DIRECT_MAX && !isEntityAnchored(input.queryTokens, c)) {
|
|
482
|
+
dropped.push({ slug: c.slug, reason: 'direct-cap' });
|
|
483
|
+
continue;
|
|
484
|
+
}
|
|
485
|
+
const budget = Math.min(PACKAGE_DIRECT_BUDGET, PACKAGE_TOTAL - used);
|
|
486
|
+
if (budget < 24) {
|
|
487
|
+
dropped.push({ slug: c.slug, reason: 'total-budget' });
|
|
488
|
+
continue;
|
|
489
|
+
}
|
|
490
|
+
const block = directEntryText(c, input.queryTokens, budget);
|
|
491
|
+
if (used + block.usedTokens > PACKAGE_TOTAL) {
|
|
492
|
+
dropped.push({ slug: c.slug, reason: 'total-budget' });
|
|
493
|
+
continue;
|
|
494
|
+
}
|
|
495
|
+
directBlocks.push(block.text);
|
|
496
|
+
layers.direct.push(c.slug);
|
|
497
|
+
used += block.usedTokens;
|
|
498
|
+
}
|
|
499
|
+
const neighBlocks = [];
|
|
500
|
+
for (const c of neighborhood) {
|
|
501
|
+
if (neighBlocks.length >= PACKAGE_NEIGHBOR_MAX) {
|
|
502
|
+
dropped.push({ slug: c.slug, reason: 'neighborhood-cap' });
|
|
503
|
+
continue;
|
|
504
|
+
}
|
|
505
|
+
const budget = Math.min(PACKAGE_NEIGHBOR_BUDGET, PACKAGE_TOTAL - used);
|
|
506
|
+
if (budget < 16) {
|
|
507
|
+
dropped.push({ slug: c.slug, reason: 'total-budget' });
|
|
508
|
+
continue;
|
|
509
|
+
}
|
|
510
|
+
const block = neighborhoodEntryText(c);
|
|
511
|
+
if (used + block.usedTokens > PACKAGE_TOTAL) {
|
|
512
|
+
dropped.push({ slug: c.slug, reason: 'total-budget' });
|
|
513
|
+
continue;
|
|
514
|
+
}
|
|
515
|
+
neighBlocks.push(block.text);
|
|
516
|
+
layers.neighborhood.push(c.slug);
|
|
517
|
+
used += block.usedTokens;
|
|
518
|
+
}
|
|
519
|
+
const weakTake = weak.slice(0, PACKAGE_WEAK_MAX);
|
|
520
|
+
for (const c of weak.slice(PACKAGE_WEAK_MAX))
|
|
521
|
+
dropped.push({ slug: c.slug, reason: 'weak-cap' });
|
|
522
|
+
let weakText = null;
|
|
523
|
+
if (weakTake.length > 0) {
|
|
524
|
+
const full = weakSignalLine(weakTake, input.queryTokens);
|
|
525
|
+
if (used + full.usedTokens <= PACKAGE_TOTAL) {
|
|
526
|
+
weakText = full.text;
|
|
527
|
+
layers.weak = full.slugs;
|
|
528
|
+
used += full.usedTokens;
|
|
529
|
+
}
|
|
530
|
+
else if (weakTake.length > 1) {
|
|
531
|
+
const single = weakSignalLine(weakTake.slice(0, 1), input.queryTokens);
|
|
532
|
+
if (used + single.usedTokens <= PACKAGE_TOTAL) {
|
|
533
|
+
weakText = single.text;
|
|
534
|
+
layers.weak = single.slugs;
|
|
535
|
+
used += single.usedTokens;
|
|
536
|
+
for (const slug of weakTake.slice(1).map((c) => c.slug))
|
|
537
|
+
dropped.push({ slug, reason: 'total-budget' });
|
|
538
|
+
}
|
|
539
|
+
else {
|
|
540
|
+
for (const slug of full.slugs)
|
|
541
|
+
dropped.push({ slug, reason: 'total-budget' });
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
else {
|
|
545
|
+
for (const slug of full.slugs)
|
|
546
|
+
dropped.push({ slug, reason: 'total-budget' });
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
const parts = [packageHeader(input.query, layers.direct.length, layers.neighborhood.length, layers.weak.length)];
|
|
550
|
+
if (directBlocks.length > 0)
|
|
551
|
+
parts.push(['### 直接相关', ...directBlocks].join('\n\n'));
|
|
552
|
+
if (neighBlocks.length > 0)
|
|
553
|
+
parts.push(['### 邻域', ...neighBlocks].join('\n'));
|
|
554
|
+
if (weakText !== null)
|
|
555
|
+
parts.push(weakText);
|
|
556
|
+
if (parts.length === 1)
|
|
557
|
+
return null; // everything budget-cut → 零命中零注入
|
|
558
|
+
const text = `${PACKAGE_WRAPPER_OPEN}\n${parts.join('\n\n')}\n${PACKAGE_WRAPPER_CLOSE}`;
|
|
559
|
+
return {
|
|
560
|
+
text,
|
|
561
|
+
usedTokens: estimateTokens(text),
|
|
562
|
+
included: [...layers.direct, ...layers.neighborhood, ...layers.weak],
|
|
563
|
+
dropped,
|
|
564
|
+
layers,
|
|
565
|
+
};
|
|
566
|
+
}
|
package/lib/distill.d.ts
CHANGED
|
@@ -37,6 +37,8 @@ export interface DistillOp {
|
|
|
37
37
|
depends?: string[];
|
|
38
38
|
open_questions?: string[];
|
|
39
39
|
impact?: string[];
|
|
40
|
+
/** Semantic-association targets (A2): existing slugs or same-batch op slugs. */
|
|
41
|
+
links?: string[];
|
|
40
42
|
conclusion?: string;
|
|
41
43
|
recommendations?: string;
|
|
42
44
|
status?: string;
|
|
@@ -103,6 +105,27 @@ export declare class Distiller {
|
|
|
103
105
|
* escape hatch belongs to the main pass).
|
|
104
106
|
*/
|
|
105
107
|
private correctiveRetry;
|
|
108
|
+
/**
|
|
109
|
+
* The A6 §5.1 schema gate, applied to the parsed batch BEFORE any write:
|
|
110
|
+
* create ops must carry description + triggers 3-8 条 (the prompt's standing
|
|
111
|
+
* requirement, now enforced). Deficient creates get exactly ONE 补问 retry
|
|
112
|
+
* that re-asks for just those ops completed — budget-guarded exactly like
|
|
113
|
+
* the corrective ids retry (`retrySpent` reports the extra call). Every
|
|
114
|
+
* still-deficient op is dropped and comes back as a SchemaDrop carrying the
|
|
115
|
+
* ledger kind: `distill-op-invalid` after a used-but-unsuccessful retry,
|
|
116
|
+
* `distill-op-retry-exhausted` when no retry could run or the retry call
|
|
117
|
+
* itself failed. Dropped ops' observations stay unconsumed — the existing
|
|
118
|
+
* GC/corrective path accounts for them, never a silent loss. Update ops
|
|
119
|
+
* keep their narrower contract (slug only).
|
|
120
|
+
*/
|
|
121
|
+
private enforceSchema;
|
|
122
|
+
/**
|
|
123
|
+
* The one schema 补问: re-ask for exactly the deficient creates, completed.
|
|
124
|
+
* Returns key→op for what the model re-emitted (matched by slugified title),
|
|
125
|
+
* or undefined when the call itself failed / output was unparseable — the
|
|
126
|
+
* caller then ledgeres `distill-op-retry-exhausted` for every deficient op.
|
|
127
|
+
*/
|
|
128
|
+
private schemaRetryCall;
|
|
106
129
|
/**
|
|
107
130
|
* Execute a batch's ops with observed_ids sanitized upfront. A scalar
|
|
108
131
|
* observed_ids string (the commonest model shape drift) is normalized to a
|
|
@@ -114,8 +137,24 @@ export declare class Distiller {
|
|
|
114
137
|
* failures (missing fields, unknown update slug) keep the per-op try/catch
|
|
115
138
|
* isolation — one bad op never sinks the batch, and a stall they cause is
|
|
116
139
|
* NOT attributed to observed_ids (no corrective retry for those).
|
|
140
|
+
*
|
|
141
|
+
* A2 links: every link target is whitelist-checked against `knownSlugs`
|
|
142
|
+
* (existing slugs ∪ same-batch op slugs); rejected refs are stripped and
|
|
143
|
+
* ledgered (`link-ref-rejected`), survivors ride the op's topic write into
|
|
144
|
+
* the store transaction (先落 topic 再建边 — one write, no separate edge
|
|
145
|
+
* pass). The set is locally seeded with this call's predicted op slugs and
|
|
146
|
+
* grows as creates land, so same-batch references resolve in op order.
|
|
117
147
|
*/
|
|
118
148
|
private applyOps;
|
|
149
|
+
/**
|
|
150
|
+
* A2 links whitelist: a link survives only when its normalized target is a
|
|
151
|
+
* slug that already exists or belongs to this batch (`knownSlugs`), and not
|
|
152
|
+
* the op's own topic. Everything else is stripped and ledgered
|
|
153
|
+
* (`link-ref-rejected` — a dead edge must at least leave a trace). Returns
|
|
154
|
+
* the surviving targets (undefined when none — no Links section is written)
|
|
155
|
+
* plus the rejection count for the run detail.
|
|
156
|
+
*/
|
|
157
|
+
private acceptLinks;
|
|
119
158
|
}
|
|
120
159
|
/** Extract the first balanced JSON object from model output (tolerates fences). */
|
|
121
160
|
export declare function parseOps(raw: string): DistillOp[];
|