@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,357 @@
|
|
|
1
|
+
// Proactive recall: search memory cards without a vector store.
|
|
2
|
+
//
|
|
3
|
+
// The score is deliberately simple and reproducible: token hits in the title,
|
|
4
|
+
// tags and body, plus a character-bigram Dice similarity and a whole-query
|
|
5
|
+
// phrase bonus. No randomness, no time input, no new dependency — the same
|
|
6
|
+
// tree and the same query always produce byte-identical results.
|
|
7
|
+
//
|
|
8
|
+
// This tool is READ-ONLY. It never writes a file, never advances the index and
|
|
9
|
+
// never creates `.longlive/`. `locked` cards are searchable: being locked means
|
|
10
|
+
// "never decay or merge", not "hidden".
|
|
11
|
+
|
|
12
|
+
import { memoryError, memoryRootFromConfig } from './paths.js';
|
|
13
|
+
import { scanCards } from './index.js';
|
|
14
|
+
import { readVerifiedCardAnchors } from './card-anchors.js';
|
|
15
|
+
import { searchEventsReadOnly } from './event-index.js';
|
|
16
|
+
import { isHistoricalQuery, readLifecycle } from './lifecycle.js';
|
|
17
|
+
// 2.0.0 W3b(M32):archive:true 的冷档检索走 fail-closed 兜底门(A6 五码族)。
|
|
18
|
+
import { searchArchiveFallback } from '../recall/archive-fallback.mjs';
|
|
19
|
+
import { archiveStatePathFor } from '../recall/archive-state.mjs';
|
|
20
|
+
|
|
21
|
+
export const RECALL_DEFAULT_TOPK = 3;
|
|
22
|
+
export const RECALL_MAX_TOPK = 20;
|
|
23
|
+
export const RECALL_STATUSES = Object.freeze(['active', 'locked', 'archived', 'any']);
|
|
24
|
+
// SPEC-1.8.11 D9:historical 卡在工具层同样要沉层(与 pre-step 注入的 lifecycleRank 一致),
|
|
25
|
+
// 但工具层不改条数/过滤:只按权重改分数,同一 lifecycle 内原有分数序不变。
|
|
26
|
+
export const HISTORICAL_SCORE_WEIGHT = 0.3;
|
|
27
|
+
|
|
28
|
+
const CJK_RUN = /[\u3400-\u9fff]+/g;
|
|
29
|
+
const ASCII_WORD = /[a-z0-9_]{2,}/g;
|
|
30
|
+
|
|
31
|
+
/** Collapse whitespace for the 1-line excerpt. */
|
|
32
|
+
function collapse(text) {
|
|
33
|
+
return String(text ?? '').replace(/\s+/g, ' ').trim();
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Tokens for scoring: ASCII words (>=2) plus CJK chars and their bigrams. */
|
|
37
|
+
export function recallTokens(text) {
|
|
38
|
+
const lower = String(text ?? '').toLowerCase();
|
|
39
|
+
const tokens = [];
|
|
40
|
+
for (const match of lower.match(ASCII_WORD) ?? []) tokens.push(match);
|
|
41
|
+
for (const run of lower.match(CJK_RUN) ?? []) {
|
|
42
|
+
const chars = [...run];
|
|
43
|
+
for (const char of chars) tokens.push(char);
|
|
44
|
+
for (let i = 0; i + 1 < chars.length; i += 1) tokens.push(chars[i] + chars[i + 1]);
|
|
45
|
+
}
|
|
46
|
+
return tokens;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function countToken(tokens, token) {
|
|
50
|
+
let count = 0;
|
|
51
|
+
for (const item of tokens) if (item === token) count += 1;
|
|
52
|
+
return count;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Dice coefficient over character bigrams (0..1); cheap fuzzy similarity. */
|
|
56
|
+
function diceBigrams(left, right) {
|
|
57
|
+
const grams = (text) => {
|
|
58
|
+
const chars = [...collapse(text).toLowerCase().replace(/\s+/g, '')];
|
|
59
|
+
if (chars.length < 2) return chars;
|
|
60
|
+
const out = [];
|
|
61
|
+
for (let i = 0; i + 1 < chars.length; i += 1) out.push(chars[i] + chars[i + 1]);
|
|
62
|
+
return out;
|
|
63
|
+
};
|
|
64
|
+
const a = grams(left);
|
|
65
|
+
const b = grams(right);
|
|
66
|
+
if (a.length === 0 || b.length === 0) return 0;
|
|
67
|
+
const pool = new Map();
|
|
68
|
+
for (const gram of b) pool.set(gram, (pool.get(gram) ?? 0) + 1);
|
|
69
|
+
let overlap = 0;
|
|
70
|
+
for (const gram of a) {
|
|
71
|
+
const remaining = pool.get(gram) ?? 0;
|
|
72
|
+
if (remaining > 0) {
|
|
73
|
+
overlap += 1;
|
|
74
|
+
pool.set(gram, remaining - 1);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return (2 * overlap) / (a.length + b.length);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function uniqueQueryTokens(query) {
|
|
81
|
+
return [...new Set(recallTokens(query))];
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Score one card against one query. Exported so the tests (and the mark-core
|
|
86
|
+
* script) can reproduce a single number without going through the tool layer.
|
|
87
|
+
*/
|
|
88
|
+
export function scoreCard(query, card) {
|
|
89
|
+
const tokens = uniqueQueryTokens(query);
|
|
90
|
+
if (tokens.length === 0) return { score: 0, hits: [] };
|
|
91
|
+
|
|
92
|
+
const titleText = collapse(card.title);
|
|
93
|
+
const tagText = collapse((card.fields?.tags ?? []).join(' '));
|
|
94
|
+
const bodyText = collapse(card.body ?? card.summary ?? '');
|
|
95
|
+
const titleTokens = recallTokens(titleText);
|
|
96
|
+
const tagTokens = recallTokens(tagText);
|
|
97
|
+
const bodyTokens = recallTokens(bodyText);
|
|
98
|
+
const normalizedQuery = collapse(query).toLowerCase();
|
|
99
|
+
|
|
100
|
+
let score = 0;
|
|
101
|
+
const hits = [];
|
|
102
|
+
for (const token of tokens) {
|
|
103
|
+
const inTitle = countToken(titleTokens, token) > 0;
|
|
104
|
+
const inTags = countToken(tagTokens, token) > 0;
|
|
105
|
+
const bodyCount = countToken(bodyTokens, token);
|
|
106
|
+
if (inTitle) score += 5;
|
|
107
|
+
if (inTags) score += 3;
|
|
108
|
+
if (bodyCount > 0) score += Math.min(bodyCount, 3);
|
|
109
|
+
if (inTitle || inTags || bodyCount > 0) hits.push(token);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
if (normalizedQuery.length > 0 && titleText.toLowerCase().includes(normalizedQuery)) score += 6;
|
|
113
|
+
if (normalizedQuery.length > 0 && bodyText.toLowerCase().includes(normalizedQuery)) score += 2;
|
|
114
|
+
score += diceBigrams(normalizedQuery, `${titleText} ${bodyText}`) * 4;
|
|
115
|
+
|
|
116
|
+
score = Math.round(score * 100) / 100;
|
|
117
|
+
return { score, hits };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** A short excerpt centered on the first matching token, in body order. */
|
|
121
|
+
function excerptFor(query, card) {
|
|
122
|
+
const body = collapse(card.body ?? card.summary ?? '');
|
|
123
|
+
if (body === '') return collapse(card.title).slice(0, 120);
|
|
124
|
+
const lower = body.toLowerCase();
|
|
125
|
+
let at = -1;
|
|
126
|
+
for (const token of uniqueQueryTokens(query)) {
|
|
127
|
+
const found = lower.indexOf(token.toLowerCase());
|
|
128
|
+
if (found >= 0 && (at < 0 || found < at)) at = found;
|
|
129
|
+
}
|
|
130
|
+
if (at < 0) return body.slice(0, 120);
|
|
131
|
+
const start = Math.max(0, at - 40);
|
|
132
|
+
const end = Math.min(body.length, at + 80);
|
|
133
|
+
const prefix = start > 0 ? '…' : '';
|
|
134
|
+
const suffix = end < body.length ? '…' : '';
|
|
135
|
+
return `${prefix}${body.slice(start, end)}${suffix}`;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function normalizeTopK(value) {
|
|
139
|
+
if (value == null) return RECALL_DEFAULT_TOPK;
|
|
140
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
|
141
|
+
throw memoryError('E_BAD_ARGUMENT', `topK 必须是 1..${RECALL_MAX_TOPK} 的整数,收到 ${JSON.stringify(value)}`);
|
|
142
|
+
}
|
|
143
|
+
const rounded = Math.trunc(value);
|
|
144
|
+
return Math.min(RECALL_MAX_TOPK, Math.max(1, rounded));
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function normalizeRoom(room) {
|
|
148
|
+
if (room == null || room === '') return null;
|
|
149
|
+
if (typeof room !== 'string') throw memoryError('E_BAD_ARGUMENT', 'room 必须是字符串,例如 "topics" 或 "journal"');
|
|
150
|
+
const text = room.trim().replace(/\\/g, '/').replace(/\/+$/, '');
|
|
151
|
+
if (text === '' || text.startsWith('/') || text.includes('..')) {
|
|
152
|
+
throw memoryError('E_BAD_ARGUMENT', `room 必须是记忆根下的相对目录(topics / journal / 子目录),收到「${room}」`);
|
|
153
|
+
}
|
|
154
|
+
return text;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function statusesFor(status) {
|
|
158
|
+
if (status == null || status === '') return ['active', 'locked'];
|
|
159
|
+
if (typeof status !== 'string' || !RECALL_STATUSES.includes(status)) {
|
|
160
|
+
throw memoryError('E_BAD_ARGUMENT', `status 只能是 ${RECALL_STATUSES.join(' / ')},收到「${status}」`);
|
|
161
|
+
}
|
|
162
|
+
if (status === 'any') return ['active', 'locked', 'archived'];
|
|
163
|
+
return [status];
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* `memory_recall` implementation.
|
|
168
|
+
*
|
|
169
|
+
* @param {{query?: string, topK?: number, room?: string, status?: string}} args
|
|
170
|
+
* @param {{memoryRoot?: string, memRoot?: string}} config
|
|
171
|
+
* @returns {object} `{ ok, status, query, topK, room, statuses, scanned, count, results }`
|
|
172
|
+
*/
|
|
173
|
+
export function memoryRecall(args, config = {}) {
|
|
174
|
+
const rawQuery = args?.query;
|
|
175
|
+
if (typeof rawQuery !== 'string' || rawQuery.trim() === '') {
|
|
176
|
+
throw memoryError(
|
|
177
|
+
'E_RECALL_EMPTY_QUERY',
|
|
178
|
+
'memory_recall 需要 query(自然语言或关键词)— 例如 {"query":"听觉 训练","topK":3}',
|
|
179
|
+
);
|
|
180
|
+
}
|
|
181
|
+
// 2.0.0 W3b(M32):archive:true = 冷档 fail-closed 视图(返回 Promise,宿主 await)。
|
|
182
|
+
// 空 query 仍在上面的同步分支里抛,参数错误不变成未处理的 rejection。
|
|
183
|
+
if (args?.archive === true) return memoryRecallArchive(args, config);
|
|
184
|
+
const query = rawQuery.trim();
|
|
185
|
+
const topK = normalizeTopK(args?.topK);
|
|
186
|
+
const room = normalizeRoom(args?.room);
|
|
187
|
+
const statuses = statusesFor(args?.status);
|
|
188
|
+
const root = memoryRootFromConfig(config);
|
|
189
|
+
// 显式历史查询(以前/旧版/被取代…)不降权;普通查询把 historical 卡乘权重沉下去。
|
|
190
|
+
const historyQuery = isHistoricalQuery(query);
|
|
191
|
+
|
|
192
|
+
const scanned = scanCards(root);
|
|
193
|
+
const sidecar = readVerifiedCardAnchors({ memoryRoot: root }).links;
|
|
194
|
+
const includeAuto = args?.includeAuto === true || args?.archive === true;
|
|
195
|
+
const results = [];
|
|
196
|
+
for (const card of scanned) {
|
|
197
|
+
// topics/auto/ 卡默认不进手动召回面;归档视图(archive:true)显式放开。
|
|
198
|
+
if (card.auto === true && !includeAuto) continue;
|
|
199
|
+
const status = card.fields?.status ?? 'active';
|
|
200
|
+
if (!statuses.includes(status)) continue;
|
|
201
|
+
if (room && !(card.rel === room || card.rel.startsWith(`${room}/`))) continue;
|
|
202
|
+
const { score, hits } = scoreCard(query, card);
|
|
203
|
+
if (score <= 0 || hits.length === 0) continue;
|
|
204
|
+
const lifecycle = readLifecycle(card);
|
|
205
|
+
// historical 只在非历史查询里降权;canonical/普通卡不变(权重 1)。
|
|
206
|
+
const weight = lifecycle === 'historical' && !historyQuery ? HISTORICAL_SCORE_WEIGHT : 1;
|
|
207
|
+
const weightedScore = weight === 1 ? score : Math.round(score * weight * 100) / 100;
|
|
208
|
+
const link = sidecar.get(card.rel);
|
|
209
|
+
results.push({
|
|
210
|
+
path: card.rel,
|
|
211
|
+
title: card.title,
|
|
212
|
+
score: weightedScore,
|
|
213
|
+
lifecycle,
|
|
214
|
+
excerpt: excerptFor(query, card),
|
|
215
|
+
body: card.body ?? '',
|
|
216
|
+
bodyChars: card.bodyChars ?? Array.from(String(card.body ?? '')).length,
|
|
217
|
+
...(card.bodyTruncated === true ? { bodyTruncated: true } : {}),
|
|
218
|
+
...(card.auto === true ? { auto: true } : {}),
|
|
219
|
+
...(link && Array.isArray(link.sourceEventIds) && link.sourceEventIds.length > 0
|
|
220
|
+
? { sourceEventIds: link.sourceEventIds }
|
|
221
|
+
: {}),
|
|
222
|
+
...(link && Array.isArray(link.anchors) && link.anchors.length > 0
|
|
223
|
+
? { anchors: link.anchors }
|
|
224
|
+
: {}),
|
|
225
|
+
...(link?.legacy === true ? { legacy: true } : {}),
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
results.sort((left, right) => {
|
|
230
|
+
if (right.score !== left.score) return right.score - left.score;
|
|
231
|
+
return left.path < right.path ? -1 : left.path > right.path ? 1 : 0;
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
// 1.8.2 D2: auto-card layer removed. Only curated markdown cards are
|
|
235
|
+
// recalled; cards.jsonl stays as a cold read-only archive.
|
|
236
|
+
const weighted = [...results].sort((left, right) => {
|
|
237
|
+
const l = left.score * 1.12;
|
|
238
|
+
const r = right.score * 1.12;
|
|
239
|
+
if (r !== l) return r - l;
|
|
240
|
+
return left.path < right.path ? -1 : left.path > right.path ? 1 : 0;
|
|
241
|
+
});
|
|
242
|
+
// C 召回面(DESIGN v0.5.1 §8):手动召回默认给 5 条;深档/显式 topK 上限仍 20。
|
|
243
|
+
const manualCap = Math.min(5, topK);
|
|
244
|
+
const manualResults = weighted.slice(0, manualCap);
|
|
245
|
+
const top = [...manualResults].slice(0, topK);
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
const base = {
|
|
249
|
+
ok: true,
|
|
250
|
+
query,
|
|
251
|
+
topK,
|
|
252
|
+
room,
|
|
253
|
+
statuses,
|
|
254
|
+
scanned: scanned.length,
|
|
255
|
+
scannedEvents: null,
|
|
256
|
+
autoCards: null,
|
|
257
|
+
eventFallback: null,
|
|
258
|
+
count: top.length,
|
|
259
|
+
results: top,
|
|
260
|
+
};
|
|
261
|
+
if (top.length === 0) {
|
|
262
|
+
return {
|
|
263
|
+
...base,
|
|
264
|
+
status: 'empty',
|
|
265
|
+
code: 'E_RECALL_NO_MATCH',
|
|
266
|
+
message: `没有卡片命中「${query}」— 换更短/更具体的关键词,或放宽 room/status 过滤;本次扫描 ${scanned.length} 张卡`,
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
return { ...base, status: 'ok' };
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* 2.0.0 W3b(M32):`memory_recall({ archive:true })` 的冷档 fail-closed 视图。
|
|
274
|
+
*
|
|
275
|
+
* 与本地卡召回分离保证两点:① 内部同步调用方(migrate-lifecycle / recall-v2)
|
|
276
|
+
* 拿到的仍是普通对象,不会被 Promise 静默替换;② 冷档不可用时必须抛出
|
|
277
|
+
* `E_HG_ARCHIVE_OFFLINE` / `E_HG_ARCHIVE_MIGRATE_MISMATCH`(W5/W6),
|
|
278
|
+
* 不许记成「没有命中」的空成功。
|
|
279
|
+
*
|
|
280
|
+
* 返回形状(docs/CONFIG.md 归档段):`{ ok, archived:true, available, items, count,
|
|
281
|
+
* manifestSha, stats, code? }`;items 只给 title/sessionId 前 8 位/turn/ts/score/source,
|
|
282
|
+
* 不带 excerpt、不带绝对路径(§20 隐私)。
|
|
283
|
+
*
|
|
284
|
+
* @param {{query?: string, topK?: number}} args
|
|
285
|
+
* @param {{memoryRoot?: string, memRoot?: string, archiveRoot?: string, archiveStatePath?: string, archiveFailOpen?: boolean}} config
|
|
286
|
+
* @returns {Promise<object>}
|
|
287
|
+
*/
|
|
288
|
+
export async function memoryRecallArchive(args, config = {}) {
|
|
289
|
+
const root = memoryRootFromConfig(config);
|
|
290
|
+
const query = String(args?.query ?? '').trim();
|
|
291
|
+
const limit = Math.min(3, Math.max(1, Number.isFinite(args?.topK) ? Math.trunc(args.topK) : 3));
|
|
292
|
+
const result = await searchArchiveFallback({
|
|
293
|
+
memoryRoot: root,
|
|
294
|
+
queryText: query,
|
|
295
|
+
limit,
|
|
296
|
+
archiveRoot: typeof config.archiveRoot === 'string' ? config.archiveRoot : '',
|
|
297
|
+
archiveStatePath: typeof config.archiveStatePath === 'string'
|
|
298
|
+
? config.archiveStatePath
|
|
299
|
+
: archiveStatePathFor(root),
|
|
300
|
+
failOpen: config.archiveFailOpen === true,
|
|
301
|
+
});
|
|
302
|
+
if (result.ok === true && result.available === true) {
|
|
303
|
+
const items = result.items.slice(0, 3).map((item) => {
|
|
304
|
+
const sessionId = String(item.sessionId ?? '').slice(0, 8);
|
|
305
|
+
return {
|
|
306
|
+
title: `已归档 ${sessionId || '未知会话'}#${item.turn ?? '?'}`,
|
|
307
|
+
sessionId,
|
|
308
|
+
turn: item.turn ?? null,
|
|
309
|
+
ts: item.ts ?? null,
|
|
310
|
+
score: item.score ?? null,
|
|
311
|
+
source: 'archive',
|
|
312
|
+
};
|
|
313
|
+
});
|
|
314
|
+
return {
|
|
315
|
+
ok: true,
|
|
316
|
+
status: items.length > 0 ? 'ok' : 'empty',
|
|
317
|
+
archived: true,
|
|
318
|
+
available: true,
|
|
319
|
+
query,
|
|
320
|
+
items,
|
|
321
|
+
count: items.length,
|
|
322
|
+
manifestSha: result.manifestSha,
|
|
323
|
+
stats: result.stats,
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
if (result.ok === true && result.available === false) {
|
|
327
|
+
// 未配置冷档 → 旧语义静默空(不报错、不算命中)。
|
|
328
|
+
return {
|
|
329
|
+
ok: true,
|
|
330
|
+
status: 'empty',
|
|
331
|
+
archived: true,
|
|
332
|
+
available: false,
|
|
333
|
+
configured: result.configured === true,
|
|
334
|
+
query,
|
|
335
|
+
items: [],
|
|
336
|
+
count: 0,
|
|
337
|
+
manifestSha: null,
|
|
338
|
+
stats: null,
|
|
339
|
+
...(result.code ? { code: result.code } : {}),
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
// READONLY / LOW_SPACE / WRONG_VOLUME:v1 只降级告警不抛(not_run,不得记 PASS)。
|
|
343
|
+
return {
|
|
344
|
+
ok: true,
|
|
345
|
+
status: 'degraded',
|
|
346
|
+
archived: true,
|
|
347
|
+
available: false,
|
|
348
|
+
degraded: true,
|
|
349
|
+
query,
|
|
350
|
+
items: [],
|
|
351
|
+
count: 0,
|
|
352
|
+
manifestSha: null,
|
|
353
|
+
stats: null,
|
|
354
|
+
code: result.code ?? null,
|
|
355
|
+
...(result.reason ? { reason: result.reason } : {}),
|
|
356
|
+
};
|
|
357
|
+
}
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
// src/memory/reconcile.js — event/card/audit/anchor reconciliation + promotion.
|
|
2
|
+
//
|
|
3
|
+
// Read-mostly maintenance:
|
|
4
|
+
// * compare events.db, cards.jsonl, events.audit, card-audit, card-anchors
|
|
5
|
+
// * report set differences instead of silently trusting any one layer
|
|
6
|
+
// * surface "event + auto card exist, but no curated card / INDEX row" facts
|
|
7
|
+
// (the e219 turn-205 "朋友五问" live case) and allow a reviewed promotion.
|
|
8
|
+
// Default is dry-run: nothing is written unless write:true / promote dryRun:false.
|
|
9
|
+
|
|
10
|
+
import crypto from 'node:crypto';
|
|
11
|
+
import fs from 'node:fs';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
|
|
14
|
+
import { memoryRootFromConfig, resolveInside, relativePath } from './paths.js';
|
|
15
|
+
import { readAutoCards, cardsPathOf } from './auto-cards.js';
|
|
16
|
+
import { readCardAnchors } from './card-anchors.js';
|
|
17
|
+
import { openEventIndex } from './event-index.js';
|
|
18
|
+
import { readState, writeFileAtomic } from './state.js';
|
|
19
|
+
import { scanCards } from './index.js';
|
|
20
|
+
import { memoryIndex } from './index.js';
|
|
21
|
+
import { priorityFor } from './card-priority.js';
|
|
22
|
+
|
|
23
|
+
export const RECONCILE_SCHEMA = 'index-reconcile/v1';
|
|
24
|
+
export const RECONCILE_FILE_PREFIX = 'reconcile-';
|
|
25
|
+
|
|
26
|
+
const HIGH_VALUE_KIND = new Set(['conclusion', 'decision', 'incident']);
|
|
27
|
+
const HIGH_VALUE_RE = /五问|智能体工程师|决定|结论|不能忘|重要|规则|承诺|教训|根因|必须|以后/iu;
|
|
28
|
+
|
|
29
|
+
function sha1(text) {
|
|
30
|
+
return crypto.createHash('sha1').update(String(text)).digest('hex');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function readJsonl(file) {
|
|
34
|
+
const rows = [];
|
|
35
|
+
let badLines = 0;
|
|
36
|
+
let raw = '';
|
|
37
|
+
try { raw = fs.readFileSync(file, 'utf8'); } catch { return { rows, badLines, present: false }; }
|
|
38
|
+
for (const line of raw.split('\n')) {
|
|
39
|
+
if (line.trim() === '') continue;
|
|
40
|
+
try { rows.push(JSON.parse(line)); } catch { badLines += 1; }
|
|
41
|
+
}
|
|
42
|
+
return { rows, badLines, present: true };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function readEvents(root) {
|
|
46
|
+
const dbPath = resolveInside(root, path.join('.longlive', 'index', 'events.db'));
|
|
47
|
+
if (!fs.existsSync(dbPath)) return { ok: false, rows: [], total: 0, code: 'E_EVENTS_INDEX_MISSING' };
|
|
48
|
+
let index = null;
|
|
49
|
+
try {
|
|
50
|
+
index = openEventIndex({ memoryRoot: root });
|
|
51
|
+
const total = index.count();
|
|
52
|
+
const rows = [];
|
|
53
|
+
for (let offset = 0; offset < total; offset += 500) rows.push(...index.listEvents({ limit: 500, offset }));
|
|
54
|
+
return { ok: true, rows, total };
|
|
55
|
+
} catch (error) {
|
|
56
|
+
return { ok: false, rows: [], total: 0, code: error?.code ?? 'E_EVENTS_INDEX_READ', message: String(error?.message ?? error) };
|
|
57
|
+
} finally {
|
|
58
|
+
try { index?.close(); } catch { /* best effort */ }
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function curatedSourceIds(root) {
|
|
63
|
+
const ids = new Set();
|
|
64
|
+
const links = readCardAnchors(root).values();
|
|
65
|
+
for (const link of links) {
|
|
66
|
+
for (const id of Array.isArray(link.sourceEventIds) ? link.sourceEventIds : []) {
|
|
67
|
+
if (typeof id === 'string' && id !== '') ids.add(id);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
for (const card of scanCards(root)) {
|
|
71
|
+
const raw = card.fields?.sourceEventIds;
|
|
72
|
+
if (Array.isArray(raw)) for (const id of raw) if (typeof id === 'string') ids.add(id);
|
|
73
|
+
if (typeof raw === 'string') {
|
|
74
|
+
try {
|
|
75
|
+
const parsed = JSON.parse(raw);
|
|
76
|
+
if (Array.isArray(parsed)) for (const id of parsed) if (typeof id === 'string') ids.add(id);
|
|
77
|
+
} catch { /* malformed frontmatter is reported elsewhere */ }
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return ids;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function highValue(card, event) {
|
|
84
|
+
const kind = String(event?.kind ?? card?.kind ?? '').toLowerCase();
|
|
85
|
+
const text = `${card?.title ?? ''} ${(card?.terms ?? []).join(' ')}`;
|
|
86
|
+
return {
|
|
87
|
+
value: HIGH_VALUE_KIND.has(kind) || HIGH_VALUE_RE.test(text),
|
|
88
|
+
kind,
|
|
89
|
+
reason: HIGH_VALUE_KIND.has(kind) ? `kind:${kind}` : (HIGH_VALUE_RE.test(text) ? 'keyword' : ''),
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Compute a reconcile summary. Read-only except for the optional JSON report
|
|
95
|
+
* (`write:true`, default false). Never promotes anything here.
|
|
96
|
+
*/
|
|
97
|
+
export function reconcileIndex({ memoryRoot = '', now = new Date(), write = false } = {}) {
|
|
98
|
+
const root = path.resolve(String(memoryRoot ?? ''));
|
|
99
|
+
if (root === '') throw new Error('E_MEMORY_ROOT: reconcile requires memoryRoot');
|
|
100
|
+
const nowDate = now instanceof Date ? now : new Date(now);
|
|
101
|
+
const events = readEvents(root);
|
|
102
|
+
// legacy cold-archive diagnostic only; not used by recall/INDEX/panel stats.
|
|
103
|
+
// Explicit promotion review still reads the old archive; no summary is emitted.
|
|
104
|
+
const cards = readAutoCards(root);
|
|
105
|
+
const curated = scanCards(root);
|
|
106
|
+
const eventsAudit = readJsonl(resolveInside(root, path.join('.longlive', 'index', 'events.audit.jsonl')));
|
|
107
|
+
const cardAudit = readJsonl(resolveInside(root, path.join('.longlive', 'index', 'card-audit.jsonl')));
|
|
108
|
+
const anchors = readCardAnchors(root);
|
|
109
|
+
const curatedIds = curatedSourceIds(root);
|
|
110
|
+
|
|
111
|
+
const eventIds = new Set(events.rows.map((row) => row.id));
|
|
112
|
+
const cardEventIds = new Set(cards.map((card) => card.eventId));
|
|
113
|
+
const auditIds = new Set(eventsAudit.rows.map((row) => row.id));
|
|
114
|
+
const duplicateAuditRows = eventsAudit.rows.length - auditIds.size;
|
|
115
|
+
const missingAudit = [...eventIds].filter((id) => !auditIds.has(id));
|
|
116
|
+
const auditWithoutEvent = [...auditIds].filter((id) => !eventIds.has(id));
|
|
117
|
+
const missingCard = events.rows.filter((row) => !cardEventIds.has(row.id)).map((row) => row.id);
|
|
118
|
+
const cardWithoutEvent = cards.filter((card) => !eventIds.has(card.eventId)).map((card) => card.eventId);
|
|
119
|
+
const dropRows = cardAudit.rows.filter((row) => row.action === 'drop');
|
|
120
|
+
const dropStillCarded = [...new Set(dropRows.map((row) => row.eventId).filter((id) => cardEventIds.has(id)))];
|
|
121
|
+
const anchorRows = [...anchors.values()];
|
|
122
|
+
const legacyEmptyAnchors = anchorRows.filter((link) => link.legacy === true || (Array.isArray(link.anchors) && link.anchors.length === 0));
|
|
123
|
+
const emptySourceEventIds = anchorRows.filter((link) => !Array.isArray(link.sourceEventIds) || link.sourceEventIds.length === 0);
|
|
124
|
+
const invalidSourceEventIds = [];
|
|
125
|
+
for (const link of anchorRows) for (const id of Array.isArray(link.sourceEventIds) ? link.sourceEventIds : []) {
|
|
126
|
+
if (!eventIds.has(id)) invalidSourceEventIds.push({ rel: link.rel, id });
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const autoCandidates = [];
|
|
130
|
+
for (const card of cards) {
|
|
131
|
+
if (curatedIds.has(card.eventId)) continue;
|
|
132
|
+
const event = events.rows.find((row) => row.id === card.eventId) ?? null;
|
|
133
|
+
const hv = highValue(card, event);
|
|
134
|
+
if (!hv.value) continue;
|
|
135
|
+
autoCandidates.push({
|
|
136
|
+
cardId: card.cardId,
|
|
137
|
+
eventId: card.eventId,
|
|
138
|
+
sessionId: card.sessionId ?? card.anchor?.sessionId ?? null,
|
|
139
|
+
turn: card.turn ?? card.anchor?.turn ?? null,
|
|
140
|
+
title: card.title ?? '',
|
|
141
|
+
terms: Array.isArray(card.terms) ? card.terms : [],
|
|
142
|
+
kind: hv.kind || card.kind || null,
|
|
143
|
+
reason: hv.reason,
|
|
144
|
+
promotion: {
|
|
145
|
+
dryRun: true,
|
|
146
|
+
target: `topics/promoted-${sha1(`${card.eventId}|${card.title}`).slice(0, 12)}.md`,
|
|
147
|
+
accept: `node scripts/index-reconcile.mjs --memory-root <root> --accept ${card.cardId} --apply`,
|
|
148
|
+
},
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
const summary = {
|
|
152
|
+
schema: RECONCILE_SCHEMA,
|
|
153
|
+
generatedAt: nowDate.toISOString(),
|
|
154
|
+
memoryRoot: root,
|
|
155
|
+
events: {
|
|
156
|
+
ok: events.ok,
|
|
157
|
+
total: events.total,
|
|
158
|
+
indexFile: path.join('.longlive', 'index', 'events.db'),
|
|
159
|
+
...(events.code ? { code: events.code } : {}),
|
|
160
|
+
},
|
|
161
|
+
curatedCards: curated.length,
|
|
162
|
+
sets: {
|
|
163
|
+
eventNotAudit: { count: missingAudit.length, sample: missingAudit.slice(0, 20) },
|
|
164
|
+
auditNotEvent: { count: auditWithoutEvent.length, sample: auditWithoutEvent.slice(0, 20) },
|
|
165
|
+
duplicateAuditRows,
|
|
166
|
+
eventNoCard: { count: missingCard.length, sample: missingCard.slice(0, 20) },
|
|
167
|
+
cardNoEvent: { count: cardWithoutEvent.length, sample: cardWithoutEvent.slice(0, 20) },
|
|
168
|
+
cardAuditDrops: dropRows.length,
|
|
169
|
+
dropButStillCarded: { count: dropStillCarded.length, sample: dropStillCarded.slice(0, 20) },
|
|
170
|
+
cardAnchors: {
|
|
171
|
+
total: anchorRows.length,
|
|
172
|
+
legacyOrEmptyAnchors: legacyEmptyAnchors.length,
|
|
173
|
+
emptySourceEventIds: emptySourceEventIds.length,
|
|
174
|
+
invalidSourceEventIds,
|
|
175
|
+
},
|
|
176
|
+
},
|
|
177
|
+
autoCandidates: {
|
|
178
|
+
count: autoCandidates.length,
|
|
179
|
+
sample: autoCandidates.slice(0, 20),
|
|
180
|
+
note: 'event + auto card exist, but no curated card/card-anchor sourceEventId covers them',
|
|
181
|
+
},
|
|
182
|
+
safeRepairs: {
|
|
183
|
+
dryRunByDefault: true,
|
|
184
|
+
actions: [
|
|
185
|
+
'promote reviewed autoCandidates to topics/ (--accept <cardId> --apply)',
|
|
186
|
+
're-run memory_index after promotion',
|
|
187
|
+
'card-audit drops that are still present are reported, never silently rewritten; rebuild card-audit only after a verified card rebuild',
|
|
188
|
+
],
|
|
189
|
+
},
|
|
190
|
+
};
|
|
191
|
+
let reportPath = null;
|
|
192
|
+
if (write) {
|
|
193
|
+
const reportsDir = resolveInside(root, path.join('.longlive', 'reports'));
|
|
194
|
+
fs.mkdirSync(reportsDir, { recursive: true });
|
|
195
|
+
const stamp = nowDate.toISOString().slice(0, 10).replace(/-/g, '');
|
|
196
|
+
reportPath = path.join(reportsDir, `${RECONCILE_FILE_PREFIX}${stamp}.json`);
|
|
197
|
+
writeFileAtomic(root, relativePath(root, reportPath), `${JSON.stringify(summary, null, 2)}\n`, { now: nowDate });
|
|
198
|
+
}
|
|
199
|
+
return { ...summary, reportPath };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Promote one reviewed auto card to a topics card. The card body is newly
|
|
204
|
+
* written; the source auto card is never edited. Default dryRun=true.
|
|
205
|
+
*/
|
|
206
|
+
export function promoteAutoCard({ memoryRoot = '', cardId = '', eventId = '', now = new Date(), dryRun = true } = {}) {
|
|
207
|
+
const root = path.resolve(String(memoryRoot ?? ''));
|
|
208
|
+
if (root === '') throw new Error('E_MEMORY_ROOT: promote requires memoryRoot');
|
|
209
|
+
const nowDate = now instanceof Date ? now : new Date(now);
|
|
210
|
+
// legacy cold-archive diagnostic only; not used by recall/INDEX/panel stats.
|
|
211
|
+
const card = readAutoCards(root).find((item) => (cardId && item.cardId === cardId) || (eventId && item.eventId === eventId));
|
|
212
|
+
if (!card) throw new Error('E_AUTO_CARD_NOT_FOUND');
|
|
213
|
+
const index = openEventIndex({ memoryRoot: root });
|
|
214
|
+
let event = null;
|
|
215
|
+
try { event = index.getEvent(card.eventId); } finally { index.close(); }
|
|
216
|
+
if (!event) throw new Error('E_EVENT_NOT_FOUND');
|
|
217
|
+
const target = `topics/promoted-${sha1(`${card.eventId}|${card.title}`).slice(0, 12)}.md`;
|
|
218
|
+
const abs = resolveInside(root, target);
|
|
219
|
+
const kind = ['conclusion', 'decision'].includes(String(event.kind)) ? event.kind : 'fact';
|
|
220
|
+
const priority = priorityFor({ kind, source: 'manual' });
|
|
221
|
+
const title = String(card.title ?? '').replace(/\s+/g, ' ').trim().slice(0, 120) || 'promoted event';
|
|
222
|
+
const terms = Array.isArray(card.terms) ? card.terms.filter((term) => typeof term === 'string') : [];
|
|
223
|
+
const body = [
|
|
224
|
+
'---',
|
|
225
|
+
`title: ${title}`,
|
|
226
|
+
`date: ${nowDate.toISOString().slice(0, 10)}`,
|
|
227
|
+
'tags: [promoted, auto-card]',
|
|
228
|
+
`salience: ${priority.salience}`,
|
|
229
|
+
`retention: ${JSON.stringify(priority.retention)}`,
|
|
230
|
+
`kind: ${kind}`,
|
|
231
|
+
`source_session: ${card.sessionId ?? card.anchor?.sessionId ?? ''}`,
|
|
232
|
+
`source_turn: ${card.turn ?? card.anchor?.turn ?? ''}`,
|
|
233
|
+
`sourceEventIds: [${JSON.stringify(card.eventId)}]`,
|
|
234
|
+
`promoted_from_card: ${card.cardId}`,
|
|
235
|
+
'---',
|
|
236
|
+
'',
|
|
237
|
+
title,
|
|
238
|
+
'',
|
|
239
|
+
`原文锚点:session=${card.sessionId ?? card.anchor?.sessionId ?? ''} turn=${card.turn ?? card.anchor?.turn ?? ''}`,
|
|
240
|
+
terms.length > 0 ? `检索词:${terms.join(' / ')}` : '',
|
|
241
|
+
'',
|
|
242
|
+
].join('\n');
|
|
243
|
+
const result = {
|
|
244
|
+
ok: true,
|
|
245
|
+
dryRun: dryRun !== false,
|
|
246
|
+
cardId: card.cardId,
|
|
247
|
+
eventId: card.eventId,
|
|
248
|
+
rel: target,
|
|
249
|
+
path: abs,
|
|
250
|
+
title,
|
|
251
|
+
kind,
|
|
252
|
+
salience: priority.salience,
|
|
253
|
+
body,
|
|
254
|
+
sourceAnchor: card.anchor ?? null,
|
|
255
|
+
};
|
|
256
|
+
if (dryRun !== false) return result;
|
|
257
|
+
if (fs.existsSync(abs)) throw new Error(`E_PROMOTE_EXISTS: ${target}`);
|
|
258
|
+
writeFileAtomic(root, target, body, { backup: false, now: nowDate });
|
|
259
|
+
const indexResult = memoryIndex({ apply: true }, { memoryRoot: root, now: nowDate });
|
|
260
|
+
return { ...result, dryRun: false, written: true, index: indexResult };
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export function reconcileRootFromConfig(config = {}) {
|
|
264
|
+
return memoryRootFromConfig(config);
|
|
265
|
+
}
|