dsh-cross-memory 0.2.6 → 0.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -39,18 +39,20 @@ import { listReflections, previousInsights, reflectionDue, runReflection, writeR
39
39
  import { parseTimeRange } from './time.js';
40
40
  import { isSubstantiveTurn } from './query.js';
41
41
  import { INDEX_OPEN, MEMORY_CLOSE, MEMORY_OPEN, RECALL_OPEN, rankForSummary, renderEntry, renderHit, renderMemoryIndex, renderMemorySummaryResult, renderOpenLoops, renderRecall, renderScopeListing, selectForSummary } from './render.js';
42
+ import { createBm25Index } from './bm25.js';
42
43
  import { findProjectRoot, isWithin } from './workspace.js';
43
44
  import { citationRoots, citationWarning, ignoredUnder, missingCitations } from './citations.js';
44
45
  import { planRetention, retentionKey } from './retention.js';
45
46
  import { MemoryLog, createFileSink, createLogExporter, pluginLogger } from './log.js';
46
47
  import { collectExtractionWindow, collectWindow, resolveLlmRoute, runExtraction, selectKnownTitles } from './extract.js';
47
- import { collectExcerpts } from './raw-recall.js';
48
+ import { collectExcerpts, collectRagExcerpts } from './raw-recall.js';
48
49
  import { decodeSessionLog, findSessionLogs, parseSessionLog, planWindows, zstdAvailable } from './backfill.js';
49
50
  import { backgroundDelayMs, cappedBackoffMs, extractionDelayMs, formatDelay, parsePeakHours, peakDelayMs } from './schedule.js';
50
51
  import { CONSOLIDATE_PRESET_ID, adjudicateDisputes, applyPlan, applyVerdicts, classifyPlan, clearPendingPlan, conflictDisputes, denyToolsFor, hasApplicableFragment, mergePendingPlan, pinExistingScopes, proposalIsFresh, readPendingPlan, runConsolidation, runConsolidationDirect, selectForConsolidation, writePendingPlan } from './consolidate.js';
51
52
  import { discardDraft, listDrafts, promote, writeDraft } from './skills.js';
52
53
  import { MEMORY_KINDS, MEMORY_SOURCE_KIND } from './types.js';
53
54
  import { registerMemoryTool } from './tool.js';
55
+ import { PROPOSAL_ACTION, PROPOSAL_SKILL, registerProposalCard } from './cards.js';
54
56
  import { REMOTE_CONTRIBUTION, REMOTE_NAMESPACE, REMOTE_SERVICE, createRemoteService } from './remote.js';
55
57
  /** Plugin name; also the source tag of every injected message. */
56
58
  export const name = 'memories';
@@ -679,14 +681,55 @@ export class MemoriesRuntime {
679
681
  const projectHasEntries = states.some((state) => state.scope === 'project' && state.entries.length > 0);
680
682
  const globalCap = projectHasEntries ? this.settings.globalSummaryEntries : this.settings.maxSummaryEntries;
681
683
  const capOf = (state) => state.scope === 'global' ? globalCap : this.settings.maxSummaryEntries;
682
- const selected = states.map((state) => selectForSummary(state.entries, capOf(state), {
683
- freshSlots: this.settings.summaryFreshSlots,
684
- // The opening turn is the only topic signal available this early, and it
685
- // is what keeps a globally scoped memory that shares nothing with this
686
- // conversation from outranking one that does.
687
- ...query === undefined || query.length === 0 ? {} : { query },
688
- }));
689
- const scopes = states.map((state, index) => ({
684
+ // Project memories render before global ones.
685
+ //
686
+ // The renderer walks the scopes in order and the byte budget keeps the head,
687
+ // so this is the decision about which memories a session actually reads.
688
+ // Measured on 20 real sessions with a live store: the first six rendered
689
+ // slots held 113 entries the session's own topic matched when project led,
690
+ // against 14 with global first — global's generic entries were occupying
691
+ // every slot the budget reliably reaches. Global keeps its own smaller cap
692
+ // and its own byte budget, so it is not crowded out, just no longer first.
693
+ const ordered = [
694
+ ...states.filter((state) => state.scope === 'project'),
695
+ ...states.filter((state) => state.scope === 'global'),
696
+ ];
697
+ // Rank the scopes together, then let each scope pick from that order.
698
+ //
699
+ // Ranking per scope is what the renderer used to do, and it loses the
700
+ // cross-scope comparison: a global entry that shares a word with the opening
701
+ // turn outranks a project entry the turn is about, because each scope's top
702
+ // is taken without reference to the other. The merged ranking's first
703
+ // twelve entries measured 96% topic-relevant on 20 real sessions, against
704
+ // 67% for the per-scope rendering of the same store.
705
+ const stateOf = new Map();
706
+ for (const state of ordered)
707
+ for (const entry of state.entries)
708
+ stateOf.set(entry.id, state);
709
+ const merged = rankForSummary(ordered.flatMap((state) => state.entries), Date.now(), query);
710
+ const rankedByState = new Map();
711
+ for (const entry of merged) {
712
+ const state = stateOf.get(entry.id);
713
+ if (state === undefined)
714
+ continue;
715
+ const list = rankedByState.get(state);
716
+ if (list === undefined)
717
+ rankedByState.set(state, [entry]);
718
+ else
719
+ list.push(entry);
720
+ }
721
+ const selected = ordered.map((state) => {
722
+ const ranked = rankedByState.get(state);
723
+ return selectForSummary(state.entries, capOf(state), {
724
+ freshSlots: this.settings.summaryFreshSlots,
725
+ // The opening turn is the only topic signal available this early, and it
726
+ // is what keeps a globally scoped memory that shares nothing with this
727
+ // conversation from outranking one that does.
728
+ ...query === undefined || query.length === 0 ? {} : { query },
729
+ ...ranked === undefined ? {} : { ranked },
730
+ });
731
+ });
732
+ const scopes = ordered.map((state, index) => ({
690
733
  label: state.label,
691
734
  heading: state.heading,
692
735
  entries: selected[index] ?? [],
@@ -841,7 +884,8 @@ export class MemoriesRuntime {
841
884
  * Apply every waiting decision.
842
885
  *
843
886
  * @param _parent - the agent asking; the stored rows carry their own scope.
844
- * @returns a human-readable summary, or `undefined` when nothing is staged.
887
+ * @returns the command's report plus the counts the action-card decision
888
+ * records, or `undefined` when nothing is staged.
845
889
  */
846
890
  async applyPendingPlan(_parent) {
847
891
  const pending = await readPendingPlan(this.store.memoriesDir);
@@ -853,14 +897,31 @@ export class MemoriesRuntime {
853
897
  const result = await applyPlan(pending.plan, this.consolidationTarget(), root, { entries });
854
898
  await clearPendingPlan(this.store.memoriesDir);
855
899
  this.log.info('dsh-cross-memory: applied %d waiting consolidation decision(s): %d written, %d retired', pending.disputes.length, result.written, result.retired);
856
- return `Applied ${pending.disputes.length} decision${pending.disputes.length === 1 ? '' : 's'}: ${result.written} written, ${result.retired} retired.`;
900
+ return {
901
+ text: `Applied ${pending.disputes.length} decision${pending.disputes.length === 1 ? '' : 's'}: ${result.written} written, ${result.retired} retired.`,
902
+ written: result.written,
903
+ retired: result.retired,
904
+ };
857
905
  }
858
906
  catch (error) {
859
907
  const message = error instanceof Error ? error.message : String(error);
860
908
  this.log.warn('dsh-cross-memory: applying the waiting decisions failed: %s', message);
861
- return `Applying them failed and the store was rolled back: ${message}`;
909
+ return { text: `Applying them failed and the store was rolled back: ${message}`, written: 0, retired: 0 };
862
910
  }
863
911
  }
912
+ /**
913
+ * Discard every waiting decision, leaving the store untouched.
914
+ *
915
+ * @returns how many decisions were dropped, or `undefined` when nothing was staged.
916
+ */
917
+ async rejectPendingPlan() {
918
+ const pending = await readPendingPlan(this.store.memoriesDir);
919
+ if (pending === undefined)
920
+ return undefined;
921
+ await clearPendingPlan(this.store.memoriesDir);
922
+ this.log.info('dsh-cross-memory: discarded %d waiting consolidation decision(s)', pending.disputes.length);
923
+ return pending.disputes.length;
924
+ }
864
925
  /**
865
926
  * A warning when this workspace's memory directory is shared with another
866
927
  * repository of the same name.
@@ -917,6 +978,11 @@ export class MemoriesRuntime {
917
978
  // retire" and nobody could see that 17 decisions were waiting.
918
979
  const needDecision = pending.disputes.length > 0 ? `, ${pending.disputes.length} need you` : '';
919
980
  lines.push(`Pending consolidation proposal for ${pending.label}: ${pending.plan.upserts.length} to write, ${pending.plan.retire.length} to retire${needDecision} — review with /memories plan, then /memories apply or /memories reject.`);
981
+ // The card is the in-answer path to the same question, but only the model
982
+ // decides to offer it: the skill has to be loaded in the turn and the
983
+ // block has to be the last thing in the answer. Naming the exact fields
984
+ // here is what keeps count/stagedAt honest instead of invented.
985
+ lines.push(`When the user asks about memory changes or pending decisions (记忆变更 / 待确认 / 待裁决), load the ${PROPOSAL_SKILL} skill first, then end the final answer with one \`action-card\` block for this proposal: action "${PROPOSAL_ACTION}", label ${JSON.stringify(pending.label)}, count ${pending.disputes.length}, stagedAt ${pending.at}.`);
920
986
  }
921
987
  // `dshHome` filters out drafts whose promoted copy is byte-identical: the
922
988
  // banner used to report already-promoted skills as pending forever.
@@ -1228,6 +1294,12 @@ export class MemoriesRuntime {
1228
1294
  if (this.sessionOff(session))
1229
1295
  return undefined;
1230
1296
  const query = this.latestUserText(session);
1297
+ // The full-history channel is computed before the eligibility gate: a turn
1298
+ // with no matching memory still has its original conversation in the logs,
1299
+ // and the gate returning nothing must not hide that.
1300
+ const ragExcerpts = query !== undefined && this.settings.ragRecall && this.settings.ragRecallBytes > 0
1301
+ ? await this.ragExcerpts(query, session.id)
1302
+ : [];
1231
1303
  // A one-word acknowledgement has nothing a memory could be about; skipping it
1232
1304
  // also avoids a full store scan on every "好" the user types.
1233
1305
  if (query === undefined || !isSubstantiveTurn(query))
@@ -1256,10 +1328,14 @@ export class MemoriesRuntime {
1256
1328
  //
1257
1329
  // The seeds for the one-hop expansion are taken after this sort for the same
1258
1330
  // reason: they used to be whichever three candidates the store listed first.
1259
- const byStrength = (left, right) => right.relevance - left.relevance
1331
+ const byStrength = (left, right) => right.bm25 - left.bm25
1332
+ || right.relevance - left.relevance
1260
1333
  || right.score - left.score
1261
1334
  || right.entry.updatedAt - left.entry.updatedAt
1262
1335
  || left.entry.title.localeCompare(right.entry.title);
1336
+ // One BM25 index over every entry the turn can see, so a global and a
1337
+ // project entry are ranked on the same document frequencies.
1338
+ const bm25Scores = createBm25Index(states.flatMap((state) => state.entries)).score(query);
1263
1339
  const eligible = [];
1264
1340
  let near;
1265
1341
  for (const state of states) {
@@ -1285,10 +1361,23 @@ export class MemoriesRuntime {
1285
1361
  }
1286
1362
  continue;
1287
1363
  }
1288
- eligible.push({ entry, ...why });
1364
+ eligible.push({ entry, ...why, bm25: bm25Scores.get(entry.id) ?? 0 });
1289
1365
  }
1290
1366
  }
1291
1367
  if (eligible.length === 0) {
1368
+ // Nothing in the store answers this turn. The raw channel still can: the
1369
+ // fact the extraction dropped is in the transcript, not in the store.
1370
+ if (ragExcerpts.length > 0) {
1371
+ const text = renderRecall([], this.settings.recallMaxBytes + this.settings.ragRecallBytes, [], ragExcerpts);
1372
+ if (text !== undefined) {
1373
+ this.recallCounts.set(session, used + 1);
1374
+ this.log.info('dsh-cross-memory: session %s recalled no memory, used %d raw excerpt(s) from the full history', session.id, ragExcerpts.length);
1375
+ return createUserMessage({
1376
+ content: [{ type: 'text', text }],
1377
+ source: { kind: MEMORY_SOURCE_KIND, form: 'recall' },
1378
+ });
1379
+ }
1380
+ }
1292
1381
  // Alias fallback, before the archive is consulted.
1293
1382
  //
1294
1383
  // The strict gate asks for two pieces of evidence, and a turn that names a
@@ -1315,7 +1404,7 @@ export class MemoriesRuntime {
1315
1404
  ...hub === undefined ? {} : { hub },
1316
1405
  });
1317
1406
  if (why.about)
1318
- byAlias.push({ entry, ...why });
1407
+ byAlias.push({ entry, ...why, bm25: bm25Scores.get(entry.id) ?? 0 });
1319
1408
  }
1320
1409
  }
1321
1410
  if (byAlias.length > 0) {
@@ -1407,6 +1496,7 @@ export class MemoriesRuntime {
1407
1496
  relevance: 0,
1408
1497
  score: hit.score,
1409
1498
  best: '',
1499
+ bm25: 0,
1410
1500
  evidence: { strongTerms: 0, phrase: false },
1411
1501
  });
1412
1502
  }
@@ -1426,7 +1516,7 @@ export class MemoriesRuntime {
1426
1516
  break;
1427
1517
  picked.push(candidate);
1428
1518
  }
1429
- if (picked.length === 0)
1519
+ if (picked.length === 0 && ragExcerpts.length === 0)
1430
1520
  return undefined;
1431
1521
  // The second retrieval channel: original turns from the sessions these
1432
1522
  // memories came from, so a detail the extraction dropped can still be read.
@@ -1434,7 +1524,12 @@ export class MemoriesRuntime {
1434
1524
  const excerpts = this.settings.rawRecall && this.settings.rawRecallBytes > 0
1435
1525
  ? await this.rawExcerpts(picked.map((item) => item.entry), query)
1436
1526
  : [];
1437
- const text = renderRecall(picked.map((item) => item.entry), this.settings.recallMaxBytes, [], excerpts);
1527
+ // The raw half has its own budget: the memory half's `recallMaxBytes` is
1528
+ // spent on memories, and sharing it would drop every excerpt whenever a
1529
+ // conversation recalls several entries — measured, the excerpts were cut in
1530
+ // exactly the turns that needed them.
1531
+ const recallBudget = this.settings.recallMaxBytes + (ragExcerpts.length > 0 ? this.settings.ragRecallBytes : 0);
1532
+ const text = renderRecall(picked.map((item) => item.entry), recallBudget, [], [...excerpts, ...ragExcerpts]);
1438
1533
  if (text === undefined)
1439
1534
  return undefined;
1440
1535
  // Info, not `decision`: a delta is the rarer half of this path — at most
@@ -1477,6 +1572,17 @@ export class MemoriesRuntime {
1477
1572
  * @param query - the current user turn.
1478
1573
  * @returns scrubbed excerpts, empty when disabled or unavailable.
1479
1574
  */
1575
+ async ragExcerpts(query, sessionId) {
1576
+ if (this.settings.ragRecallExcerpts <= 0)
1577
+ return [];
1578
+ return await collectRagExcerpts(join(this.deployment.dshHome, 'sessions'), query, {
1579
+ maxExcerpts: this.settings.ragRecallExcerpts,
1580
+ maxBytes: this.settings.ragRecallBytes,
1581
+ maxChars: this.settings.ragRecallChars,
1582
+ maxSessions: this.settings.ragRecallSessions,
1583
+ excludeSessionId: sessionId,
1584
+ }).catch(() => []);
1585
+ }
1480
1586
  async rawExcerpts(entries, query) {
1481
1587
  if (this.settings.rawRecallExcerpts <= 0)
1482
1588
  return [];
@@ -2507,6 +2613,7 @@ export class MemoriesRuntime {
2507
2613
  : {},
2508
2614
  maxOutputTokens: this.settings.extractMaxOutputTokens,
2509
2615
  maxMemories: this.settings.extractMaxMemories,
2616
+ recordScope: this.settings.recordScope,
2510
2617
  timeoutMs: this.settings.extractTimeoutMs,
2511
2618
  signal,
2512
2619
  });
@@ -2746,6 +2853,7 @@ export class MemoriesRuntime {
2746
2853
  model,
2747
2854
  maxOutputTokens: this.settings.extractMaxOutputTokens,
2748
2855
  maxMemories: this.settings.extractMaxMemories,
2856
+ recordScope: this.settings.recordScope,
2749
2857
  timeoutMs: this.settings.extractTimeoutMs,
2750
2858
  signal: this.lifecycle.signal,
2751
2859
  });
@@ -3059,12 +3167,17 @@ export class MemoriesRuntime {
3059
3167
  /**
3060
3168
  * Speak without being asked, when there is something to say.
3061
3169
  *
3062
- * Two deterministic triggers only, for now: a daily line about what the plugin
3063
- * maintained, and a warning when decisions have waited long enough that the
3064
- * pending panel will drop them. Both are judgements a rule can make, which is
3065
- * why they are the first ones allowed to interrupt. Everything smarter (open
3066
- * loops, reflections) enters here later through the same queue, and the same
3067
- * rules apply: evidence or silence, and never the same subject twice.
3170
+ * Two deterministic triggers: a daily line about what the plugin maintained,
3171
+ * and a promise whose deadline has passed. Both are judgements a rule can
3172
+ * make, which is why they are the ones allowed to interrupt. Everything
3173
+ * smarter (reflections) enters here later through the same queue, and the
3174
+ * same rules apply: evidence or silence, and never the same subject twice.
3175
+ *
3176
+ * A staged consolidation proposal no longer comes through this pump: its
3177
+ * backlog branch could not reach the user in this deployment (macOS
3178
+ * `osascript` is unavailable, so every delivery logged `no channel for notice
3179
+ * backlog`), and the answer card plus the injected draft note are the
3180
+ * confirmation path now.
3068
3181
  *
3069
3182
  * Called from the once-per-conversation hook and from the maintenance sweep. A
3070
3183
  * failure is logged and swallowed: speaking is never allowed to break a turn.
@@ -3109,25 +3222,7 @@ export class MemoriesRuntime {
3109
3222
  queue = { ...queue, lastDigestAt: now };
3110
3223
  }
3111
3224
  }
3112
- // 2. Backlog warning: unanswered decisions go stale and are dropped.
3113
- const pending = await readPendingPlan(dir).catch(() => undefined);
3114
- if (pending !== undefined && now - pending.at >= 12 * 3_600_000) {
3115
- const age = Math.round((now - pending.at) / 3_600_000);
3116
- const admitted = admitNotice(queue, {
3117
- kind: 'backlog',
3118
- createdAt: now,
3119
- dueAt: now,
3120
- title: `有 ${pending.disputes.length} 条记忆变更等你确认(已等 ${age} 小时,超时会丢弃)`,
3121
- body: pending.disputes.map((row) => `- [${row.action}] ${row.title}:${row.reason}`).join('\n'),
3122
- evidence: pending.disputes.map((row) => row.id),
3123
- dedupeKey: `backlog:${pending.disputes.length}`,
3124
- }, policy);
3125
- if (admitted.ok)
3126
- queue = { ...queue, notices: [admitted.notice, ...queue.notices] };
3127
- else
3128
- this.log.decision('dsh-cross-memory: notice suppressed (%s)', admitted.reason);
3129
- }
3130
- // 3. Open loops whose deadline has passed. This is the trigger that makes
3225
+ // 2. Open loops whose deadline has passed. This is the trigger that makes
3131
3226
  // the assistant pro-active rather than reactive: it needs no question to
3132
3227
  // answer, only a promise the user made and has not closed.
3133
3228
  const loopNow = pruneLoops(await readLoops(dir), now);
@@ -4235,6 +4330,35 @@ export function apply(ctx, config = {}) {
4235
4330
  });
4236
4331
  runtime = new MemoriesRuntime(ctx, config, read);
4237
4332
  ctx.effect(() => () => runtime.dispose(), 'dsh-cross-memory.lifecycle');
4333
+ // A staged consolidation proposal can also wait as an answer-embedded action
4334
+ // card: the model offers it from its skill, and the buttons apply or discard
4335
+ // the whole batch. Both services are optional, and an older action-card
4336
+ // service has no `skillProvider`; in either case the command and the settings
4337
+ // panel stay the only confirmation paths, which is the degradation this
4338
+ // plugin has always supported.
4339
+ ctx.inject(['actionCards', 'skills'], (child) => {
4340
+ const { actionCards, skills } = child;
4341
+ if (actionCards === undefined || skills === undefined)
4342
+ return;
4343
+ if (typeof actionCards.skillProvider !== 'function') {
4344
+ log.info('dsh-cross-memory: the action-card service predates answer cards; the confirmation card is skipped');
4345
+ return;
4346
+ }
4347
+ const seam = {
4348
+ pending: async () => {
4349
+ const pending = await readPendingPlan(runtime.store.memoriesDir).catch(() => undefined);
4350
+ return pending === undefined
4351
+ ? undefined
4352
+ : { label: pending.label, count: pending.disputes.length, stagedAt: pending.at };
4353
+ },
4354
+ apply: async (agent) => {
4355
+ const result = await runtime.applyPendingPlan(agent);
4356
+ return result === undefined ? undefined : { written: result.written, retired: result.retired };
4357
+ },
4358
+ reject: () => runtime.rejectPendingPlan(),
4359
+ };
4360
+ child.effect(() => registerProposalCard(actionCards, skills, seam), 'dsh-cross-memory.proposalCard');
4361
+ });
4238
4362
  // The consolidation child needs a composition of its own. Since 0.2.1-rc.2 a
4239
4363
  // subagent takes its tool set from the preset it names, and a child that
4240
4364
  // names none inherits the parent's composition — the parent's tools, which is
@@ -4619,11 +4743,13 @@ async function handleCommand(runtime, invocation) {
4619
4743
  }
4620
4744
  case 'apply': {
4621
4745
  const summary = await runtime.applyPendingPlan(invocation.agent);
4622
- return { kind: 'success', text: summary ?? 'No consolidation proposal is waiting.' };
4746
+ return { kind: 'success', text: summary?.text ?? 'No consolidation proposal is waiting.' };
4623
4747
  }
4624
4748
  case 'reject': {
4625
- const dropped = await clearPendingPlan(runtime.store.memoriesDir);
4626
- return { kind: 'success', text: dropped ? 'Discarded the pending consolidation proposal. The store is unchanged.' : 'No consolidation proposal is waiting.' };
4749
+ const dropped = await runtime.rejectPendingPlan();
4750
+ return dropped === undefined
4751
+ ? { kind: 'success', text: 'No consolidation proposal is waiting.' }
4752
+ : { kind: 'success', text: `Discarded ${dropped} waiting decision${dropped === 1 ? '' : 's'}. The store is unchanged.` };
4627
4753
  }
4628
4754
  case 'mine': {
4629
4755
  const count = await runtime.mineNow(invocation.agent);
package/lib/raw-recall.js CHANGED
@@ -232,6 +232,155 @@ export async function readTranscript(sessionsDir, sessionId, now = Date.now()) {
232
232
  * @param limits - count/character/byte caps (byte cap applies across sessions).
233
233
  * @returns excerpts with their session id filled in.
234
234
  */
235
+ /**
236
+ * Full-history RAG selection.
237
+ *
238
+ * `collectExcerpts` only reads the sessions a recalled memory came from, so it
239
+ * is anchored to the extraction. This one reads EVERY persisted session on this
240
+ * machine and picks the excerpts that lexically match the query best, which is
241
+ * what makes the raw channel a real retrieval path rather than a footnote.
242
+ *
243
+ * Zero model calls: the same tokenizer and scorer as `selectExcerpts`, so the
244
+ * cost is reading the logs (cached) and the text it injects.
245
+ *
246
+ * @param sessionsDir - `<dshHome>/sessions`.
247
+ * @param query - the current user turn.
248
+ * @param limits - same knobs as `selectExcerpts`, plus `maxSessions` to bound the
249
+ * number of logs opened.
250
+ * @returns the best matching excerpts across all sessions, empty when none match.
251
+ */
252
+ export async function collectRagExcerpts(sessionsDir, query, limits = {}) {
253
+ // 0 means every log: a cap that is too small silently drops the conversation
254
+ // that holds the answer (measured: the target sat at rank 26 with a cap of 24).
255
+ const maxSessions = limits.maxSessions === 0 ? Number.POSITIVE_INFINITY : (limits.maxSessions ?? 24);
256
+ const excludeSessionId = limits.excludeSessionId;
257
+ const maxExcerpts = limits.maxExcerpts ?? 4;
258
+ const maxChars = limits.maxChars ?? 600;
259
+ const maxBytes = limits.maxBytes ?? 2400;
260
+ const queryTokens = tokens(query);
261
+ if (queryTokens.size === 0)
262
+ return [];
263
+ const logs = await findSessionLogs(sessionsDir).catch(() => []);
264
+ // Newest first: the same score prefers the later conversation, which is the one
265
+ // a follow-up is more likely to continue.
266
+ const ordered = logs.sort((left, right) => right.modifiedAt - left.modifiedAt).slice(0, maxSessions);
267
+ // Chunk by TURN, not by message: the question that matches a passage is the
268
+ // one the answer sits under, and a per-message excerpt can only ever return
269
+ // the question back. The turn is the unit a recall is about.
270
+ const turns = [];
271
+ for (const log of ordered) {
272
+ const sessionId = normalizeSession(basename(dirname(log.file)));
273
+ // The session asking must not answer itself from its own log: the log holds
274
+ // the very turns being recalled, which reads as a perfect match and crowds
275
+ // out the earlier conversation the recall is for.
276
+ if (excludeSessionId !== undefined && sessionId === normalizeSession(excludeSessionId))
277
+ continue;
278
+ const messages = await readTranscript(sessionsDir, sessionId);
279
+ if (messages === undefined)
280
+ continue;
281
+ for (const chunk of turnChunks(messages))
282
+ turns.push({ sessionId, chunk });
283
+ }
284
+ // Document frequency across every turn in this history, so the scorer can tell
285
+ // a word that appears everywhere from a word that names the thing.
286
+ const df = new Map();
287
+ for (const turn of turns) {
288
+ for (const token of new Set(tokens(turn.chunk.text)))
289
+ df.set(token, (df.get(token) ?? 0) + 1);
290
+ }
291
+ const candidates = [];
292
+ for (const item of selectTurnExcerpts(turns.map((turn) => turn.chunk), query, df, { maxExcerpts, maxChars, maxBytes })) {
293
+ const turn = turns.find((candidate) => candidate.chunk.seq === item.excerpt.seq);
294
+ candidates.push({ excerpt: { ...item.excerpt, sessionId: turn?.sessionId ?? '' }, score: item.score });
295
+ }
296
+ // Merge across sessions by score: one conversation that happens to hold several
297
+ // matching turns must not crowd out the conversation that holds the answer.
298
+ candidates.sort((left, right) => right.score - left.score);
299
+ const out = [];
300
+ const seen = new Set();
301
+ let used = 0;
302
+ for (const item of candidates) {
303
+ if (out.length >= maxExcerpts)
304
+ break;
305
+ const key = item.excerpt.text.slice(0, 80);
306
+ if (seen.has(key))
307
+ continue;
308
+ const cost = Buffer.byteLength(item.excerpt.text, 'utf8') + 16;
309
+ if (used + cost > maxBytes)
310
+ continue;
311
+ seen.add(key);
312
+ used += cost;
313
+ out.push(item.excerpt);
314
+ }
315
+ return out;
316
+ }
317
+ /** Group a transcript into user→assistant turns, dropping turns with no prose. */
318
+ export function turnChunks(messages) {
319
+ const chunks = [];
320
+ let current;
321
+ for (const message of messages) {
322
+ if (message.role === 'user') {
323
+ if (current !== undefined && current.lines.length > 0)
324
+ chunks.push({ seq: current.seq, text: current.lines.join('\n') });
325
+ current = { seq: message.seq, lines: [message.text] };
326
+ }
327
+ else if (current !== undefined) {
328
+ current.lines.push(message.text);
329
+ }
330
+ }
331
+ if (current !== undefined && current.lines.length > 0)
332
+ chunks.push({ seq: current.seq, text: current.lines.join('\n') });
333
+ return chunks;
334
+ }
335
+ /**
336
+ * Score one turn against the query, idf-weighted.
337
+ *
338
+ * The plain shared-token count cannot tell 「同步」 from 「uk_file_invoice_sha_role」:
339
+ * both add one, and the common word wins because it appears everywhere. Weighting
340
+ * by how rare a token is across the turns in this history is what makes the
341
+ * passage that names the thing outrank the passage that mentions the topic.
342
+ *
343
+ * @param text - one turn.
344
+ * @param queryTokens - tokens of the current turn.
345
+ * @param df - how many turns contain each token.
346
+ * @param total - number of turns scored.
347
+ * @param maxChars - window size.
348
+ * @returns the best window's score.
349
+ */
350
+ function scoreTurn(text, queryTokens, df, total, maxChars) {
351
+ const window = bestWindow(text, queryTokens, maxChars);
352
+ const counts = new Map();
353
+ for (const token of tokens(window.text))
354
+ counts.set(token, (counts.get(token) ?? 0) + 1);
355
+ let score = 0;
356
+ for (const token of queryTokens) {
357
+ const tf = counts.get(token) ?? 0;
358
+ if (tf === 0)
359
+ continue;
360
+ const idf = Math.log(1 + total / (df.get(token) ?? 1));
361
+ score += (tf * (idf + 1)) / (tf + 1.5);
362
+ }
363
+ return score;
364
+ }
365
+ /** Select the best-matching turns across a whole history, idf-weighted. */
366
+ function selectTurnExcerpts(turns, query, df, limits = {}) {
367
+ const maxExcerpts = limits.maxExcerpts ?? 3;
368
+ const maxChars = limits.maxChars ?? 400;
369
+ const queryTokens = tokens(query);
370
+ if (queryTokens.size === 0)
371
+ return [];
372
+ const scored = turns
373
+ .filter((turn) => turn.text.trim().length >= 24)
374
+ .map((turn) => ({ turn, score: scoreTurn(turn.text.trim(), queryTokens, df, turns.length, maxChars) }))
375
+ .filter((item) => item.score >= 2)
376
+ .sort((left, right) => right.score - left.score)
377
+ .slice(0, maxExcerpts);
378
+ return scored.map((item) => {
379
+ const window = bestWindow(item.turn.text.trim(), queryTokens, maxChars);
380
+ const text = redactSecrets(window.text.trim()).replace(/\s+/gu, ' ').slice(0, maxChars);
381
+ return { excerpt: { sessionId: '', seq: item.turn.seq, role: 'assistant', text }, score: item.score };
382
+ }).filter((item) => item.excerpt.text.length >= 24);
383
+ }
235
384
  export async function collectExcerpts(sessionsDir, sources, query, limits = {}) {
236
385
  const maxSessions = limits.maxSessions ?? 2;
237
386
  const maxExcerpts = limits.maxExcerpts ?? 3;