@jjh32456/longlive 0.0.0-stage → 2.0.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/CHANGELOG.md +235 -0
- package/LICENSE +21 -0
- package/QUICKSTART.md +362 -0
- package/README.en.md +64 -0
- package/README.md +256 -2
- package/SPEC.md +211 -0
- package/build-info.json +1665 -0
- package/cordis.patch.yml +208 -0
- package/docs/A1-MIGRATION.md +75 -0
- package/docs/ANSWER-GUARD.md +92 -0
- package/docs/ARCHITECTURE.md +128 -0
- package/docs/AUTO-RECALL-WIRING.md +115 -0
- package/docs/AUTO-RECALL.md +237 -0
- package/docs/CONCEPTS.md +143 -0
- package/docs/CONFIG.md +839 -0
- package/docs/ERRORS.md +271 -0
- package/docs/FAQ.md +186 -0
- package/docs/FEATURES.md +579 -0
- package/docs/INDEX-FRESHNESS.md +21 -0
- package/docs/METRICS.md +244 -0
- package/docs/MIGRATION-1.6.0.md +220 -0
- package/docs/OPERATIONS.md +439 -0
- package/docs/PANEL-INTEGRATION.md +190 -0
- package/docs/PRIVACY.md +88 -0
- package/docs/QUICKSTART.md +155 -0
- package/docs/RAW-INDEX-POLICY.md +7 -0
- package/docs/README.en.md +48 -0
- package/docs/RESIDENT-WATCHER.md +90 -0
- package/docs/SESSION-WATCH.md +214 -0
- package/docs/TOOLS.md +184 -0
- package/docs/TROUBLESHOOTING.md +329 -0
- package/icon.svg +11 -0
- package/lib/client.js +436 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +163 -4
- package/runbook.md +343 -0
- package/scripts/archive-digest-build.mjs +668 -0
- package/scripts/auto-truncate-run.ps1 +752 -0
- package/scripts/backfill-auto-cards.mjs +98 -0
- package/scripts/edges-build.mjs +1003 -0
- package/scripts/index-maintain.mjs +39 -0
- package/scripts/index-reconcile.mjs +49 -0
- package/scripts/index-status.mjs +28 -0
- package/scripts/install-resident-watcher.ps1 +15 -0
- package/scripts/install-session-watch.ps1 +332 -0
- package/scripts/install-surgery-task.ps1 +174 -0
- package/scripts/lib/auto-truncate-run.ps1 +512 -0
- package/scripts/lib/session-watch-fixture.mjs +207 -0
- package/scripts/longlive-doctor.mjs +578 -0
- package/scripts/metrics-read.mjs +79 -0
- package/scripts/metrics-sample.mjs +215 -0
- package/scripts/migrate-180.mjs +163 -0
- package/scripts/migrate-200.mjs +8 -0
- package/scripts/migrate-a1-legacy.mjs +62 -0
- package/scripts/migrate-lifecycle.mjs +157 -0
- package/scripts/pack.mjs +392 -0
- package/scripts/recall-index-build.mjs +128 -0
- package/scripts/recall-links-build.mjs +420 -0
- package/scripts/rescore-cards.mjs +36 -0
- package/scripts/resident-watcher-status.ps1 +15 -0
- package/scripts/resident-watcher.ps1 +643 -0
- package/scripts/session-watch-drill.mjs +553 -0
- package/scripts/session-watch-status.ps1 +146 -0
- package/scripts/session-watch.mjs +1367 -0
- package/scripts/surgery-inspect.mjs +122 -0
- package/scripts/surgery-run.cmd +34 -0
- package/scripts/truncate-cli.mjs +279 -0
- package/scripts/unattended-surgery.ps1 +1019 -0
- package/scripts/uninstall-resident-watcher.ps1 +15 -0
- package/scripts/uninstall-session-watch.ps1 +192 -0
- package/scripts/verify-card-anchors.mjs +138 -0
- package/scripts/watch-loop.ps1 +916 -0
- package/src/actions/audit.js +125 -0
- package/src/actions/evidence.js +122 -0
- package/src/actions/fs.js +162 -0
- package/src/activity/index.js +873 -0
- package/src/activity/model.js +351 -0
- package/src/activity/store.js +786 -0
- package/src/activity/summary.js +180 -0
- package/src/activity/thinking.js +191 -0
- package/src/adapters/constants.js +11 -0
- package/src/adapters/engram/data/aliases.json +51 -0
- package/src/adapters/engram/data/policy.json +8 -0
- package/src/adapters/engram/data/routing-rules.json +546 -0
- package/src/adapters/engram/index.js +278 -0
- package/src/adapters/registry.js +315 -0
- package/src/answer/audit.js +238 -0
- package/src/answer/claim-guard.mjs +234 -0
- package/src/answer/evidence.js +30 -0
- package/src/answer/guard.js +1370 -0
- package/src/answer/index.js +1086 -0
- package/src/answer/query.js +111 -0
- package/src/answer/second-hop.mjs +101 -0
- package/src/auto-truncate-status.js +164 -0
- package/src/auto-truncate.js +1181 -0
- package/src/autoprocedure/candidate.js +342 -0
- package/src/autoprocedure/config.js +122 -0
- package/src/autoprocedure/evidence.js +345 -0
- package/src/autoprocedure/index.js +83 -0
- package/src/autoprocedure/ledger.js +329 -0
- package/src/autoprocedure/lint.js +232 -0
- package/src/autoprocedure/llm.js +409 -0
- package/src/autoprocedure/locks.js +102 -0
- package/src/autoprocedure/paths.js +39 -0
- package/src/autoprocedure/privacy.js +87 -0
- package/src/autoprocedure/rules.js +288 -0
- package/src/autoprocedure/runtime.js +718 -0
- package/src/autoprocedure/session-reader.js +328 -0
- package/src/backup.js +310 -0
- package/src/bus/bus.mjs +1446 -0
- package/src/codec.js +269 -0
- package/src/compaction/cut-engine.js +44 -0
- package/src/compaction/engine-core.js +1237 -0
- package/src/compaction/entry.js +228 -0
- package/src/compaction.js +230 -0
- package/src/conclusion.js +366 -0
- package/src/config.js +835 -0
- package/src/d6/runtime.js +517 -0
- package/src/d6/surface.js +181 -0
- package/src/deps.js +189 -0
- package/src/engine-status.js +141 -0
- package/src/features.js +1035 -0
- package/src/handoff/index.js +1077 -0
- package/src/handoff/model.js +1058 -0
- package/src/handoff/store.js +1233 -0
- package/src/heartbeat.js +385 -0
- package/src/home.js +16 -0
- package/src/host-version.js +280 -0
- package/src/hot-truncate-diag.js +98 -0
- package/src/identity/card-marker.js +281 -0
- package/src/identity/handover.js +845 -0
- package/src/identity/index.js +337 -0
- package/src/identity/inject-position.js +133 -0
- package/src/identity/writeback.js +344 -0
- package/src/identity.js +118 -0
- package/src/index.js +647 -0
- package/src/lifecycle/gap-clocks.js +364 -0
- package/src/lifecycle/index.js +269 -0
- package/src/lifecycle/proactive.js +1426 -0
- package/src/live-target.js +212 -0
- package/src/live.js +1603 -0
- package/src/log-rotation.js +153 -0
- package/src/memory/a1-migration.js +190 -0
- package/src/memory/activity-capture.js +229 -0
- package/src/memory/anchor-fallback.js +116 -0
- package/src/memory/anchors.js +194 -0
- package/src/memory/archive-cold-state.mjs +794 -0
- package/src/memory/archive-staging.mjs +305 -0
- package/src/memory/archive.mjs +415 -0
- package/src/memory/audit-records.js +222 -0
- package/src/memory/auto-cards.js +441 -0
- package/src/memory/capture-host.js +297 -0
- package/src/memory/capture.js +496 -0
- package/src/memory/card-anchors.js +203 -0
- package/src/memory/card-priority.js +110 -0
- package/src/memory/cards.js +425 -0
- package/src/memory/catchup.mjs +534 -0
- package/src/memory/conclusion-distill.js +381 -0
- package/src/memory/conclusion-drafts.js +243 -0
- package/src/memory/conflicts.js +1060 -0
- package/src/memory/consolidate.js +834 -0
- package/src/memory/decay.js +311 -0
- package/src/memory/distill.js +485 -0
- package/src/memory/event-index.js +1826 -0
- package/src/memory/evidence-chain.js +295 -0
- package/src/memory/evidence.js +213 -0
- package/src/memory/filter-runner.js +555 -0
- package/src/memory/filter.js +1035 -0
- package/src/memory/forget-v2.js +680 -0
- package/src/memory/forget.js +531 -0
- package/src/memory/frames-activation.js +249 -0
- package/src/memory/frontmatter.js +454 -0
- package/src/memory/fts-query.js +342 -0
- package/src/memory/governance.js +604 -0
- package/src/memory/index-freshness.js +234 -0
- package/src/memory/index.js +435 -0
- package/src/memory/l2-gate.js +169 -0
- package/src/memory/land.mjs +743 -0
- package/src/memory/lifecycle.js +235 -0
- package/src/memory/lock.js +121 -0
- package/src/memory/maintenance.js +1149 -0
- package/src/memory/manifest.js +245 -0
- package/src/memory/memory-health.mjs +607 -0
- package/src/memory/migrate-200.js +1681 -0
- package/src/memory/migrate-lifecycle.js +1808 -0
- package/src/memory/migrate.js +139 -0
- package/src/memory/paths.js +229 -0
- package/src/memory/procedure-candidate.mjs +377 -0
- package/src/memory/procedure.js +982 -0
- package/src/memory/prospective-memory.mjs +362 -0
- package/src/memory/provenance.js +119 -0
- package/src/memory/recall-feedback.mjs +406 -0
- package/src/memory/recall-v2.js +218 -0
- package/src/memory/recall.js +357 -0
- package/src/memory/reconcile.js +265 -0
- package/src/memory/records.js +433 -0
- package/src/memory/reinforce.js +281 -0
- package/src/memory/retention.js +162 -0
- package/src/memory/review.js +124 -0
- package/src/memory/state.js +279 -0
- package/src/memory/tiers.js +168 -0
- package/src/memory/topic-phrases.js +73 -0
- package/src/memory/trust.js +97 -0
- package/src/memory/turn-budget.mjs +290 -0
- package/src/memory/version-chain.js +264 -0
- package/src/memory/wake-bridge.mjs +2999 -0
- package/src/memory/wal.js +137 -0
- package/src/memory/working-frame.js +779 -0
- package/src/metrics/classify.mjs +191 -0
- package/src/metrics/estimate.mjs +108 -0
- package/src/metrics/index.mjs +204 -0
- package/src/metrics/measure.mjs +462 -0
- package/src/metrics/prestep-latency.mjs +307 -0
- package/src/metrics/store.mjs +264 -0
- package/src/original.js +294 -0
- package/src/policy/threshold-policy.js +224 -0
- package/src/policy-profile.js +463 -0
- package/src/recall/anaphora.mjs +87 -0
- package/src/recall/archive-config.mjs +130 -0
- package/src/recall/archive-fallback.mjs +390 -0
- package/src/recall/archive-search.mjs +428 -0
- package/src/recall/archive-state.mjs +588 -0
- package/src/recall/brain.mjs +501 -0
- package/src/recall/cards.mjs +202 -0
- package/src/recall/current-line.mjs +110 -0
- package/src/recall/edges.js +398 -0
- package/src/recall/embedding.mjs +698 -0
- package/src/recall/entities.mjs +112 -0
- package/src/recall/explain.mjs +443 -0
- package/src/recall/force-policy.mjs +138 -0
- package/src/recall/gate-log.mjs +280 -0
- package/src/recall/gate-metrics.mjs +191 -0
- package/src/recall/index.js +1337 -0
- package/src/recall/inject-order.mjs +279 -0
- package/src/recall/link-recall.mjs +183 -0
- package/src/recall/links.mjs +696 -0
- package/src/recall/privacy.mjs +208 -0
- package/src/recall/recall-core.mjs +810 -0
- package/src/recall/shared-visibility.js +302 -0
- package/src/recall/time-normalizer.mjs +196 -0
- package/src/recall/turn-budget-inject.mjs +154 -0
- package/src/retention/cold-gate.mjs +146 -0
- package/src/retention/config.js +163 -0
- package/src/retention/index.js +801 -0
- package/src/role/activation.js +191 -0
- package/src/role/attention.js +318 -0
- package/src/role/base.js +36 -0
- package/src/role/channels.js +423 -0
- package/src/role/index.js +425 -0
- package/src/role/interfaces.js +115 -0
- package/src/role/personality.js +370 -0
- package/src/role/readers.js +151 -0
- package/src/role/relationships.js +477 -0
- package/src/role/store.js +202 -0
- package/src/role/writeprotect.js +373 -0
- package/src/router/aliases.json +182 -0
- package/src/router/background/agent-runner.mjs +239 -0
- package/src/router/background/anchor.mjs +323 -0
- package/src/router/background/audit.mjs +337 -0
- package/src/router/background/budget-ledger.mjs +648 -0
- package/src/router/background/host-sim.mjs +451 -0
- package/src/router/background/index.mjs +81 -0
- package/src/router/background/memory.mjs +63 -0
- package/src/router/background/mock-llm.mjs +203 -0
- package/src/router/background/queue.mjs +224 -0
- package/src/router/background/retry.mjs +255 -0
- package/src/router/background/router.mjs +1459 -0
- package/src/router/background/stream.mjs +276 -0
- package/src/router/background/tool-policy.mjs +255 -0
- package/src/router/design-headings.json +221 -0
- package/src/router/face/config.mjs +155 -0
- package/src/router/face/context.mjs +284 -0
- package/src/router/face/face.mjs +466 -0
- package/src/router/face/identity.mjs +130 -0
- package/src/router/face/index.mjs +65 -0
- package/src/router/face/journal.mjs +119 -0
- package/src/router/face/llm.mjs +252 -0
- package/src/router/face/outbox.mjs +153 -0
- package/src/router/face/paths.mjs +54 -0
- package/src/router/judge.mjs +987 -0
- package/src/router/policies/generic.json +131 -0
- package/src/router/route.js +1766 -0
- package/src/router/router.mjs +535 -0
- package/src/router/routing-rules.json +816 -0
- package/src/router/run-sim.mjs +530 -0
- package/src/router/runtime.js +569 -0
- package/src/router/service/apply.mjs +1218 -0
- package/src/router/service/board.mjs +712 -0
- package/src/router/service/caller.mjs +131 -0
- package/src/router/service/config.mjs +361 -0
- package/src/router/service/context.mjs +314 -0
- package/src/router/service/hint.mjs +668 -0
- package/src/router/service/lease.mjs +494 -0
- package/src/router/service/live.mjs +251 -0
- package/src/router/service/lock.mjs +550 -0
- package/src/router/service/merge.mjs +255 -0
- package/src/router/service/model-resolve.mjs +350 -0
- package/src/router/service/paths.mjs +168 -0
- package/src/router/service/proposals.mjs +1461 -0
- package/src/router/service/queue.mjs +477 -0
- package/src/router/service/reconcile.mjs +271 -0
- package/src/router/service/service.mjs +2998 -0
- package/src/router/service/sources.mjs +352 -0
- package/src/router/service/status.mjs +520 -0
- package/src/router/service/store.mjs +476 -0
- package/src/router/service/ticklock.mjs +239 -0
- package/src/router/service/tokens.mjs +95 -0
- package/src/router/service/tools.mjs +248 -0
- package/src/router/service/wake.mjs +544 -0
- package/src/router/service/wal.mjs +685 -0
- package/src/router/shadow.mjs +821 -0
- package/src/surgery-recovery.js +1909 -0
- package/src/tool-output.js +485 -0
- package/src/tools.js +3262 -0
- package/src/truncate-visible.js +2416 -0
- package/src/truncate.js +999 -0
- package/src/ui/actions.js +1312 -0
- package/src/ui/flags.js +259 -0
- package/src/ui/panel-api.js +371 -0
- package/src/ui/panel-auth.js +251 -0
- package/src/ui/panel-integrity.js +243 -0
- package/src/ui/routes-readonly.js +759 -0
- package/src/ui/routes.js +284 -0
- package/src/util/append-store.js +368 -0
- package/src/util/local-day.js +30 -0
- package/src/util/redact.js +227 -0
- package/src/util/stale-locks.js +148 -0
- package/src/version.js +99 -0
- package/test/fixtures/pre-step-container.mjs +100 -0
- package/test/p1_probe.mjs +97 -0
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// src/recall/entities.mjs — B2:实体别名表(`.longlive/entities/entities.jsonl`)
|
|
2
|
+
//
|
|
3
|
+
// 字段:{schema:'entities/v1', canonical, aliases[], kind, at}
|
|
4
|
+
// 只读路径给召回查询扩展用;写入口只允许宿主传入(本模块不做权限门,由调用方保证)。
|
|
5
|
+
|
|
6
|
+
import crypto from 'node:crypto';
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
|
|
10
|
+
export const ENTITIES_SCHEMA = 'entities/v1';
|
|
11
|
+
|
|
12
|
+
export function entitiesPathOf(memoryRoot) {
|
|
13
|
+
return path.join(path.resolve(String(memoryRoot ?? '')), '.longlive', 'entities', 'entities.jsonl');
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function nowIso(now) {
|
|
17
|
+
const value = typeof now === 'function' ? now() : new Date();
|
|
18
|
+
return (value instanceof Date ? value : new Date(value)).toISOString();
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Read alias registry (append-only; later rows add aliases). Missing file => empty map. */
|
|
22
|
+
export function readEntityAliases({ memoryRoot }) {
|
|
23
|
+
const file = entitiesPathOf(memoryRoot);
|
|
24
|
+
const byCanonical = new Map();
|
|
25
|
+
let text = '';
|
|
26
|
+
try {
|
|
27
|
+
text = fs.readFileSync(file, 'utf8');
|
|
28
|
+
} catch {
|
|
29
|
+
return { present: false, file, aliases: {}, byCanonical: {}, badLines: 0 };
|
|
30
|
+
}
|
|
31
|
+
let bad = 0;
|
|
32
|
+
for (const line of text.split('\n')) {
|
|
33
|
+
if (line.trim() === '') continue;
|
|
34
|
+
let row;
|
|
35
|
+
try {
|
|
36
|
+
row = JSON.parse(line);
|
|
37
|
+
} catch {
|
|
38
|
+
bad += 1;
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
const canonical = typeof row?.canonical === 'string' ? row.canonical.trim() : '';
|
|
42
|
+
if (canonical === '') continue;
|
|
43
|
+
const aliases = Array.isArray(row.aliases) ? row.aliases.map((a) => String(a).trim()).filter(Boolean) : [];
|
|
44
|
+
const prev = byCanonical.get(canonical) ?? { canonical, aliases: new Set([canonical]), kind: row.kind ?? null };
|
|
45
|
+
for (const alias of aliases) prev.aliases.add(alias);
|
|
46
|
+
byCanonical.set(canonical, prev);
|
|
47
|
+
}
|
|
48
|
+
const aliases = {};
|
|
49
|
+
for (const [canonical, entry] of byCanonical) aliases[canonical] = [...entry.aliases];
|
|
50
|
+
return { present: true, file, aliases, byCanonical, badLines: bad };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Append one entity alias row (host/panel write path). Idempotent per canonical+alias set. */
|
|
54
|
+
export function appendEntityAlias({ memoryRoot, canonical, aliases = [], kind = null, now = () => new Date() }) {
|
|
55
|
+
const name = typeof canonical === 'string' ? canonical.trim() : '';
|
|
56
|
+
if (name === '') {
|
|
57
|
+
const error = new Error('E_ENTITY_CANONICAL_REQUIRED: canonical 不能为空');
|
|
58
|
+
error.code = 'E_ENTITY_CANONICAL_REQUIRED';
|
|
59
|
+
throw error;
|
|
60
|
+
}
|
|
61
|
+
const list = [...new Set([name, ...(Array.isArray(aliases) ? aliases : [])].map((a) => String(a).trim()).filter(Boolean))];
|
|
62
|
+
const file = entitiesPathOf(memoryRoot);
|
|
63
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
64
|
+
const row = { schema: ENTITIES_SCHEMA, canonical: name, aliases: list, kind: kind ?? null, at: nowIso(now) };
|
|
65
|
+
fs.appendFileSync(file, `${JSON.stringify(row)}\n`, 'utf8');
|
|
66
|
+
return { ok: true, file, row };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Find canonical entities mentioned in `text` (longest alias first). */
|
|
70
|
+
export function resolveEntityAliases(text, aliasMap, { max = 20 } = {}) {
|
|
71
|
+
const value = typeof text === 'string' ? text : '';
|
|
72
|
+
const matches = [];
|
|
73
|
+
const entries = [];
|
|
74
|
+
for (const [canonical, aliases] of Object.entries(aliasMap ?? {})) {
|
|
75
|
+
for (const alias of new Set([canonical, ...(Array.isArray(aliases) ? aliases : [])])) {
|
|
76
|
+
if (typeof alias !== 'string' || alias.trim() === '') continue;
|
|
77
|
+
entries.push({ canonical, alias });
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
entries.sort((a, b) => b.alias.length - a.alias.length || a.alias.localeCompare(b.alias));
|
|
81
|
+
const usedRanges = [];
|
|
82
|
+
for (const entry of entries) {
|
|
83
|
+
let from = 0;
|
|
84
|
+
while (matches.length < max) {
|
|
85
|
+
const index = value.indexOf(entry.alias, from);
|
|
86
|
+
if (index === -1) break;
|
|
87
|
+
from = index + entry.alias.length;
|
|
88
|
+
const end = index + entry.alias.length;
|
|
89
|
+
if (usedRanges.some((range) => index < range.end && end > range.start)) continue;
|
|
90
|
+
usedRanges.push({ start: index, end });
|
|
91
|
+
matches.push({ canonical: entry.canonical, alias: entry.alias, index });
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
matches.sort((a, b) => a.index - b.index);
|
|
95
|
+
return {
|
|
96
|
+
terms: [...new Set(matches.map((match) => match.canonical))],
|
|
97
|
+
matches,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Deterministic expansion text: canonical names appended once. */
|
|
102
|
+
export function expandQueryWithEntities(queryText, resolution) {
|
|
103
|
+
const terms = Array.isArray(resolution?.terms) ? resolution.terms : [];
|
|
104
|
+
if (terms.length === 0) return { text: String(queryText ?? ''), changed: false, terms };
|
|
105
|
+
const base = String(queryText ?? '');
|
|
106
|
+
const tail = terms.filter((term) => !base.includes(term)).join(' ');
|
|
107
|
+
return { text: tail === '' ? base : `${base} ${tail}`, changed: tail !== '', terms };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function entityAliasDigest(aliasMap) {
|
|
111
|
+
return crypto.createHash('sha1').update(JSON.stringify(aliasMap ?? {})).digest('hex').slice(0, 12);
|
|
112
|
+
}
|
|
@@ -0,0 +1,443 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* S3 · 召回可解释性(recall explainability)
|
|
3
|
+
*
|
|
4
|
+
* 职责边界:
|
|
5
|
+
* - 本模块只做**读**与纯函数分类/汇总;recall-log 的写在 src/recall/index.js。
|
|
6
|
+
* - 给 recall-log 每条补 why/eligible/dropped/gate/trigger/channel(审计 P1-7),
|
|
7
|
+
* 并把「策略跳过」「零命中」「失败」分开计数,供最近 24h 汇总(面板/健康输出)。
|
|
8
|
+
* - 行为零改动:不改变触发规则(turn<=1 / same-as-last / quiet),
|
|
9
|
+
* 只给已有决策补原因。
|
|
10
|
+
*
|
|
11
|
+
* why 语义(7 类,固定枚举):
|
|
12
|
+
* - everyNTurns 历史 1.8.1 及以前的 every-n-turns 行;1.8.2 起 decideTrigger
|
|
13
|
+
* 不再产生该触发(此处只兼容读旧 recall-log,不是现行触发路径)
|
|
14
|
+
* - injected 本轮确实注入了卡片(非心跳轮)
|
|
15
|
+
* - zero-hit 本轮执行了检索但零命中(非心跳轮)
|
|
16
|
+
* - everyNTurns 本轮由 everyNTurns 心跳触发(不论最终是否有注入;用 injected 数组区分结果)
|
|
17
|
+
* - quiet 触发规则判定本轮「安静」(gate.why === 'quiet')
|
|
18
|
+
* - policy-skip gate 因其它策略跳过(same-as-last / empty-query 等)
|
|
19
|
+
* - user-task 1.8.8 M2:强制触发(autoRecall.forceOnUserMessage)路径。
|
|
20
|
+
* 它与静默/周期路径正交:只要本轮是「真人任务消息 → 强制召回」,
|
|
21
|
+
* why 固定为 user-task、trigger 固定为 forced,不看最终是否注入
|
|
22
|
+
* (是否真注入看 injected 数组与 outcome 字段,禁止用 why 冒充成功)。
|
|
23
|
+
* - error 本轮召回失败(异常 / 注入工厂不可用)
|
|
24
|
+
*
|
|
25
|
+
* trigger 是 gate.why 的稳定口径(turn<=1 等),与 why 正交,便于对照触发规则。
|
|
26
|
+
* 1.8.8 起 trigger 多了 'forced'(强制触发),旧值一个不动。
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
import fs from 'node:fs';
|
|
30
|
+
import path from 'node:path';
|
|
31
|
+
|
|
32
|
+
// 第三方记忆插件的通道 id 只从 adapters 注册表取,核心 src 不出现第三方字面量(独立性门禁)。
|
|
33
|
+
import { EXTERNAL_PLUGIN_IDS } from '../adapters/constants.js';
|
|
34
|
+
import { OUTPUT_RESERVE_NORMAL_TOKENS } from '../policy/threshold-policy.js';
|
|
35
|
+
|
|
36
|
+
export const RECALL_LOG_FILE = 'recall-log.jsonl';
|
|
37
|
+
export const LEGACY_RECALL_LOG_REL = path.join('recall', 'log.jsonl');
|
|
38
|
+
export const RECALL_EXPLAIN_SCHEMA = 'recall-explain/v1';
|
|
39
|
+
export const RECALL_LOG_SCHEMA = 'recall-log/v1';
|
|
40
|
+
export const RECALL_WINDOW_MS = 24 * 60 * 60 * 1000;
|
|
41
|
+
|
|
42
|
+
/** 固定 why 枚举;测试与面板按它校验,不许悄悄加值。 */
|
|
43
|
+
export const RECALL_WHY_VALUES = Object.freeze([
|
|
44
|
+
'injected',
|
|
45
|
+
'zero-hit',
|
|
46
|
+
'everyNTurns',
|
|
47
|
+
'quiet',
|
|
48
|
+
'policy-skip',
|
|
49
|
+
'error',
|
|
50
|
+
// 1.8.8 M2:强制触发路径单列;只在 buildRecallLogRecord({forced:true}) 时出现。
|
|
51
|
+
'user-task',
|
|
52
|
+
]);
|
|
53
|
+
|
|
54
|
+
/** gate.why → 面板可读 trigger 口径。 */
|
|
55
|
+
export const RECALL_TRIGGER_BY_GATE = Object.freeze({
|
|
56
|
+
'new-session': 'turn<=1',
|
|
57
|
+
'after-compaction': 'after-compaction',
|
|
58
|
+
'every-n-turns': 'everyNTurns',
|
|
59
|
+
'topic-switch': 'topic-switch',
|
|
60
|
+
'same-as-last': 'same-as-last',
|
|
61
|
+
'quiet': 'quiet',
|
|
62
|
+
'empty-query': 'empty-query',
|
|
63
|
+
'mid-turn': 'mid-turn',
|
|
64
|
+
// 1.8.8 M2:强制触发(不看 everyNTurns、不被 quiet 挡)。
|
|
65
|
+
'forced': 'forced',
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
export const RECALL_CHANNELS = Object.freeze(['file', ...EXTERNAL_PLUGIN_IDS, 'degraded']);
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* gate.why → trigger 字段。
|
|
72
|
+
* @param {string|undefined} gateWhy
|
|
73
|
+
* @returns {string}
|
|
74
|
+
*/
|
|
75
|
+
export function normalizeTrigger(gateWhy) {
|
|
76
|
+
if (typeof gateWhy !== 'string' || gateWhy === '') return 'unknown';
|
|
77
|
+
return RECALL_TRIGGER_BY_GATE[gateWhy] ?? gateWhy;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* 单轮 why 分类(纯函数,行为语义见文件头)。
|
|
82
|
+
* @param {{gate?:{recall?:boolean, why?:string}, items?:unknown[], error?:boolean, factoryUnavailable?:boolean}} input
|
|
83
|
+
* @returns {'injected'|'zero-hit'|'everyNTurns'|'quiet'|'policy-skip'|'error'}
|
|
84
|
+
*/
|
|
85
|
+
export function classifyRecallWhy({ gate = null, items = [], error = false, factoryUnavailable = false } = {}) {
|
|
86
|
+
if (error === true || factoryUnavailable === true) return 'error';
|
|
87
|
+
const recall = gate?.recall === true;
|
|
88
|
+
if (!recall) return gate?.why === 'quiet' ? 'quiet' : 'policy-skip';
|
|
89
|
+
// 1.8.1 及以前的心跳行:只用于读旧日志归类,1.8.2 已没有该触发。
|
|
90
|
+
if (gate?.why === 'every-n-turns') return 'everyNTurns';
|
|
91
|
+
return Array.isArray(items) && items.length > 0 ? 'injected' : 'zero-hit';
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* chooseRecall() 的 hits + rejections → 面板可读 dropped 摘要。
|
|
96
|
+
* 只统计「没进本轮注入」的原因;预算内正常落选的重复项也算进去(与 blocked 对齐)。
|
|
97
|
+
* @param {object|null} hits
|
|
98
|
+
* @param {object[]|null} rejections
|
|
99
|
+
* @returns {{budget:number,dedupe:number,seen:number,localOnly:number,privacy:number,lowTrust:number,maxItems:number,total:number}|null}
|
|
100
|
+
*/
|
|
101
|
+
export function summarizeDropped(hits = null, rejections = null) {
|
|
102
|
+
if (!hits || typeof hits !== 'object') return null;
|
|
103
|
+
const byReason = {};
|
|
104
|
+
for (const row of Array.isArray(rejections) ? rejections : []) {
|
|
105
|
+
const reason = typeof row?.reason === 'string' ? row.reason : 'unknown';
|
|
106
|
+
byReason[reason] = (byReason[reason] ?? 0) + 1;
|
|
107
|
+
}
|
|
108
|
+
const n = (value) => (Number.isFinite(Number(value)) ? Math.max(0, Number(value)) : 0);
|
|
109
|
+
const out = {
|
|
110
|
+
budget: n(hits.droppedByBudget),
|
|
111
|
+
dedupe: n(hits.droppedByDedupe),
|
|
112
|
+
seen: n(hits.droppedBySeen),
|
|
113
|
+
localOnly: n(hits.droppedLocalOnly),
|
|
114
|
+
privacy: n(hits.droppedByPrivacy),
|
|
115
|
+
lowTrust: n(hits.droppedByLowTrust),
|
|
116
|
+
maxItems: n(byReason['max-items']),
|
|
117
|
+
};
|
|
118
|
+
out.total = out.budget + out.dedupe + out.seen + out.localOnly + out.privacy + out.lowTrust + out.maxItems;
|
|
119
|
+
return out;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* 选择本轮 channel:embedding 降级优先标注;目前召回候选只有文件卡(AutoCard 也是文件派生)。
|
|
124
|
+
* 外部记忆插件通道(EXTERNAL_PLUGIN_IDS)留给后续接入:path 前缀 `<id>:` 时自动标。
|
|
125
|
+
*/
|
|
126
|
+
export function resolveChannel({ items = [], embeddingDegraded = false } = {}) {
|
|
127
|
+
if (embeddingDegraded === true) return 'degraded';
|
|
128
|
+
const list = Array.isArray(items) ? items : [];
|
|
129
|
+
const external = EXTERNAL_PLUGIN_IDS.find((id) => list.some((item) => String(item?.path ?? '').startsWith(`${id}:`)));
|
|
130
|
+
return external ?? 'file';
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** recall-log 里的 query 摘要上限(字符);只留线索,不留整段对话。 */
|
|
134
|
+
export const RECALL_QUERY_SUMMARY_MAX = 200;
|
|
135
|
+
|
|
136
|
+
/** 日志里的敏感串:手机号 / 邮箱 / 身份证 / IPv4 / 长 token(key)。 */
|
|
137
|
+
const LOG_PII_PATTERNS = Object.freeze([
|
|
138
|
+
/\b1[3-9]\d{9}\b/g,
|
|
139
|
+
/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g,
|
|
140
|
+
/\b\d{17}[\dXx]\b/g,
|
|
141
|
+
/\b(?:\d{1,3}\.){3}\d{1,3}\b/g,
|
|
142
|
+
/\b[A-Za-z0-9_-]{24,}\b/g,
|
|
143
|
+
]);
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* 1.8.8 M2:recall-log 的 query 摘要(隐私友好)。
|
|
147
|
+
* 只做四件事:去控制字符、折叠空白、遮蔽常见敏感串、截到 200 字符。
|
|
148
|
+
* 不存整段用户消息,不做语义改写。
|
|
149
|
+
* @param {unknown} text
|
|
150
|
+
* @returns {string}
|
|
151
|
+
*/
|
|
152
|
+
export function summarizeQuery(text) {
|
|
153
|
+
let value = String(text ?? '');
|
|
154
|
+
value = value.replace(/[\u0000-\u001f\u007f]+/g, ' ').replace(/\s+/g, ' ').trim();
|
|
155
|
+
if (value === '') return '';
|
|
156
|
+
for (const pattern of LOG_PII_PATTERNS) value = value.replace(pattern, '[已隐去]');
|
|
157
|
+
if (value.length > RECALL_QUERY_SUMMARY_MAX) value = `${value.slice(0, RECALL_QUERY_SUMMARY_MAX)}…`;
|
|
158
|
+
return value;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** link 统计的最小化形状(只记词数/命中数,不记用户原句)。 */
|
|
162
|
+
function summarizeLinkStat(link) {
|
|
163
|
+
if (!link || typeof link !== 'object') return null;
|
|
164
|
+
const terms = Array.isArray(link.matchedTerms) ? link.matchedTerms.map((t) => String(t)).filter((t) => t !== '').slice(0, 20) : [];
|
|
165
|
+
return {
|
|
166
|
+
enabled: link.enabled !== false,
|
|
167
|
+
matchedTerms: terms,
|
|
168
|
+
injectedCount: Number.isFinite(Number(link.injectedCount)) ? Math.max(0, Number(link.injectedCount)) : 0,
|
|
169
|
+
tokens: Number.isFinite(Number(link.tokens)) ? Math.max(0, Number(link.tokens)) : 0,
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* 构造一条 recall-log 行(字段纯计算,不写盘)。
|
|
175
|
+
* @param {object} input
|
|
176
|
+
* @param {Date|string|number} [input.at]
|
|
177
|
+
* @param {string} input.sessionId
|
|
178
|
+
* @param {number} input.turn
|
|
179
|
+
* @param {object|null} [input.result] chooseRecall 结果(skips 传 null)
|
|
180
|
+
* @param {object|null} [input.gate] decideTrigger 结果
|
|
181
|
+
* @param {number} [input.everyNTurns] 历史字段兼容(1.8.2 不再触发)
|
|
182
|
+
* @param {boolean} [input.error]
|
|
183
|
+
* @param {boolean} [input.factoryUnavailable]
|
|
184
|
+
* @param {boolean} [input.embeddingDegraded]
|
|
185
|
+
* @param {unknown[]|null} [input.injectedItems] 覆盖注入项(factory 不可用时传 [])
|
|
186
|
+
* @param {string} [input.query] 1.8.8 M2:触发本轮的真实用户消息摘要(summarizeQuery 后写入)
|
|
187
|
+
* @param {number|null} [input.elapsedMs] 1.8.8 M2:agent/pre-step 内召回耗时(毫秒)
|
|
188
|
+
* @param {boolean} [input.forced] 1.8.8 M2:是否强制触发(autoRecall.forceOnUserMessage)
|
|
189
|
+
* @param {string|null} [input.why] 覆盖 why(强制路径固定 'user-task')
|
|
190
|
+
* @param {string|null} [input.trigger] 覆盖 trigger(强制路径固定 'forced')
|
|
191
|
+
* @param {boolean} [input.archiveUnavailable] 1.8.8 M2:归档兜底模块不可用/调用失败
|
|
192
|
+
* @param {object|null} [input.link] 1.8.8 M2:链路命中统计 {matchedTerms,injectedCount,tokens}
|
|
193
|
+
* @returns {object}
|
|
194
|
+
*/
|
|
195
|
+
export function buildRecallLogRecord({
|
|
196
|
+
at = new Date(),
|
|
197
|
+
sessionId = 'unknown',
|
|
198
|
+
turn = 0,
|
|
199
|
+
result = null,
|
|
200
|
+
gate = null,
|
|
201
|
+
everyNTurns = null,
|
|
202
|
+
error = false,
|
|
203
|
+
factoryUnavailable = false,
|
|
204
|
+
embeddingDegraded = false,
|
|
205
|
+
injectedItems = null,
|
|
206
|
+
query = '',
|
|
207
|
+
elapsedMs = null,
|
|
208
|
+
// B3 C5:本轮注入块的实际字符数与估算 token(字符车道口径,1 token ≈ 2 字符)。
|
|
209
|
+
injectedChars = null,
|
|
210
|
+
injectedTokens = null,
|
|
211
|
+
forced = false,
|
|
212
|
+
why: whyOverride = null,
|
|
213
|
+
trigger: triggerOverride = null,
|
|
214
|
+
archiveUnavailable = false,
|
|
215
|
+
link = null,
|
|
216
|
+
} = {}) {
|
|
217
|
+
const items = Array.isArray(injectedItems) ? injectedItems : (Array.isArray(result?.items) ? result.items : []);
|
|
218
|
+
const hits = result?.hits && typeof result.hits === 'object' ? result.hits : null;
|
|
219
|
+
const why = typeof whyOverride === 'string' && whyOverride !== ''
|
|
220
|
+
? whyOverride
|
|
221
|
+
: classifyRecallWhy({ gate, items, error, factoryUnavailable });
|
|
222
|
+
const dropped = summarizeDropped(hits, result?.rejections);
|
|
223
|
+
const gateSummary = {
|
|
224
|
+
recall: gate?.recall === true,
|
|
225
|
+
why: typeof gate?.why === 'string' ? gate.why : 'unknown',
|
|
226
|
+
everyNTurns: Number.isFinite(Number(everyNTurns)) ? Number(everyNTurns) : null,
|
|
227
|
+
};
|
|
228
|
+
// 注意 Number(null) === 0:缺省(null/undefined/'')必须落 null,不能落 0。
|
|
229
|
+
const elapsedRaw = elapsedMs === null || elapsedMs === undefined || elapsedMs === '' ? null : Number(elapsedMs);
|
|
230
|
+
const elapsed = Number.isFinite(elapsedRaw) && elapsedRaw >= 0 ? Math.round(elapsedRaw) : null;
|
|
231
|
+
const injectedCharsRaw = injectedChars === null || injectedChars === undefined || injectedChars === '' ? null : Number(injectedChars);
|
|
232
|
+
const injectedCharsValue = Number.isFinite(injectedCharsRaw) && injectedCharsRaw >= 0 ? Math.round(injectedCharsRaw) : null;
|
|
233
|
+
const injectedTokensRaw = injectedTokens === null || injectedTokens === undefined || injectedTokens === '' ? null : Number(injectedTokens);
|
|
234
|
+
const injectedTokensValue = Number.isFinite(injectedTokensRaw) && injectedTokensRaw >= 0 ? Math.round(injectedTokensRaw) : null;
|
|
235
|
+
let outcome = 'zero-hit';
|
|
236
|
+
if (error === true) outcome = 'error';
|
|
237
|
+
else if (factoryUnavailable === true) outcome = 'factory-unavailable';
|
|
238
|
+
else if (items.length > 0) outcome = 'injected';
|
|
239
|
+
else if (gate && gate.recall !== true) outcome = 'gate-skip';
|
|
240
|
+
return {
|
|
241
|
+
at: at instanceof Date ? at.toISOString() : new Date(at).toISOString(),
|
|
242
|
+
sessionId: String(sessionId ?? 'unknown'),
|
|
243
|
+
turn: Number.isFinite(Number(turn)) ? Number(turn) : 0,
|
|
244
|
+
why,
|
|
245
|
+
eligible: hits ? (Number.isFinite(Number(hits.eligible)) ? Number(hits.eligible) : 0) : null,
|
|
246
|
+
dropped,
|
|
247
|
+
gate: gateSummary,
|
|
248
|
+
trigger: typeof triggerOverride === 'string' && triggerOverride !== ''
|
|
249
|
+
? triggerOverride
|
|
250
|
+
: normalizeTrigger(gate?.why),
|
|
251
|
+
// 1.8.8 M2:强制触发 / 链路直连 / 归档兜底的取证字段。
|
|
252
|
+
forced: forced === true,
|
|
253
|
+
query: summarizeQuery(query),
|
|
254
|
+
elapsedMs: elapsed,
|
|
255
|
+
// B3 C5:injected 行必须能读到 token/延迟;字符数是本轮真正的注入块大小。
|
|
256
|
+
injectedChars: injectedCharsValue,
|
|
257
|
+
injectedTokens: injectedTokensValue,
|
|
258
|
+
outcome,
|
|
259
|
+
archiveUnavailable: archiveUnavailable === true,
|
|
260
|
+
link: summarizeLinkStat(link),
|
|
261
|
+
// D5 forward instrumentation: the existing recall result already carries the
|
|
262
|
+
// rendered token estimate; never read a session or add a new parse path.
|
|
263
|
+
estimatedTokens: Number.isFinite(Number(result?.tokens)) ? Number(result.tokens) : 0,
|
|
264
|
+
budgetUsed: Number.isFinite(Number(result?.tokens)) ? Number(result.tokens) : 0,
|
|
265
|
+
// 1.8.3 D5 shared-window fields: forward-only. The recall path has no
|
|
266
|
+
// session/input read; unavailable fields are explicitly null.
|
|
267
|
+
estimatedInputTokens: null,
|
|
268
|
+
estimatedOutputTokens: null,
|
|
269
|
+
outputReserveTokens: OUTPUT_RESERVE_NORMAL_TOKENS,
|
|
270
|
+
actual_output_tokens: null,
|
|
271
|
+
finish_reason: null,
|
|
272
|
+
truncated: false,
|
|
273
|
+
reserve_class: 'long',
|
|
274
|
+
fold_failed: null,
|
|
275
|
+
fold_busy: false,
|
|
276
|
+
injectedCount: items.length,
|
|
277
|
+
channel: resolveChannel({ items, embeddingDegraded }),
|
|
278
|
+
injected: items.map((item) => ({
|
|
279
|
+
id: item.path,
|
|
280
|
+
title: item.title,
|
|
281
|
+
score: Number(Number(item.score ?? 0).toFixed(3)),
|
|
282
|
+
reason: item.reason ?? 'keyword',
|
|
283
|
+
// 1.8.8 M2:来源 file / link / archive;旧行缺该字段时按 file 读。
|
|
284
|
+
source: typeof item.source === 'string' && item.source !== '' ? item.source : 'file',
|
|
285
|
+
})),
|
|
286
|
+
blocked: (Array.isArray(result?.rejections) ? result.rejections : []).map((item) => ({
|
|
287
|
+
id: item.path,
|
|
288
|
+
title: item.title,
|
|
289
|
+
reason: item.reason,
|
|
290
|
+
})),
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* 读取 recall-log 行。
|
|
296
|
+
* 规范位置:<memoryRoot>/.longlive/recall-log.jsonl(auto-recall 写入)。
|
|
297
|
+
* 兼容旧位置:<memoryRoot>/.longlive/recall/log.jsonl(M2-C 读审计);规范文件不存在时才回退。
|
|
298
|
+
* @param {{memoryRoot?:string, limit?:number}} [options]
|
|
299
|
+
*/
|
|
300
|
+
export function readRecallLogRows(options = {}) {
|
|
301
|
+
const memoryRoot = typeof options.memoryRoot === 'string' ? options.memoryRoot.trim() : '';
|
|
302
|
+
if (memoryRoot === '') {
|
|
303
|
+
return { ok: false, code: 'E_MEMORY_ROOT_UNSET', present: false, path: '', legacyPath: false, rows: [], bad: 0, bytes: 0 };
|
|
304
|
+
}
|
|
305
|
+
const root = path.resolve(memoryRoot);
|
|
306
|
+
const canonical = path.join(root, '.longlive', RECALL_LOG_FILE);
|
|
307
|
+
const legacy = path.join(root, '.longlive', LEGACY_RECALL_LOG_REL);
|
|
308
|
+
let file = canonical;
|
|
309
|
+
try {
|
|
310
|
+
fs.accessSync(canonical);
|
|
311
|
+
} catch {
|
|
312
|
+
try {
|
|
313
|
+
fs.accessSync(legacy);
|
|
314
|
+
file = legacy;
|
|
315
|
+
} catch {
|
|
316
|
+
file = canonical;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
let text;
|
|
320
|
+
try {
|
|
321
|
+
text = fs.readFileSync(file, 'utf8');
|
|
322
|
+
} catch (error) {
|
|
323
|
+
if (error?.code === 'ENOENT') {
|
|
324
|
+
return { ok: true, present: false, path: file, legacyPath: file === legacy, rows: [], bad: 0, bytes: 0 };
|
|
325
|
+
}
|
|
326
|
+
return { ok: false, code: 'E_RECALL_LOG_READ', present: false, path: file, legacyPath: file === legacy, rows: [], bad: 0, bytes: 0 };
|
|
327
|
+
}
|
|
328
|
+
const rows = [];
|
|
329
|
+
let bad = 0;
|
|
330
|
+
for (const line of text.split(/\r?\n/)) {
|
|
331
|
+
const trimmed = line.trim();
|
|
332
|
+
if (trimmed === '') continue;
|
|
333
|
+
try {
|
|
334
|
+
const row = JSON.parse(trimmed);
|
|
335
|
+
if (row && typeof row === 'object') rows.push(row);
|
|
336
|
+
else bad += 1;
|
|
337
|
+
} catch {
|
|
338
|
+
bad += 1;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
const limit = Number.isInteger(options.limit) && options.limit > 0 ? options.limit : 0;
|
|
342
|
+
return {
|
|
343
|
+
ok: true,
|
|
344
|
+
present: rows.length > 0,
|
|
345
|
+
path: file,
|
|
346
|
+
legacyPath: file === legacy,
|
|
347
|
+
rows: limit > 0 ? rows.slice(-limit) : rows,
|
|
348
|
+
bad,
|
|
349
|
+
bytes: Buffer.byteLength(text, 'utf8'),
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* 最近 windowMs(默认 24h)的 why/trigger/channel 计数。
|
|
355
|
+
* 明确把「策略跳过」与「零命中/失败」拆开:policySkipTotal / zeroHitTotal / errorTotal。
|
|
356
|
+
* 旧行(没有 why 字段)单独计入 legacyRows,不猜原因。
|
|
357
|
+
* @param {object[]} rows
|
|
358
|
+
* @param {{now?:Date|number|string, windowMs?:number}} [options]
|
|
359
|
+
*/
|
|
360
|
+
export function summarizeRecallRows(rows = [], options = {}) {
|
|
361
|
+
const rawNow = options.now;
|
|
362
|
+
const nowMs = rawNow instanceof Date ? rawNow.getTime()
|
|
363
|
+
: Number.isFinite(Number(rawNow)) ? Number(rawNow)
|
|
364
|
+
: Date.now();
|
|
365
|
+
const windowMs = Number.isFinite(Number(options.windowMs)) && Number(options.windowMs) > 0
|
|
366
|
+
? Number(options.windowMs)
|
|
367
|
+
: RECALL_WINDOW_MS;
|
|
368
|
+
const cutoff = nowMs - windowMs;
|
|
369
|
+
const byWhy = Object.fromEntries(RECALL_WHY_VALUES.map((why) => [why, 0]));
|
|
370
|
+
const byTrigger = {};
|
|
371
|
+
const byChannel = {};
|
|
372
|
+
const dropped = { budget: 0, dedupe: 0, seen: 0, localOnly: 0, privacy: 0, lowTrust: 0, maxItems: 0, total: 0 };
|
|
373
|
+
let totalRows = 0;
|
|
374
|
+
let inWindow = 0;
|
|
375
|
+
let legacyRows = 0;
|
|
376
|
+
let injectedRounds = 0;
|
|
377
|
+
let emptyInjections = 0;
|
|
378
|
+
let forcedTotal = 0;
|
|
379
|
+
let archiveUnavailableTotal = 0;
|
|
380
|
+
let linkInjectedTotal = 0;
|
|
381
|
+
const byOutcome = {};
|
|
382
|
+
let lastAt = null;
|
|
383
|
+
|
|
384
|
+
const list = Array.isArray(rows) ? rows : [];
|
|
385
|
+
for (const row of list) {
|
|
386
|
+
if (!row || typeof row !== 'object') continue;
|
|
387
|
+
totalRows += 1;
|
|
388
|
+
const atMs = Date.parse(String(row.at ?? ''));
|
|
389
|
+
const inWindowRow = Number.isFinite(atMs) ? atMs >= cutoff : false;
|
|
390
|
+
if (!inWindowRow) continue;
|
|
391
|
+
inWindow += 1;
|
|
392
|
+
if (lastAt === null || (Number.isFinite(atMs) && atMs > Date.parse(lastAt))) lastAt = String(row.at);
|
|
393
|
+
const why = RECALL_WHY_VALUES.includes(row.why) ? row.why : null;
|
|
394
|
+
if (why === null) legacyRows += 1;
|
|
395
|
+
else byWhy[why] += 1;
|
|
396
|
+
const trigger = typeof row.trigger === 'string' && row.trigger !== '' ? row.trigger : 'unknown';
|
|
397
|
+
byTrigger[trigger] = (byTrigger[trigger] ?? 0) + 1;
|
|
398
|
+
const channel = RECALL_CHANNELS.includes(row.channel) ? row.channel : 'file';
|
|
399
|
+
byChannel[channel] = (byChannel[channel] ?? 0) + 1;
|
|
400
|
+
const injected = Array.isArray(row.injected) ? row.injected : [];
|
|
401
|
+
if (injected.length > 0) injectedRounds += 1;
|
|
402
|
+
else emptyInjections += 1;
|
|
403
|
+
// 1.8.8 M2:强制触发 / 归档不可用 / 链路来源计数(只读已有字段,不猜)。
|
|
404
|
+
if (row.forced === true) forcedTotal += 1;
|
|
405
|
+
if (row.archiveUnavailable === true) archiveUnavailableTotal += 1;
|
|
406
|
+
if (injected.some((item) => item?.source === 'link')) linkInjectedTotal += 1;
|
|
407
|
+
const outcome = typeof row.outcome === 'string' && row.outcome !== '' ? row.outcome : 'unknown';
|
|
408
|
+
byOutcome[outcome] = (byOutcome[outcome] ?? 0) + 1;
|
|
409
|
+
if (row.dropped && typeof row.dropped === 'object') {
|
|
410
|
+
for (const key of Object.keys(dropped)) {
|
|
411
|
+
if (key === 'total') continue;
|
|
412
|
+
dropped[key] += Number.isFinite(Number(row.dropped[key])) ? Math.max(0, Number(row.dropped[key])) : 0;
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
dropped.total = dropped.budget + dropped.dedupe + dropped.seen + dropped.localOnly
|
|
417
|
+
+ dropped.privacy + dropped.lowTrust + dropped.maxItems;
|
|
418
|
+
return {
|
|
419
|
+
schema: RECALL_EXPLAIN_SCHEMA,
|
|
420
|
+
windowHours: Math.round((windowMs / (60 * 60 * 1000)) * 100) / 100,
|
|
421
|
+
windowMs,
|
|
422
|
+
totalRows,
|
|
423
|
+
inWindow,
|
|
424
|
+
legacyRows,
|
|
425
|
+
byWhy,
|
|
426
|
+
byTrigger,
|
|
427
|
+
byChannel,
|
|
428
|
+
byOutcome,
|
|
429
|
+
injectedRounds,
|
|
430
|
+
emptyInjections,
|
|
431
|
+
policySkipTotal: byWhy['policy-skip'] + byWhy.quiet,
|
|
432
|
+
policySkip: { other: byWhy['policy-skip'], quiet: byWhy.quiet },
|
|
433
|
+
zeroHitTotal: byWhy['zero-hit'],
|
|
434
|
+
errorTotal: byWhy.error,
|
|
435
|
+
everyNTurnsTotal: byWhy.everyNTurns,
|
|
436
|
+
forcedTotal,
|
|
437
|
+
userTaskTotal: byWhy['user-task'],
|
|
438
|
+
archiveUnavailableTotal,
|
|
439
|
+
linkInjectedTotal,
|
|
440
|
+
dropped,
|
|
441
|
+
lastAt,
|
|
442
|
+
};
|
|
443
|
+
}
|