@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,398 @@
|
|
|
1
|
+
// edges.js — 1.8.11 记忆网络边表(recall-edges/v1)
|
|
2
|
+
//
|
|
3
|
+
// 与 links.jsonl 分开:links 是「词→卡」的检索边,edges 是「卡→卡」的语义边。
|
|
4
|
+
// 存储:<memoryRoot>/.longlive/recall/edges.jsonl,一行一条边。
|
|
5
|
+
// 读路径 fail-open:文件缺失/坏行只计数,不抛、不影响既有召回。
|
|
6
|
+
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { normalizeCardPath } from './links.mjs';
|
|
10
|
+
import { estimateTokens } from './recall-core.mjs';
|
|
11
|
+
import { isHistoricalQuery } from '../memory/lifecycle.js';
|
|
12
|
+
|
|
13
|
+
export { isHistoricalQuery };
|
|
14
|
+
|
|
15
|
+
export const EDGES_SCHEMA = 'recall-edges/v1';
|
|
16
|
+
export const EDGE_TYPES = Object.freeze([
|
|
17
|
+
'supersedes',
|
|
18
|
+
'superseded_by',
|
|
19
|
+
'deprecated_by',
|
|
20
|
+
'conflicts_with',
|
|
21
|
+
'answers_with',
|
|
22
|
+
'derived_from',
|
|
23
|
+
'mentions',
|
|
24
|
+
'same_topic',
|
|
25
|
+
]);
|
|
26
|
+
// 1-hop 扩展的优先级(越小越先注入)。
|
|
27
|
+
export const EXPAND_PRIORITY = Object.freeze({
|
|
28
|
+
deprecated_by: 0,
|
|
29
|
+
conflicts_with: 1,
|
|
30
|
+
superseded_by: 2,
|
|
31
|
+
answers_with: 3,
|
|
32
|
+
derived_from: 4,
|
|
33
|
+
supersedes: 5,
|
|
34
|
+
});
|
|
35
|
+
// 历史查询词判定统一走 src/memory/lifecycle.js 的 isHistoricalQuery(D9 单一实现)。
|
|
36
|
+
|
|
37
|
+
export function edgesPaths(memoryRoot) {
|
|
38
|
+
const dir = path.join(String(memoryRoot ?? ''), '.longlive', 'recall');
|
|
39
|
+
return { dir, file: path.join(dir, 'edges.jsonl') };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function normalizeText(value) {
|
|
43
|
+
return typeof value === 'string' ? value.trim() : '';
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function clampConfidence(value) {
|
|
47
|
+
const n = Number(value);
|
|
48
|
+
if (!Number.isFinite(n)) return 0.5;
|
|
49
|
+
if (n < 0) return 0;
|
|
50
|
+
if (n > 1) return 1;
|
|
51
|
+
return n;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** evidence: null | string | { path, sha256?, lines?:[start,end], quote? } */
|
|
55
|
+
export function normalizeEvidence(raw) {
|
|
56
|
+
if (raw == null) return null;
|
|
57
|
+
if (typeof raw === 'string') {
|
|
58
|
+
const text = raw.trim();
|
|
59
|
+
return text === '' ? null : { path: text };
|
|
60
|
+
}
|
|
61
|
+
if (typeof raw !== 'object' || Array.isArray(raw)) return null;
|
|
62
|
+
const evidence = {};
|
|
63
|
+
const p = normalizeText(raw.path);
|
|
64
|
+
if (p) evidence.path = p.replace(/\\/g, '/');
|
|
65
|
+
if (typeof raw.sha256 === 'string' && /^[0-9a-f]{64}$/i.test(raw.sha256)) {
|
|
66
|
+
evidence.sha256 = raw.sha256.toLowerCase();
|
|
67
|
+
}
|
|
68
|
+
if (Array.isArray(raw.lines) && raw.lines.length === 2) {
|
|
69
|
+
const start = Number(raw.lines[0]);
|
|
70
|
+
const end = Number(raw.lines[1]);
|
|
71
|
+
if (Number.isInteger(start) && Number.isInteger(end) && start >= 1 && end >= start) {
|
|
72
|
+
evidence.lines = [start, end];
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (typeof raw.quote === 'string' && raw.quote.trim() !== '') {
|
|
76
|
+
evidence.quote = raw.quote.trim();
|
|
77
|
+
}
|
|
78
|
+
return Object.keys(evidence).length > 0 ? evidence : null;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** 归一化一条边;非法返回 null(调用方计入 dropped)。 */
|
|
82
|
+
export function normalizeEdge(raw, { memoryRoot = '' } = {}) {
|
|
83
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
|
|
84
|
+
const from = normalizeCardPath(raw.from ?? raw.source, memoryRoot);
|
|
85
|
+
const to = normalizeCardPath(raw.to ?? raw.target, memoryRoot);
|
|
86
|
+
const type = normalizeText(raw.type);
|
|
87
|
+
if (!from || !to || from === to) return null;
|
|
88
|
+
if (!EDGE_TYPES.includes(type)) return null;
|
|
89
|
+
return {
|
|
90
|
+
from,
|
|
91
|
+
to,
|
|
92
|
+
type,
|
|
93
|
+
evidence: normalizeEvidence(raw.evidence),
|
|
94
|
+
confidence: clampConfidence(raw.confidence),
|
|
95
|
+
created_at: normalizeText(raw.created_at ?? raw.createdAt) || null,
|
|
96
|
+
source: normalizeText(raw.source) || null,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function edgeKey(edge) {
|
|
101
|
+
return `${edge.from}\u0000${edge.to}\u0000${edge.type}`;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** 去重:同 key 保留 confidence 更高的;持平保留先出现的。 */
|
|
105
|
+
export function dedupeEdges(edges) {
|
|
106
|
+
const byKey = new Map();
|
|
107
|
+
let deduped = 0;
|
|
108
|
+
for (const edge of edges) {
|
|
109
|
+
const key = edgeKey(edge);
|
|
110
|
+
const prev = byKey.get(key);
|
|
111
|
+
if (!prev) { byKey.set(key, edge); continue; }
|
|
112
|
+
deduped += 1;
|
|
113
|
+
if (edge.confidence > prev.confidence) byKey.set(key, edge);
|
|
114
|
+
}
|
|
115
|
+
return { edges: [...byKey.values()], deduped };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** supersedes ↔ superseded_by 对称补边(只补缺失方向)。 */
|
|
119
|
+
export function symmetrizeEdges(edges) {
|
|
120
|
+
const keys = new Set(edges.map(edgeKey));
|
|
121
|
+
const added = [];
|
|
122
|
+
const pairs = { supersedes: 'superseded_by', superseded_by: 'supersedes' };
|
|
123
|
+
for (const edge of edges) {
|
|
124
|
+
const reverseType = pairs[edge.type];
|
|
125
|
+
if (!reverseType) continue;
|
|
126
|
+
const reverse = { ...edge, from: edge.to, to: edge.from, type: reverseType };
|
|
127
|
+
const key = edgeKey(reverse);
|
|
128
|
+
if (!keys.has(key)) { keys.add(key); added.push(reverse); }
|
|
129
|
+
}
|
|
130
|
+
return { edges: [...edges, ...added], added: added.length };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function buildIndex(edges) {
|
|
134
|
+
const byFrom = new Map();
|
|
135
|
+
const byTo = new Map();
|
|
136
|
+
for (const edge of edges) {
|
|
137
|
+
if (!byFrom.has(edge.from)) byFrom.set(edge.from, []);
|
|
138
|
+
byFrom.get(edge.from).push(edge);
|
|
139
|
+
if (!byTo.has(edge.to)) byTo.set(edge.to, []);
|
|
140
|
+
byTo.get(edge.to).push(edge);
|
|
141
|
+
}
|
|
142
|
+
return { byFrom, byTo };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export function backlinksFor(cardPath, edges, { memoryRoot = '' } = {}) {
|
|
146
|
+
const rel = normalizeCardPath(cardPath, memoryRoot);
|
|
147
|
+
return edges.filter((edge) => edge.to === rel);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export function parseEdgesText(text, { memoryRoot = '' } = {}) {
|
|
151
|
+
const edges = [];
|
|
152
|
+
let badLines = 0;
|
|
153
|
+
let dropped = 0;
|
|
154
|
+
for (const rawLine of String(text ?? '').split(/\r?\n/)) {
|
|
155
|
+
const line = rawLine.trim();
|
|
156
|
+
if (line === '') continue;
|
|
157
|
+
let row;
|
|
158
|
+
try {
|
|
159
|
+
row = JSON.parse(line);
|
|
160
|
+
} catch {
|
|
161
|
+
badLines += 1;
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
const edge = normalizeEdge(row, { memoryRoot });
|
|
165
|
+
if (!edge) { dropped += 1; continue; }
|
|
166
|
+
edges.push(edge);
|
|
167
|
+
}
|
|
168
|
+
const deduped = dedupeEdges(edges);
|
|
169
|
+
const symmetric = symmetrizeEdges(deduped.edges);
|
|
170
|
+
return {
|
|
171
|
+
edges: symmetric.edges,
|
|
172
|
+
stats: {
|
|
173
|
+
parsed: edges.length,
|
|
174
|
+
badLines,
|
|
175
|
+
dropped,
|
|
176
|
+
deduped: deduped.deduped,
|
|
177
|
+
symmetrized: symmetric.added,
|
|
178
|
+
kept: symmetric.edges.length,
|
|
179
|
+
},
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* 读 edges.jsonl。mtime/size 缓存与 links.mjs 同款;坏文件 fail-open。
|
|
185
|
+
* @returns {{present:boolean,path:string,edges:Array,stats:object,error:string|null}}
|
|
186
|
+
*/
|
|
187
|
+
export function loadEdges({ memoryRoot, cache } = {}) {
|
|
188
|
+
const paths = edgesPaths(memoryRoot);
|
|
189
|
+
const empty = {
|
|
190
|
+
schema: EDGES_SCHEMA,
|
|
191
|
+
present: false,
|
|
192
|
+
path: paths.file,
|
|
193
|
+
bytes: 0,
|
|
194
|
+
mtimeMs: 0,
|
|
195
|
+
size: 0,
|
|
196
|
+
edges: [],
|
|
197
|
+
stats: { parsed: 0, badLines: 0, dropped: 0, deduped: 0, symmetrized: 0, kept: 0 },
|
|
198
|
+
error: null,
|
|
199
|
+
};
|
|
200
|
+
try {
|
|
201
|
+
const stat = fs.statSync(paths.file);
|
|
202
|
+
if (cache && cache.path === paths.file && cache.mtimeMs === stat.mtimeMs
|
|
203
|
+
&& cache.size === stat.size && cache.store) {
|
|
204
|
+
return cache.store;
|
|
205
|
+
}
|
|
206
|
+
const text = fs.readFileSync(paths.file, 'utf8');
|
|
207
|
+
const parsed = parseEdgesText(text, { memoryRoot });
|
|
208
|
+
const store = {
|
|
209
|
+
...empty,
|
|
210
|
+
present: true,
|
|
211
|
+
bytes: Buffer.byteLength(text, 'utf8'),
|
|
212
|
+
mtimeMs: stat.mtimeMs,
|
|
213
|
+
size: stat.size,
|
|
214
|
+
edges: parsed.edges,
|
|
215
|
+
stats: parsed.stats,
|
|
216
|
+
};
|
|
217
|
+
if (cache) {
|
|
218
|
+
cache.path = paths.file;
|
|
219
|
+
cache.mtimeMs = stat.mtimeMs;
|
|
220
|
+
cache.size = stat.size;
|
|
221
|
+
cache.store = store;
|
|
222
|
+
}
|
|
223
|
+
return store;
|
|
224
|
+
} catch (error) {
|
|
225
|
+
const code = error?.code ?? 'E_EDGES_READ';
|
|
226
|
+
if (code === 'ENOENT' || code === 'ENOTDIR') {
|
|
227
|
+
const store = { ...empty, present: false };
|
|
228
|
+
if (cache) { cache.path = paths.file; cache.mtimeMs = 0; cache.size = -1; cache.store = store; }
|
|
229
|
+
return store;
|
|
230
|
+
}
|
|
231
|
+
return { ...empty, error: `E_EDGES_READ:${code}` };
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
export function serializeEdges(edges) {
|
|
236
|
+
return edges.map((edge) => JSON.stringify(edge)).join('\n') + '\n';
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function cardMapOf(cards) {
|
|
240
|
+
const map = new Map();
|
|
241
|
+
for (const card of Array.isArray(cards) ? cards : []) {
|
|
242
|
+
if (!card || typeof card !== 'object') continue;
|
|
243
|
+
const key = normalizeCardPath(card.path ?? card.rel ?? card.abs ?? '', '');
|
|
244
|
+
if (key) map.set(key, card);
|
|
245
|
+
}
|
|
246
|
+
return map;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function clipSentence(text, maxChars = 120) {
|
|
250
|
+
const flat = String(text ?? '').replace(/\s+/g, ' ').trim();
|
|
251
|
+
return flat.length > maxChars ? `${flat.slice(0, Math.max(1, maxChars - 1))}…` : flat;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** 目标卡正文首句(跳过 markdown 标题,剥列表符/引用符/[[wikilink]])。 */
|
|
255
|
+
function firstBodySentence(card) {
|
|
256
|
+
const body = typeof card?.body === 'string' ? card.body : '';
|
|
257
|
+
for (const rawLine of body.split(/\r?\n/)) {
|
|
258
|
+
const trimmed = rawLine.trim();
|
|
259
|
+
if (trimmed === '' || trimmed.startsWith('#')) continue;
|
|
260
|
+
const line = trimmed
|
|
261
|
+
.replace(/^[-*>]\s*/, '')
|
|
262
|
+
.replace(/\[\[([^\]]+)\]\]/g, '$1')
|
|
263
|
+
.trim();
|
|
264
|
+
if (line !== '') return clipSentence(line, 120);
|
|
265
|
+
}
|
|
266
|
+
return '';
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// H3:扩展条目的 excerpt 不只是关系标签 + evidence.path,还要带一句可指认的具体话:
|
|
270
|
+
// evidence.quote 优先(边自己的证据句),其次目标卡 summary,再其次目标卡正文首句。
|
|
271
|
+
function relationSentence(edge, target) {
|
|
272
|
+
const typeLabel = {
|
|
273
|
+
deprecated_by: '已被取代',
|
|
274
|
+
conflicts_with: '与此卡冲突',
|
|
275
|
+
superseded_by: '被后续卡取代',
|
|
276
|
+
answers_with: '回答该问题',
|
|
277
|
+
derived_from: '派生自',
|
|
278
|
+
supersedes: '取代了',
|
|
279
|
+
mentions: '提及',
|
|
280
|
+
same_topic: '同主题',
|
|
281
|
+
}[edge.type] ?? edge.type;
|
|
282
|
+
const evidence = edge.evidence?.path ? `,证据 ${edge.evidence.path}` : '';
|
|
283
|
+
const quote = typeof edge.evidence?.quote === 'string' ? clipSentence(edge.evidence.quote, 120) : '';
|
|
284
|
+
const summary = typeof target?.summary === 'string' && target.summary.trim() !== ''
|
|
285
|
+
? clipSentence(target.summary, 120)
|
|
286
|
+
: '';
|
|
287
|
+
const specific = quote || summary || firstBodySentence(target);
|
|
288
|
+
return `${typeLabel}${evidence}${specific === '' ? '' : `:${specific}`}`;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* 1-hop 扩展。
|
|
293
|
+
* @param {Array<{path:string,title?:string}>} baseItems 已召回项
|
|
294
|
+
* @param {object} opts
|
|
295
|
+
* @param {Array} opts.edges 归一化边
|
|
296
|
+
* @param {number} opts.budget 剩余 token 预算
|
|
297
|
+
* @param {Array} [opts.cards] 卡列表(title/summary)
|
|
298
|
+
* @param {(cardPath:string)=>string|null} [opts.lifecycleOf] 返回 'canonical'|'historical'|null
|
|
299
|
+
* @param {boolean} [opts.allowHistorical] 历史查询才放行 historical 目标
|
|
300
|
+
* @param {string} [opts.queryText] 用于判断是否历史查询(allowHistorical 未显式给时)
|
|
301
|
+
* @param {{memoryRoot?:string}} [opts.pathOptions]
|
|
302
|
+
*/
|
|
303
|
+
export function expandEdges(baseItems, {
|
|
304
|
+
edges = [],
|
|
305
|
+
budget = 2000,
|
|
306
|
+
cards = [],
|
|
307
|
+
lifecycleOf = null,
|
|
308
|
+
allowHistorical,
|
|
309
|
+
queryText = '',
|
|
310
|
+
memoryRoot = '',
|
|
311
|
+
} = {}) {
|
|
312
|
+
const allowHistory = allowHistorical ?? isHistoricalQuery(queryText);
|
|
313
|
+
const cardsByPath = cardMapOf(cards);
|
|
314
|
+
const { byFrom, byTo } = buildIndex(edges);
|
|
315
|
+
const basePaths = new Set();
|
|
316
|
+
for (const item of baseItems) {
|
|
317
|
+
const rel = normalizeCardPath(item?.path ?? '', memoryRoot);
|
|
318
|
+
if (rel) basePaths.add(rel);
|
|
319
|
+
}
|
|
320
|
+
const candidates = [];
|
|
321
|
+
const walked = new Set();
|
|
322
|
+
for (const item of baseItems) {
|
|
323
|
+
const rel = normalizeCardPath(item?.path ?? '', memoryRoot);
|
|
324
|
+
if (!rel) continue;
|
|
325
|
+
const incident = [];
|
|
326
|
+
for (const edge of byFrom.get(rel) ?? []) incident.push({ edge, target: edge.to });
|
|
327
|
+
for (const edge of byTo.get(rel) ?? []) incident.push({ edge, target: edge.from });
|
|
328
|
+
for (const { edge, target } of incident) {
|
|
329
|
+
if (!(edge.type in EXPAND_PRIORITY)) continue;
|
|
330
|
+
walked.add(edgeKey(edge));
|
|
331
|
+
candidates.push({ edge, target, priority: EXPAND_PRIORITY[edge.type] });
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
candidates.sort((a, b) => a.priority - b.priority
|
|
335
|
+
|| b.edge.confidence - a.edge.confidence
|
|
336
|
+
|| edgeKey(a.edge).localeCompare(edgeKey(b.edge)));
|
|
337
|
+
|
|
338
|
+
const items = [];
|
|
339
|
+
const seen = new Set(basePaths);
|
|
340
|
+
const dropped = [];
|
|
341
|
+
const dropCounts = { missingCard: 0, historical: 0, archived: 0, budget: 0 };
|
|
342
|
+
let tokens = 0;
|
|
343
|
+
let injected = 0;
|
|
344
|
+
for (const candidate of candidates) {
|
|
345
|
+
if (seen.has(candidate.target)) continue;
|
|
346
|
+
const card = cardsByPath.get(candidate.target);
|
|
347
|
+
if (!card) { dropCounts.missingCard += 1; dropped.push({ path: candidate.target, reason: 'missing-card' }); continue; }
|
|
348
|
+
const lifecycle = lifecycleOf ? lifecycleOf(candidate.target) : null;
|
|
349
|
+
if (lifecycle === 'historical' && !allowHistory) {
|
|
350
|
+
dropCounts.historical += 1;
|
|
351
|
+
dropped.push({ path: candidate.target, reason: 'historical' });
|
|
352
|
+
continue;
|
|
353
|
+
}
|
|
354
|
+
// M21 归档修边:archived/forgotten 目标不再注入(历史查询也不放行归档卡)。
|
|
355
|
+
const targetStatus = card?.fields?.status ?? card?.status ?? 'active';
|
|
356
|
+
if (targetStatus === 'archived' || targetStatus === 'forgotten') {
|
|
357
|
+
dropCounts.archived += 1;
|
|
358
|
+
dropped.push({ path: candidate.target, reason: 'archived' });
|
|
359
|
+
continue;
|
|
360
|
+
}
|
|
361
|
+
const title = String(card.title ?? card.fields?.title ?? candidate.target);
|
|
362
|
+
const excerpt = relationSentence(candidate.edge, card);
|
|
363
|
+
const text = `- 《${title}》(${candidate.target})\n${excerpt}`;
|
|
364
|
+
const cost = estimateTokens(text);
|
|
365
|
+
if (tokens + cost > budget) { dropCounts.budget += 1; dropped.push({ path: candidate.target, reason: 'budget' }); continue; }
|
|
366
|
+
tokens += cost;
|
|
367
|
+
injected += 1;
|
|
368
|
+
seen.add(candidate.target);
|
|
369
|
+
items.push({
|
|
370
|
+
path: candidate.target,
|
|
371
|
+
title,
|
|
372
|
+
score: 0,
|
|
373
|
+
excerpt,
|
|
374
|
+
lifecycle,
|
|
375
|
+
edge: {
|
|
376
|
+
from: candidate.edge.from,
|
|
377
|
+
to: candidate.edge.to,
|
|
378
|
+
type: candidate.edge.type,
|
|
379
|
+
evidence: candidate.edge.evidence,
|
|
380
|
+
},
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
return {
|
|
384
|
+
items,
|
|
385
|
+
tokens,
|
|
386
|
+
walked: walked.size,
|
|
387
|
+
injected,
|
|
388
|
+
dropped,
|
|
389
|
+
counts: {
|
|
390
|
+
walked: walked.size,
|
|
391
|
+
injected,
|
|
392
|
+
droppedHistorical: dropCounts.historical,
|
|
393
|
+
droppedArchived: dropCounts.archived,
|
|
394
|
+
droppedMissingCard: dropCounts.missingCard,
|
|
395
|
+
droppedBudget: dropCounts.budget,
|
|
396
|
+
},
|
|
397
|
+
};
|
|
398
|
+
}
|