@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,680 @@
|
|
|
1
|
+
// src/memory/forget-v2.js — M2-D:forget v2 门面(propose / execute / restore)
|
|
2
|
+
//
|
|
3
|
+
// 设计依据 §4.6(归档仅纯噪声/重复,重要事件永禁;沿用 forget.js 的备份→三问→
|
|
4
|
+
// rename→审计,不重写 forget.js):
|
|
5
|
+
// * propose = forget.js dry-run(只读,不建目录、不写审计);
|
|
6
|
+
// * execute = forget.js 执行(需 confirm:"FORGET";保护卡由 retention 拒绝);
|
|
7
|
+
// * restore = 从 tombstones.md 的 recoverable 目标或 epochs/ 把卡移回原路径,
|
|
8
|
+
// 只 rename、不删除,写 1 行恢复审计(生命周期上「忘/恢复」两条审计)。
|
|
9
|
+
//
|
|
10
|
+
// 本模块不注册工具(见 Lead 拍板:不 expose 新工具);入口在 admin 脚本。
|
|
11
|
+
|
|
12
|
+
import crypto from 'node:crypto';
|
|
13
|
+
import fs from 'node:fs';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
|
|
16
|
+
import { appendAuditRecord, resolveAuditKey, verifyAuditChain } from './audit-records.js';
|
|
17
|
+
import { memoryForget, DECAY_RULES } from './forget.js';
|
|
18
|
+
import { daysBetween, dayString, isDayString, parseFrontmatter } from './frontmatter.js';
|
|
19
|
+
import { memoryError, memoryRootFromConfig, relativePath, resolveInside } from './paths.js';
|
|
20
|
+
import { isProtectedPath } from './retention.js';
|
|
21
|
+
import { readCardAnchors } from './card-anchors.js';
|
|
22
|
+
import { appendGateLog } from '../recall/gate-log.mjs';
|
|
23
|
+
import {
|
|
24
|
+
appendAudit, ensureDir, epochsDir, sha256File, tombstonesPath, writeFileAtomic,
|
|
25
|
+
} from './state.js';
|
|
26
|
+
|
|
27
|
+
export const FORGET_V2_SCHEMA = 'forget-v2/v1';
|
|
28
|
+
export const PURE_NOISE_PATTERNS = Object.freeze([
|
|
29
|
+
/^\.longlive\/tool-output\//,
|
|
30
|
+
/^\.tmp-test\//,
|
|
31
|
+
/(^|\/)diag\//,
|
|
32
|
+
/(^|\/)tmp\//,
|
|
33
|
+
]);
|
|
34
|
+
|
|
35
|
+
/** Pure-noise whitelist for the v2 archive path; anything else is never auto-archived. */
|
|
36
|
+
export function isPureNoisePath(relPath) {
|
|
37
|
+
const rel = String(relPath ?? '').replace(/\\/g, '/').replace(/^\/+/, '');
|
|
38
|
+
if (rel === '') return false;
|
|
39
|
+
return PURE_NOISE_PATTERNS.some((pattern) => pattern.test(rel));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 选择性遗忘评分(D13 唯一公式源):score = salience*2 + strength + 30/(30+ageDays)。
|
|
44
|
+
*
|
|
45
|
+
* 原始分、全程不四舍五入;参数缺失/非法返回 null(绝不返回 0 冒充有效分)。
|
|
46
|
+
* 阈值 7.50 的比较一律用本函数原始返回值,展示层才允许 toFixed(2)。
|
|
47
|
+
*/
|
|
48
|
+
export function score({ salience, strength, ageDays } = {}) {
|
|
49
|
+
const s = Number(salience);
|
|
50
|
+
const t = Number(strength);
|
|
51
|
+
const a = Number(ageDays);
|
|
52
|
+
if (!Number.isFinite(s) || !Number.isFinite(t) || !Number.isFinite(a) || a < 0) return null;
|
|
53
|
+
return s * 2 + t + 30 / (30 + a);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** 计划 §4② 术语里的别名;两个名字指向同一实现。 */
|
|
57
|
+
export const forgetScore = score;
|
|
58
|
+
|
|
59
|
+
export const FORGET_SUGGESTIONS_REL = '.longlive/hardgate/forget-suggestions.jsonl';
|
|
60
|
+
export const FORGET_SUGGESTIONS_SCHEMA = 'hardgate-forget-suggestions/v1';
|
|
61
|
+
export const SCORE_THRESHOLD = 7.5;
|
|
62
|
+
export const SUGGESTION_MAX_ITEMS = 200;
|
|
63
|
+
export const SUGGESTION_RETENTION_DAYS = 90;
|
|
64
|
+
export const SUGGESTION_AGE_DAYS_MIN = 30;
|
|
65
|
+
export const SUGGESTION_SALIENCE_BELOW = 4;
|
|
66
|
+
export const SUGGESTION_GATE_EVENT = 'hg.d13.fail';
|
|
67
|
+
|
|
68
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
69
|
+
|
|
70
|
+
function gateFail(root, code, message, extra = {}) {
|
|
71
|
+
try {
|
|
72
|
+
appendGateLog(root, {
|
|
73
|
+
gate: SUGGESTION_GATE_EVENT,
|
|
74
|
+
decision: 'fail',
|
|
75
|
+
reason: code,
|
|
76
|
+
evidence: [String(message), ...(Array.isArray(extra.evidence) ? extra.evidence : [])],
|
|
77
|
+
});
|
|
78
|
+
} catch {
|
|
79
|
+
// 门日志本身失败不能再把主流程拖垮;返回码仍是 fail-closed。
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function suggestionFilePath(root) {
|
|
84
|
+
return path.join(root, FORGET_SUGGESTIONS_REL);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function readSuggestionRows(root) {
|
|
88
|
+
let text = '';
|
|
89
|
+
try {
|
|
90
|
+
text = fs.readFileSync(suggestionFilePath(root), 'utf8');
|
|
91
|
+
} catch {
|
|
92
|
+
return [];
|
|
93
|
+
}
|
|
94
|
+
const rows = [];
|
|
95
|
+
for (const line of text.split(/\r?\n/)) {
|
|
96
|
+
const trimmed = line.trim();
|
|
97
|
+
if (trimmed === '') continue;
|
|
98
|
+
try {
|
|
99
|
+
const row = JSON.parse(trimmed);
|
|
100
|
+
if (row && typeof row.rel === 'string') rows.push(row);
|
|
101
|
+
} catch {
|
|
102
|
+
// 坏行丢弃,不当建议使用
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return rows;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function pruneSuggestionRows(rows, atMs) {
|
|
109
|
+
const cutoff = atMs - SUGGESTION_RETENTION_DAYS * DAY_MS;
|
|
110
|
+
const kept = rows.filter((row) => {
|
|
111
|
+
const stamp = Date.parse(String(row.suggestedAt ?? ''));
|
|
112
|
+
return Number.isFinite(stamp) && stamp >= cutoff;
|
|
113
|
+
});
|
|
114
|
+
kept.sort((left, right) => {
|
|
115
|
+
const l = Date.parse(String(left.suggestedAt ?? '')) || 0;
|
|
116
|
+
const r = Date.parse(String(right.suggestedAt ?? '')) || 0;
|
|
117
|
+
if (l !== r) return l - r;
|
|
118
|
+
return String(left.rel).localeCompare(String(right.rel));
|
|
119
|
+
});
|
|
120
|
+
return kept.slice(-SUGGESTION_MAX_ITEMS);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function writeSuggestionRows(root, rows, at) {
|
|
124
|
+
const file = suggestionFilePath(root);
|
|
125
|
+
const pruned = pruneSuggestionRows(rows, at.getTime());
|
|
126
|
+
const content = pruned.map((row) => JSON.stringify(row)).join('\n') + (pruned.length > 0 ? '\n' : '');
|
|
127
|
+
ensureDir(root, path.dirname(file));
|
|
128
|
+
writeFileAtomic(root, file, content, { now: at });
|
|
129
|
+
return { rows: pruned, file, rel: FORGET_SUGGESTIONS_REL };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function listTopicCards(root) {
|
|
133
|
+
const topics = path.join(root, 'topics');
|
|
134
|
+
const found = [];
|
|
135
|
+
const walk = (dir) => {
|
|
136
|
+
let entries = [];
|
|
137
|
+
try {
|
|
138
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
139
|
+
} catch {
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
for (const entry of entries) {
|
|
143
|
+
const abs = path.join(dir, entry.name);
|
|
144
|
+
if (entry.isDirectory()) {
|
|
145
|
+
if (entry.name === 'archive') continue;
|
|
146
|
+
walk(abs);
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
if (!entry.isFile() || !entry.name.endsWith('.md')) continue;
|
|
150
|
+
found.push(abs);
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
walk(topics);
|
|
154
|
+
found.sort((left, right) => left.localeCompare(right));
|
|
155
|
+
return found.map((abs) => ({ abs, rel: relativePath(root, abs).replace(/\\/g, '/') }));
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function cardMeta(abs) {
|
|
159
|
+
const text = fs.readFileSync(abs, 'utf8');
|
|
160
|
+
const parsed = parseFrontmatter(text);
|
|
161
|
+
const fields = parsed.fields ?? {};
|
|
162
|
+
return {
|
|
163
|
+
fields,
|
|
164
|
+
status: typeof fields.status === 'string' ? fields.status : 'active',
|
|
165
|
+
salience: Number(fields.salience),
|
|
166
|
+
strength: Number(fields.strength),
|
|
167
|
+
lastUsed: fields.last_used,
|
|
168
|
+
missingMeta: !Number.isFinite(Number(fields.salience))
|
|
169
|
+
|| !Number.isFinite(Number(fields.strength))
|
|
170
|
+
|| !isDayString(fields.last_used),
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* 选择性遗忘建议(D13)。
|
|
176
|
+
*
|
|
177
|
+
* 计划 §4② 口径:autoApply:false(默认)——只写 forget-suggestions.jsonl
|
|
178
|
+
* (≤200 条 / 90 天),绝不自动标 historical;人工确认后只走既有 memory_forget。
|
|
179
|
+
* 显式传 autoApply:true 视为越权,fail-closed 抛 E_HG_D13_AUTOAPPLY_UNSUPPORTED。
|
|
180
|
+
*
|
|
181
|
+
* 判据:score<7.50(原始分不四舍五入)∧ salience<4 ∧ ageDays>30 ∧ 非 missing_meta;
|
|
182
|
+
* salience≥5(immune5)与 status=locked 永不进建议队列。
|
|
183
|
+
*/
|
|
184
|
+
export function proposeForget(args = {}, config = {}) {
|
|
185
|
+
const requestedAutoApply = args.autoApply !== undefined ? args.autoApply : config.autoApply;
|
|
186
|
+
if (requestedAutoApply !== undefined && requestedAutoApply !== false) {
|
|
187
|
+
let root = null;
|
|
188
|
+
try {
|
|
189
|
+
root = memoryRootFromConfig(config);
|
|
190
|
+
} catch {
|
|
191
|
+
root = null;
|
|
192
|
+
}
|
|
193
|
+
if (root) gateFail(root, 'E_HG_D13_AUTOAPPLY_UNSUPPORTED', '计划 §4② 只允许 autoApply:false');
|
|
194
|
+
throw memoryError(
|
|
195
|
+
'E_HG_D13_AUTOAPPLY_UNSUPPORTED',
|
|
196
|
+
'计划 v3.6.4 §4②:遗忘只写建议队列(autoApply:false),人工确认后才标 historical',
|
|
197
|
+
);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const base = memoryForget({ ...args, confirm: undefined, autoApply: undefined }, config);
|
|
201
|
+
const root = memoryRootFromConfig(config);
|
|
202
|
+
const at = config.now instanceof Date
|
|
203
|
+
? config.now
|
|
204
|
+
: new Date(config.now ?? args.now ?? Date.now());
|
|
205
|
+
const todayDay = isDayString(config.today) ? config.today : dayString(at);
|
|
206
|
+
|
|
207
|
+
let cards;
|
|
208
|
+
try {
|
|
209
|
+
if (typeof args.path === 'string' && args.path.trim() !== '') {
|
|
210
|
+
const abs = resolveInside(root, args.path);
|
|
211
|
+
cards = [{ abs, rel: relativePath(root, abs).replace(/\\/g, '/') }];
|
|
212
|
+
} else {
|
|
213
|
+
cards = listTopicCards(root);
|
|
214
|
+
}
|
|
215
|
+
} catch (error) {
|
|
216
|
+
gateFail(root, 'E_HG_D13_SCAN_FAILED', String(error?.message ?? error));
|
|
217
|
+
throw memoryError('E_HG_D13_SCAN_FAILED', `扫描卡片失败:${error?.message ?? error}`);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
let missingMeta = 0;
|
|
221
|
+
let immune = 0;
|
|
222
|
+
let skipped = 0;
|
|
223
|
+
const candidates = [];
|
|
224
|
+
for (const card of cards) {
|
|
225
|
+
let meta;
|
|
226
|
+
try {
|
|
227
|
+
meta = cardMeta(card.abs);
|
|
228
|
+
} catch {
|
|
229
|
+
missingMeta += 1;
|
|
230
|
+
continue;
|
|
231
|
+
}
|
|
232
|
+
if (meta.missingMeta) {
|
|
233
|
+
missingMeta += 1;
|
|
234
|
+
continue;
|
|
235
|
+
}
|
|
236
|
+
if (meta.status === 'locked' || meta.salience >= DECAY_RULES.immuneSalience) {
|
|
237
|
+
immune += 1;
|
|
238
|
+
continue;
|
|
239
|
+
}
|
|
240
|
+
const usedMs = Date.parse(String(meta.lastUsed));
|
|
241
|
+
if (!Number.isFinite(usedMs)) {
|
|
242
|
+
missingMeta += 1;
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
// 与夹具/计划同口径:ageDays 是到 now 的小数天(last_used 按 UTC 零点解析)。
|
|
246
|
+
const ageDays = Math.max(0, (at.getTime() - usedMs) / DAY_MS);
|
|
247
|
+
if (ageDays == null) {
|
|
248
|
+
missingMeta += 1;
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
const value = score({ salience: meta.salience, strength: meta.strength, ageDays });
|
|
252
|
+
if (value == null) {
|
|
253
|
+
missingMeta += 1;
|
|
254
|
+
continue;
|
|
255
|
+
}
|
|
256
|
+
if (!(value < SCORE_THRESHOLD && meta.salience < SUGGESTION_SALIENCE_BELOW && ageDays > SUGGESTION_AGE_DAYS_MIN)) {
|
|
257
|
+
skipped += 1;
|
|
258
|
+
continue;
|
|
259
|
+
}
|
|
260
|
+
candidates.push({
|
|
261
|
+
schema: FORGET_SUGGESTIONS_SCHEMA,
|
|
262
|
+
rel: card.rel,
|
|
263
|
+
score: value,
|
|
264
|
+
threshold: SCORE_THRESHOLD,
|
|
265
|
+
salience: meta.salience,
|
|
266
|
+
strength: meta.strength,
|
|
267
|
+
ageDays,
|
|
268
|
+
missing_meta: false,
|
|
269
|
+
suggestedAt: at.toISOString(),
|
|
270
|
+
status: 'open',
|
|
271
|
+
autoApplied: false,
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
let queue = null;
|
|
276
|
+
try {
|
|
277
|
+
const existing = readSuggestionRows(root);
|
|
278
|
+
const openRels = new Set(existing.filter((row) => row.status !== 'closed').map((row) => String(row.rel)));
|
|
279
|
+
const added = candidates.filter((row) => !openRels.has(row.rel));
|
|
280
|
+
if (added.length > 0) {
|
|
281
|
+
queue = writeSuggestionRows(root, [...existing, ...added], at);
|
|
282
|
+
} else if (existing.length > 0) {
|
|
283
|
+
queue = writeSuggestionRows(root, existing, at);
|
|
284
|
+
} else {
|
|
285
|
+
queue = { rows: [], file: suggestionFilePath(root), rel: FORGET_SUGGESTIONS_REL };
|
|
286
|
+
}
|
|
287
|
+
} catch (error) {
|
|
288
|
+
gateFail(root, 'E_HG_D13_SUGGEST_FAILED', String(error?.message ?? error));
|
|
289
|
+
throw memoryError('E_HG_D13_SUGGEST_FAILED', `写 forget-suggestions 失败:${error?.message ?? error}`);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
return {
|
|
293
|
+
...base,
|
|
294
|
+
autoApply: false,
|
|
295
|
+
scoreThreshold: SCORE_THRESHOLD,
|
|
296
|
+
scanned: cards.length,
|
|
297
|
+
missingMeta,
|
|
298
|
+
immune,
|
|
299
|
+
skipped,
|
|
300
|
+
suggestions: (queue?.rows ?? []).map((row) => row.rel),
|
|
301
|
+
queued: candidates.length,
|
|
302
|
+
suggestionsFile: FORGET_SUGGESTIONS_REL,
|
|
303
|
+
suggestionsRel: queue?.rel ?? FORGET_SUGGESTIONS_REL,
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** 只读:给面板/维护链查建议队列(含 90 天窗口裁剪口径)。 */
|
|
308
|
+
export function readForgetSuggestions(config = {}) {
|
|
309
|
+
const root = memoryRootFromConfig(config);
|
|
310
|
+
const at = config.now instanceof Date ? config.now : new Date(config.now ?? Date.now());
|
|
311
|
+
const rows = pruneSuggestionRows(readSuggestionRows(root), at.getTime());
|
|
312
|
+
return { ok: true, schema: FORGET_SUGGESTIONS_SCHEMA, rows, file: FORGET_SUGGESTIONS_REL, count: rows.length };
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function sha256Hex(text) {
|
|
316
|
+
return crypto.createHash('sha256').update(String(text), 'utf8').digest('hex');
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function hmacHex(key, text) {
|
|
320
|
+
return crypto.createHmac('sha256', key).update(String(text), 'utf8').digest('hex');
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
const TOMB_SIG_RE = /\s*\|\s*tombstonePrevHash:\s*(genesis|[0-9a-f]{64})\s*\|\s*tombstoneHash:\s*([0-9a-f]{64})\s*\|\s*tombstoneHmac:\s*([0-9a-f]{64})$/;
|
|
324
|
+
|
|
325
|
+
function signTombstoneLine(line, { key, previousHash }) {
|
|
326
|
+
if (typeof key !== 'string' || key === '') throw new Error('E_NO_KEY');
|
|
327
|
+
const hash = sha256Hex(`${previousHash}\n${line}`);
|
|
328
|
+
const hmac = hmacHex(key, hash);
|
|
329
|
+
return {
|
|
330
|
+
line: `${line} | tombstonePrevHash: ${previousHash} | tombstoneHash: ${hash} | tombstoneHmac: ${hmac}`,
|
|
331
|
+
hash,
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** Verify every tombstone line: signature required, chain must be continuous. */
|
|
336
|
+
export function verifyTombstoneLedger(root, key) {
|
|
337
|
+
const file = tombstonesPath(root);
|
|
338
|
+
let text = '';
|
|
339
|
+
try { text = fs.readFileSync(file, 'utf8'); } catch {
|
|
340
|
+
return { ok: false, code: 'E_TOMBSTONE_MISSING', lines: 0 };
|
|
341
|
+
}
|
|
342
|
+
let previous = 'genesis';
|
|
343
|
+
let lines = 0;
|
|
344
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
345
|
+
if (!raw.startsWith('- ')) continue;
|
|
346
|
+
lines += 1;
|
|
347
|
+
const match = raw.match(TOMB_SIG_RE);
|
|
348
|
+
if (!match) return { ok: false, code: 'E_TOMBSTONE_UNSIGNED', line: lines };
|
|
349
|
+
const base = raw.slice(0, match.index);
|
|
350
|
+
const expectedHash = sha256Hex(`${previous}\n${base}`);
|
|
351
|
+
if (match[2] !== expectedHash) return { ok: false, code: 'E_TOMBSTONE_CHAIN_BROKEN', line: lines };
|
|
352
|
+
if (match[1] !== previous) return { ok: false, code: 'E_TOMBSTONE_CHAIN_BROKEN', line: lines };
|
|
353
|
+
const expectedHmac = hmacHex(key, expectedHash);
|
|
354
|
+
if (match[3] !== expectedHmac) return { ok: false, code: 'E_TOMBSTONE_HMAC_INVALID', line: lines };
|
|
355
|
+
previous = match[2];
|
|
356
|
+
}
|
|
357
|
+
return { ok: true, code: 'OK', lines, lastHash: previous };
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function lastSignedTombstoneHash(text) {
|
|
361
|
+
let previous = 'genesis';
|
|
362
|
+
for (const raw of String(text ?? '').split(/\r?\n/)) {
|
|
363
|
+
if (!raw.startsWith('- ')) continue;
|
|
364
|
+
const match = raw.match(TOMB_SIG_RE);
|
|
365
|
+
if (match) previous = match[2];
|
|
366
|
+
}
|
|
367
|
+
return previous;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
function auditDenied({ root, action, recordId, code, extra = {}, now, skipHead = false }) {
|
|
371
|
+
try {
|
|
372
|
+
appendAuditRecord({
|
|
373
|
+
memoryRoot: root,
|
|
374
|
+
action,
|
|
375
|
+
recordId: recordId ?? null,
|
|
376
|
+
readerTier: 'host',
|
|
377
|
+
questionId: 'unknown',
|
|
378
|
+
expectedTurns: null,
|
|
379
|
+
answerText: null,
|
|
380
|
+
at: now instanceof Date ? now.toISOString() : new Date(now).toISOString(),
|
|
381
|
+
extra: { code, ...extra },
|
|
382
|
+
skipHead,
|
|
383
|
+
});
|
|
384
|
+
} catch { /* denial audit best effort; fail closed regardless */ }
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/** Production gate: forget/restore must notice a broken audit chain, not only admins. */
|
|
388
|
+
function requireAuditChain(root, now, action, recordId) {
|
|
389
|
+
const chain = verifyAuditChain({ memoryRoot: root });
|
|
390
|
+
if (chain.ok !== true) {
|
|
391
|
+
auditDenied({
|
|
392
|
+
root,
|
|
393
|
+
action,
|
|
394
|
+
recordId,
|
|
395
|
+
code: 'E_AUDIT_CHAIN_BROKEN',
|
|
396
|
+
extra: { chainViolation: true, auditChain: chain },
|
|
397
|
+
now,
|
|
398
|
+
skipHead: true,
|
|
399
|
+
});
|
|
400
|
+
throw memoryError('E_AUDIT_CHAIN_BROKEN', '审计哈希链/头锚损坏:拒绝遗忘/恢复(fail-closed)', { auditChain: chain });
|
|
401
|
+
}
|
|
402
|
+
return chain;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
function requireKey(root, now, action, recordId) {
|
|
406
|
+
const resolved = resolveAuditKey(root);
|
|
407
|
+
if (resolved.key === null) {
|
|
408
|
+
auditDenied({ root, action, recordId, code: 'E_NO_KEY', extra: { hmacResidual: 'hostkey-unavailable' }, now });
|
|
409
|
+
throw memoryError('E_NO_KEY', '遗忘执行/恢复需要宿主 auditKey(env 或 .longlive/.hostkey);未提供 key,fail-closed');
|
|
410
|
+
}
|
|
411
|
+
return resolved.key;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
function sourceAnchorFor(memoryRoot, rel) {
|
|
415
|
+
try {
|
|
416
|
+
const link = readCardAnchors(memoryRoot).get(String(rel ?? '').replace(/\\/g, '/'));
|
|
417
|
+
const anchor = Array.isArray(link?.anchors) ? link.anchors.find((item) => item
|
|
418
|
+
&& (item.kind === 'session_turn' || item.kind === 'file_line')) : null;
|
|
419
|
+
if (anchor) return { anchor, sourceEventIds: Array.isArray(link.sourceEventIds) ? link.sourceEventIds : [] };
|
|
420
|
+
} catch { /* legacy sidecar unreadable: no fake anchor */ }
|
|
421
|
+
return {
|
|
422
|
+
anchor: { kind: 'legacy', status: 'missing', reason: 'no-explicit-source-anchor' },
|
|
423
|
+
sourceEventIds: [],
|
|
424
|
+
};
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
function richTombstoneLine({ prefix, moved, planned, source, rule, params }) {
|
|
428
|
+
const backup = { path: moved.backupRel, sha256: moved.sha256 };
|
|
429
|
+
return `${prefix} | ${moved.path} | ${moved.kind} | reason: ${planned.epitaph.reason}` +
|
|
430
|
+
` | affects: ${planned.epitaph.affects} | stillUseful: ${planned.epitaph.stillUseful}` +
|
|
431
|
+
` | recoverable: ${moved.destRel} | sha256: ${moved.sha256}` +
|
|
432
|
+
` | sourceAnchor: ${JSON.stringify(source.anchor)}` +
|
|
433
|
+
` | sourceEventIds: ${JSON.stringify(source.sourceEventIds)}` +
|
|
434
|
+
` | rule: ${JSON.stringify(rule)} | params: ${JSON.stringify(params)}` +
|
|
435
|
+
` | backup: ${JSON.stringify(backup)}`;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
function enrichForgottenLedger({ root, result, anchorsByPath, args, now, key }) {
|
|
439
|
+
const tombFile = tombstonesPath(root);
|
|
440
|
+
if (!fs.existsSync(tombFile)) return { enriched: 0, missingLines: [] };
|
|
441
|
+
let text = fs.readFileSync(tombFile, 'utf8');
|
|
442
|
+
const lines = text.split(/\r?\n/);
|
|
443
|
+
let previousSigned = lastSignedTombstoneHash(text);
|
|
444
|
+
let enriched = 0;
|
|
445
|
+
const missingLines = [];
|
|
446
|
+
for (const moved of Array.isArray(result.archived) ? result.archived : []) {
|
|
447
|
+
const planned = (Array.isArray(result.proposals) ? result.proposals : []).find((item) => item.path === moved.path);
|
|
448
|
+
if (!planned) { missingLines.push(moved.path); continue; }
|
|
449
|
+
const marker = ` | ${moved.path} | `;
|
|
450
|
+
const index = lines.findIndex((line) => line.startsWith('- ') && line.includes(marker));
|
|
451
|
+
if (index < 0) { missingLines.push(moved.path); continue; }
|
|
452
|
+
const cut = lines[index].indexOf(marker);
|
|
453
|
+
const prefix = lines[index].slice(0, cut);
|
|
454
|
+
const source = anchorsByPath.get(moved.path) ?? sourceAnchorFor(root, moved.path);
|
|
455
|
+
const params = {
|
|
456
|
+
today: result.today ?? null,
|
|
457
|
+
confirm: 'FORGET',
|
|
458
|
+
by: typeof args?.by === 'string' && args.by !== '' ? args.by : 'admin',
|
|
459
|
+
at: now instanceof Date ? now.toISOString() : new Date(now).toISOString(),
|
|
460
|
+
};
|
|
461
|
+
const unsigned = richTombstoneLine({ prefix, moved, planned, source, rule: DECAY_RULES, params });
|
|
462
|
+
const signed = signTombstoneLine(unsigned, { key, previousHash: previousSigned });
|
|
463
|
+
lines[index] = signed.line;
|
|
464
|
+
previousSigned = signed.hash;
|
|
465
|
+
enriched += 1;
|
|
466
|
+
appendAuditRecord({
|
|
467
|
+
memoryRoot: root,
|
|
468
|
+
action: 'archive',
|
|
469
|
+
recordId: moved.path,
|
|
470
|
+
readerTier: 'host',
|
|
471
|
+
questionId: 'unknown',
|
|
472
|
+
expectedTurns: null,
|
|
473
|
+
answerText: null,
|
|
474
|
+
at: params.at,
|
|
475
|
+
extra: {
|
|
476
|
+
forgetV2: 'tombstone-enriched',
|
|
477
|
+
layer: 'L2',
|
|
478
|
+
archived: moved.destRel,
|
|
479
|
+
backup: { path: moved.backupRel, sha256: moved.sha256 },
|
|
480
|
+
sha256: moved.sha256,
|
|
481
|
+
sourceAnchor: source.anchor,
|
|
482
|
+
sourceEventIds: source.sourceEventIds,
|
|
483
|
+
rule: DECAY_RULES,
|
|
484
|
+
params,
|
|
485
|
+
},
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
if (enriched > 0) {
|
|
489
|
+
// Atomic rewrite + read-back verify after the append-only backup already exists.
|
|
490
|
+
writeFileAtomic(root, tombFile, `${lines.join('\n')}`, { backup: false, now });
|
|
491
|
+
}
|
|
492
|
+
return { enriched, missingLines };
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
/**
|
|
496
|
+
* Execute forgets (confirm gate stays in forget.js). P0: tombstone lines carry
|
|
497
|
+
* source anchor + backup sha + frozen rule/params; audit rows carry hash chain.
|
|
498
|
+
*/
|
|
499
|
+
export function executeForget(args = {}, config = {}) {
|
|
500
|
+
const root = memoryRootFromConfig(config);
|
|
501
|
+
const now = config.now instanceof Date ? config.now : new Date();
|
|
502
|
+
const key = requireKey(root, now, 'forget-denied', null);
|
|
503
|
+
requireAuditChain(root, now, 'forget-denied', null);
|
|
504
|
+
const plan = proposeForget(args, config);
|
|
505
|
+
const anchorsByPath = new Map();
|
|
506
|
+
for (const item of Array.isArray(plan.proposals) ? plan.proposals : []) {
|
|
507
|
+
anchorsByPath.set(item.path, sourceAnchorFor(root, item.path));
|
|
508
|
+
}
|
|
509
|
+
const result = memoryForget({ ...args, confirm: 'FORGET' }, config);
|
|
510
|
+
if (result?.applied === true) {
|
|
511
|
+
const enriched = enrichForgottenLedger({ root, result, anchorsByPath, args, now, key });
|
|
512
|
+
return { ...result, tombstoneEnriched: enriched.enriched, tombstoneEnrichMissing: enriched.missingLines };
|
|
513
|
+
}
|
|
514
|
+
return result;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
function parseJsonField(line, name) {
|
|
518
|
+
const marker = `${name}: `;
|
|
519
|
+
const start = line.indexOf(marker);
|
|
520
|
+
if (start < 0) return null;
|
|
521
|
+
const tail = line.slice(start + marker.length);
|
|
522
|
+
// Structured fields are compact JSON and end at the next " | " delimiter.
|
|
523
|
+
const end = tail.indexOf(' | ');
|
|
524
|
+
const raw = (end >= 0 ? tail.slice(0, end) : tail).trim();
|
|
525
|
+
try { return JSON.parse(raw); } catch { return null; }
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
function parseTombstoneFor(root, rel) {
|
|
529
|
+
const file = tombstonesPath(root);
|
|
530
|
+
let text;
|
|
531
|
+
try {
|
|
532
|
+
text = fs.readFileSync(file, 'utf8');
|
|
533
|
+
} catch (error) {
|
|
534
|
+
if (error?.code === 'ENOENT') return null;
|
|
535
|
+
throw error;
|
|
536
|
+
}
|
|
537
|
+
const normalized = String(rel).replace(/\\/g, '/');
|
|
538
|
+
for (const line of text.split(/\r?\n/)) {
|
|
539
|
+
if (!line.startsWith('- ')) continue;
|
|
540
|
+
if (!line.includes(`| ${normalized} |`)) continue;
|
|
541
|
+
const recoverable = line.match(/recoverable:\s*([^|\n]+)/);
|
|
542
|
+
const sha = line.match(/\bsha256:\s*([0-9a-f]{64})/);
|
|
543
|
+
return {
|
|
544
|
+
line,
|
|
545
|
+
recoverable: recoverable ? recoverable[1].trim() : null,
|
|
546
|
+
sha256: sha ? sha[1] : null,
|
|
547
|
+
sourceAnchor: parseJsonField(line, 'sourceAnchor'),
|
|
548
|
+
sourceEventIds: parseJsonField(line, 'sourceEventIds'),
|
|
549
|
+
backup: parseJsonField(line, 'backup'),
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
return null;
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
function auditRestore({ root, recordId, from, to, by, now }) {
|
|
556
|
+
try {
|
|
557
|
+
appendAuditRecord({
|
|
558
|
+
memoryRoot: root,
|
|
559
|
+
action: 'restore',
|
|
560
|
+
recordId,
|
|
561
|
+
readerTier: 'host',
|
|
562
|
+
questionId: 'unknown',
|
|
563
|
+
expectedTurns: null,
|
|
564
|
+
answerText: null,
|
|
565
|
+
at: now.toISOString(),
|
|
566
|
+
extra: { from, to, by },
|
|
567
|
+
});
|
|
568
|
+
} catch {
|
|
569
|
+
/* audit best-effort; the rename already happened and audit.log records it */
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
/**
|
|
574
|
+
* Restore a forgotten card: tombstones.md 的 recoverable 目标优先,其次 epochs/。
|
|
575
|
+
* 只 rename(不删、不覆盖已有卡),写 1 行恢复审计 + 1 行 audit.log。
|
|
576
|
+
*/
|
|
577
|
+
export function restoreForgotten({ root, path: relPath, by = 'admin', now = new Date() } = {}) {
|
|
578
|
+
const memoryRoot = String(root ?? '');
|
|
579
|
+
if (memoryRoot === '') throw memoryError('E_MEMORY_ROOT', 'restoreForgotten requires root');
|
|
580
|
+
const rel = String(relPath ?? '').replace(/\\/g, '/').replace(/^\/+/, '');
|
|
581
|
+
if (rel === '') throw memoryError('E_RESTORE_PATH', 'restore 需要原卡路径(topics/… 或 journal/…)');
|
|
582
|
+
const target = resolveInside(memoryRoot, rel);
|
|
583
|
+
if (fs.existsSync(target)) {
|
|
584
|
+
throw memoryError('E_RESTORE_TARGET', `恢复目标已存在(不覆盖):${rel}`);
|
|
585
|
+
}
|
|
586
|
+
const key = requireKey(memoryRoot, now, 'restore-denied', rel);
|
|
587
|
+
requireAuditChain(memoryRoot, now, 'restore-denied', rel);
|
|
588
|
+
const tomb = parseTombstoneFor(memoryRoot, rel);
|
|
589
|
+
if (!tomb) {
|
|
590
|
+
auditDenied({ root: memoryRoot, action: 'restore-denied', recordId: rel, code: 'E_TOMBSTONE_INCOMPLETE', extra: { reason: 'tombstone-missing' }, now });
|
|
591
|
+
throw memoryError('E_TOMBSTONE_INCOMPLETE', `恢复被拒绝:tombstones.md 找不到 ${rel} 的完整条目`);
|
|
592
|
+
}
|
|
593
|
+
if (!tomb.backup || typeof tomb.backup.path !== 'string' || tomb.backup.path === ''
|
|
594
|
+
|| typeof tomb.backup.sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(tomb.backup.sha256)) {
|
|
595
|
+
auditDenied({ root: memoryRoot, action: 'restore-denied', recordId: rel, code: 'E_TOMBSTONE_INCOMPLETE', extra: { reason: 'missing-backup-field', tombstone: tomb.line }, now });
|
|
596
|
+
throw memoryError('E_TOMBSTONE_INCOMPLETE', `恢复被拒绝:tombstone 缺 backup{path,sha256}:${rel}`);
|
|
597
|
+
}
|
|
598
|
+
const ledger = verifyTombstoneLedger(memoryRoot, key);
|
|
599
|
+
if (!ledger.ok) {
|
|
600
|
+
auditDenied({ root: memoryRoot, action: 'restore-denied', recordId: rel, code: ledger.code, extra: { reason: 'tombstone-signature-chain', ledger }, now });
|
|
601
|
+
throw memoryError(ledger.code, `恢复被拒绝:tombstone 签名/哈希链无效(${ledger.code}, line=${ledger.line ?? '-'})`);
|
|
602
|
+
}
|
|
603
|
+
let backupVerified = null;
|
|
604
|
+
{
|
|
605
|
+
const expected = tomb.backup.sha256;
|
|
606
|
+
let actual = null;
|
|
607
|
+
try { actual = sha256File(resolveInside(memoryRoot, tomb.backup.path)); } catch { actual = null; }
|
|
608
|
+
if (actual === null || actual !== expected) {
|
|
609
|
+
auditDenied({
|
|
610
|
+
root: memoryRoot,
|
|
611
|
+
action: 'restore-denied',
|
|
612
|
+
recordId: rel,
|
|
613
|
+
code: 'E_RESTORE_BACKUP_MISMATCH',
|
|
614
|
+
extra: { backup: tomb.backup, expectedSha256: expected, actualSha256: actual, sourceAnchor: tomb.sourceAnchor ?? null },
|
|
615
|
+
now,
|
|
616
|
+
});
|
|
617
|
+
throw memoryError('E_RESTORE_BACKUP_MISMATCH', `恢复前备份校验失败:${rel}(backup=${tomb.backup.path})`, {
|
|
618
|
+
expectedSha256: expected,
|
|
619
|
+
actualSha256: actual,
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
backupVerified = true;
|
|
623
|
+
}
|
|
624
|
+
let from = null;
|
|
625
|
+
let source = null;
|
|
626
|
+
if (tomb?.recoverable) {
|
|
627
|
+
const candidate = resolveInside(memoryRoot, tomb.recoverable);
|
|
628
|
+
if (fs.existsSync(candidate)) {
|
|
629
|
+
source = candidate;
|
|
630
|
+
from = tomb.recoverable;
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
if (!source) {
|
|
634
|
+
const epochCandidate = path.join(epochsDir(memoryRoot), rel);
|
|
635
|
+
if (fs.existsSync(epochCandidate)) {
|
|
636
|
+
source = epochCandidate;
|
|
637
|
+
from = relativePath(memoryRoot, epochCandidate);
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
if (!source) throw memoryError('E_RESTORE_NOT_FOUND', `找不到可恢复的副本:${rel}(tombstones recoverable / epochs 均未命中)`);
|
|
641
|
+
if (isProtectedPath({ memoryRoot, relPath: rel }) === true) {
|
|
642
|
+
// 恢复本身是“加回”而不是“删除”,保护卡也允许恢复(保留 fail-safe 只在删除方向)。
|
|
643
|
+
}
|
|
644
|
+
ensureDir(memoryRoot, path.dirname(target));
|
|
645
|
+
fs.renameSync(source, target);
|
|
646
|
+
appendAudit(memoryRoot, { action: 'memory_forget_restore', object: rel, result: `from=${from} by=${by}`, now });
|
|
647
|
+
auditRestore({ root: memoryRoot, recordId: rel, from, to: rel, by, now });
|
|
648
|
+
try {
|
|
649
|
+
appendAuditRecord({
|
|
650
|
+
memoryRoot,
|
|
651
|
+
action: 'restore',
|
|
652
|
+
recordId: rel,
|
|
653
|
+
readerTier: 'host',
|
|
654
|
+
questionId: 'unknown',
|
|
655
|
+
expectedTurns: null,
|
|
656
|
+
answerText: null,
|
|
657
|
+
at: now.toISOString(),
|
|
658
|
+
extra: {
|
|
659
|
+
forgetV2: 'restore-enriched',
|
|
660
|
+
from,
|
|
661
|
+
to: rel,
|
|
662
|
+
by,
|
|
663
|
+
backup: tomb?.backup ?? null,
|
|
664
|
+
backupSha256: tomb?.backup?.sha256 ?? tomb?.sha256 ?? null,
|
|
665
|
+
backupVerified,
|
|
666
|
+
sourceAnchor: tomb?.sourceAnchor ?? null,
|
|
667
|
+
sourceEventIds: tomb?.sourceEventIds ?? [],
|
|
668
|
+
},
|
|
669
|
+
});
|
|
670
|
+
} catch { /* best effort; rename + audit.log already recorded */ }
|
|
671
|
+
return { ok: true, schema: FORGET_V2_SCHEMA, status: 'restored', path: rel, from, to: rel, restored: true, backupVerified };
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
/** Facade: mode=propose|execute|restore. */
|
|
675
|
+
export function forgetV2({ mode = 'propose', path: relPath = null, by = 'admin', now = new Date(), ...rest } = {}, config = {}) {
|
|
676
|
+
if (mode === 'propose') return { schema: FORGET_V2_SCHEMA, mode, ...proposeForget(rest, config) };
|
|
677
|
+
if (mode === 'execute') return { schema: FORGET_V2_SCHEMA, mode, ...executeForget(rest, config) };
|
|
678
|
+
if (mode === 'restore') return { schema: FORGET_V2_SCHEMA, mode, ...restoreForgotten({ root: config.memoryRoot, path: relPath, by, now }) };
|
|
679
|
+
throw memoryError('E_FORGET_V2_MODE', `未知 mode=${mode}(propose|execute|restore)`);
|
|
680
|
+
}
|