@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,279 @@
|
|
|
1
|
+
// Memory-layer filesystem state.
|
|
2
|
+
//
|
|
3
|
+
// One place owns every write into the memory root: the `.longlive` state file,
|
|
4
|
+
// the audit log, backups, reports, and the atomic write/verify/rollback path.
|
|
5
|
+
// Every path is re-checked against the root here, even when a caller already
|
|
6
|
+
// resolved it, so a bug upstream cannot become a write outside the store.
|
|
7
|
+
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import crypto from 'node:crypto';
|
|
11
|
+
|
|
12
|
+
import { memoryError, resolveInside, relativePath } from './paths.js';
|
|
13
|
+
|
|
14
|
+
export const LONGLIVE_DIR = '.longlive';
|
|
15
|
+
export const BACKUPS_DIR = 'backups';
|
|
16
|
+
export const REPORTS_DIR = 'reports';
|
|
17
|
+
|
|
18
|
+
export function longliveDir(root) {
|
|
19
|
+
return resolveInside(root, LONGLIVE_DIR);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function statePath(root) {
|
|
23
|
+
return resolveInside(root, path.join(LONGLIVE_DIR, 'memory-state.json'));
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function backupsDir(root) {
|
|
27
|
+
return resolveInside(root, path.join(LONGLIVE_DIR, BACKUPS_DIR));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function reportsDir(root) {
|
|
31
|
+
return resolveInside(root, path.join(LONGLIVE_DIR, REPORTS_DIR));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function auditPath(root) {
|
|
35
|
+
return resolveInside(root, path.join(LONGLIVE_DIR, 'audit.log'));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function tombstonesPath(root) {
|
|
39
|
+
return resolveInside(root, 'tombstones.md');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function archiveDir(root) {
|
|
43
|
+
return resolveInside(root, path.join('archive', 'tombstones'));
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function epochsDir(root) {
|
|
47
|
+
return resolveInside(root, 'epochs');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function stampToken(date = new Date()) {
|
|
51
|
+
return date.toISOString().replace(/[-:]/g, '').replace('T', '-').replace(/\..+$/, '') +
|
|
52
|
+
`-${String(date.getUTCMilliseconds()).padStart(3, '0')}`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function sha256Buffer(buffer) {
|
|
56
|
+
return crypto.createHash('sha256').update(buffer).digest('hex');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function sha256File(file) {
|
|
60
|
+
return sha256Buffer(fs.readFileSync(file));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function sha256Text(text) {
|
|
64
|
+
return sha256Buffer(Buffer.from(String(text), 'utf8'));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function ensureDir(root, dir) {
|
|
68
|
+
const abs = resolveInside(root, dir);
|
|
69
|
+
fs.mkdirSync(abs, { recursive: true });
|
|
70
|
+
return abs;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function collisionFree(dir, base, stamp, ext) {
|
|
74
|
+
let candidate = path.join(dir, `${base}.${stamp}${ext}`);
|
|
75
|
+
let index = 2;
|
|
76
|
+
while (fs.existsSync(candidate)) {
|
|
77
|
+
candidate = path.join(dir, `${base}.${stamp}-${index}${ext}`);
|
|
78
|
+
index += 1;
|
|
79
|
+
}
|
|
80
|
+
return candidate;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Copy one file into a backup directory inside the root and verify the copy
|
|
85
|
+
* byte-for-byte. A failed verification removes the partial copy and throws.
|
|
86
|
+
*/
|
|
87
|
+
export function backupInto(root, file, dir, { now = new Date() } = {}) {
|
|
88
|
+
const abs = resolveInside(root, file);
|
|
89
|
+
const targetDir = resolveInside(root, dir);
|
|
90
|
+
let stat = null;
|
|
91
|
+
try {
|
|
92
|
+
stat = fs.lstatSync(abs);
|
|
93
|
+
} catch (error) {
|
|
94
|
+
throw memoryError('E_BACKUP_SOURCE', `备份源不存在:${abs}`, error);
|
|
95
|
+
}
|
|
96
|
+
if (!stat.isFile()) {
|
|
97
|
+
throw memoryError('E_BACKUP_SOURCE', `备份源不是普通文件:${abs}`);
|
|
98
|
+
}
|
|
99
|
+
ensureDir(root, targetDir);
|
|
100
|
+
const ext = path.extname(abs);
|
|
101
|
+
const base = path.basename(abs, ext) || 'file';
|
|
102
|
+
const dest = collisionFree(targetDir, base, stampToken(now), ext || '.md');
|
|
103
|
+
fs.copyFileSync(abs, dest);
|
|
104
|
+
const want = sha256File(abs);
|
|
105
|
+
const got = sha256File(dest);
|
|
106
|
+
if (want !== got) {
|
|
107
|
+
try {
|
|
108
|
+
fs.unlinkSync(dest);
|
|
109
|
+
} catch {
|
|
110
|
+
/* best effort: never mask the verification error below */
|
|
111
|
+
}
|
|
112
|
+
throw memoryError('E_BACKUP_VERIFY', `备份校验失败:${dest} 与源文件 sha256 不一致`);
|
|
113
|
+
}
|
|
114
|
+
return { path: dest, rel: relativePath(root, dest), sha256: got };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Back a file up into `<root>/.longlive/backups/`. */
|
|
118
|
+
export function backupFile(root, file, options = {}) {
|
|
119
|
+
return backupInto(root, file, backupsDir(root), options);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Copy a verified backup back over its original, then verify again. */
|
|
123
|
+
export function restoreBackup(root, backup, target) {
|
|
124
|
+
const from = resolveInside(root, backup);
|
|
125
|
+
const to = resolveInside(root, target);
|
|
126
|
+
const want = sha256File(from);
|
|
127
|
+
fs.copyFileSync(from, to);
|
|
128
|
+
const got = sha256File(to);
|
|
129
|
+
if (got !== want) {
|
|
130
|
+
throw memoryError('E_ROLLBACK_FAILED', `回滚校验失败:${to} 的 sha256 与备份不一致`);
|
|
131
|
+
}
|
|
132
|
+
return { path: to, sha256: got };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
let tmpCounter = 0;
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Write `content` to `file` atomically: backup first, tmp + rename, read-back
|
|
139
|
+
* verify, and restore the original bytes if the verify fails. The caller gets
|
|
140
|
+
* the backup path so a later step can roll back deliberately as well.
|
|
141
|
+
*/
|
|
142
|
+
export function writeFileAtomic(root, file, content, { backup: wantBackup = true, now = new Date() } = {}) {
|
|
143
|
+
const abs = resolveInside(root, file);
|
|
144
|
+
ensureDir(root, path.dirname(abs));
|
|
145
|
+
const existed = fs.existsSync(abs);
|
|
146
|
+
const original = existed ? fs.readFileSync(abs) : null;
|
|
147
|
+
const originalSha = original ? sha256Buffer(original) : null;
|
|
148
|
+
const backup = existed && wantBackup ? backupFile(root, abs, { now }) : null;
|
|
149
|
+
const tmp = `${abs}.tmp-${process.pid}-${(tmpCounter += 1)}`;
|
|
150
|
+
try {
|
|
151
|
+
fs.writeFileSync(tmp, content, 'utf8');
|
|
152
|
+
const staged = fs.readFileSync(tmp, 'utf8');
|
|
153
|
+
if (staged !== content) {
|
|
154
|
+
throw memoryError('E_WRITE_VERIFY', `写入校验失败(临时文件):${tmp}`);
|
|
155
|
+
}
|
|
156
|
+
fs.renameSync(tmp, abs);
|
|
157
|
+
const readBack = fs.readFileSync(abs, 'utf8');
|
|
158
|
+
if (readBack !== content) {
|
|
159
|
+
throw memoryError('E_WRITE_VERIFY', `写入校验失败(读回内容不一致):${abs}`);
|
|
160
|
+
}
|
|
161
|
+
} catch (error) {
|
|
162
|
+
try {
|
|
163
|
+
if (fs.existsSync(tmp)) fs.unlinkSync(tmp);
|
|
164
|
+
} catch {
|
|
165
|
+
/* best effort: the error that matters is the one being rethrown */
|
|
166
|
+
}
|
|
167
|
+
if (originalSha != null) {
|
|
168
|
+
const currentSha = fs.existsSync(abs) ? sha256File(abs) : null;
|
|
169
|
+
if (currentSha !== originalSha) {
|
|
170
|
+
fs.writeFileSync(abs, original);
|
|
171
|
+
if (sha256File(abs) !== originalSha) {
|
|
172
|
+
throw memoryError('E_ROLLBACK_FAILED', `写失败后无法恢复原文件:${abs}`, error);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
throw error instanceof Error && error.code ? error : memoryError('E_WRITE_FAILED', `写入失败:${abs}`, error);
|
|
177
|
+
}
|
|
178
|
+
const sha256 = sha256Text(content);
|
|
179
|
+
return {
|
|
180
|
+
path: abs,
|
|
181
|
+
rel: relativePath(root, abs),
|
|
182
|
+
backup: backup?.path ?? null,
|
|
183
|
+
backupRel: backup?.rel ?? null,
|
|
184
|
+
sha256,
|
|
185
|
+
bytes: Buffer.byteLength(content, 'utf8'),
|
|
186
|
+
created: !existed,
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
export function readJsonFile(file, code, label) {
|
|
191
|
+
let text = null;
|
|
192
|
+
try {
|
|
193
|
+
text = fs.readFileSync(file, 'utf8');
|
|
194
|
+
} catch (error) {
|
|
195
|
+
if (error?.code === 'ENOENT') return null;
|
|
196
|
+
throw memoryError(code, `读取失败:${label ?? file}`, error);
|
|
197
|
+
}
|
|
198
|
+
try {
|
|
199
|
+
return JSON.parse(text);
|
|
200
|
+
} catch (error) {
|
|
201
|
+
throw memoryError(code, `JSON 解析失败:${label ?? file} — 文件可能被截断,先修好它再跑工具`, error);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const STATE_DEFAULTS = Object.freeze({
|
|
206
|
+
lastConsolidated: null,
|
|
207
|
+
indexBuiltAt: null,
|
|
208
|
+
forgetRuns: [],
|
|
209
|
+
seenProposals: [],
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
/** Read `.longlive/memory-state.json`; a missing file is an empty state. */
|
|
213
|
+
export function readState(root) {
|
|
214
|
+
const file = statePath(root);
|
|
215
|
+
const raw = readJsonFile(file, 'E_STATE_CORRUPT', file);
|
|
216
|
+
if (raw == null) return { ...STATE_DEFAULTS, forgetRuns: [], seenProposals: [] };
|
|
217
|
+
if (typeof raw !== 'object' || Array.isArray(raw)) {
|
|
218
|
+
throw memoryError('E_STATE_CORRUPT', `memory-state.json 必须是对象:${file}`);
|
|
219
|
+
}
|
|
220
|
+
return {
|
|
221
|
+
...STATE_DEFAULTS,
|
|
222
|
+
...raw,
|
|
223
|
+
forgetRuns: Array.isArray(raw.forgetRuns) ? raw.forgetRuns : [],
|
|
224
|
+
seenProposals: Array.isArray(raw.seenProposals) ? raw.seenProposals : [],
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Merge `patch` into the state file (backup + verify through writeFileAtomic). */
|
|
229
|
+
export function updateState(root, patch, { now = new Date() } = {}) {
|
|
230
|
+
const current = readState(root);
|
|
231
|
+
const next = { ...current, ...patch, updatedAt: now.toISOString() };
|
|
232
|
+
const result = writeFileAtomic(root, statePath(root), `${JSON.stringify(next, null, 2)}\n`, { now });
|
|
233
|
+
return { ...next, write: result };
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Append one audit line: ISO time, action, object, result. */
|
|
237
|
+
export function appendAudit(root, { action, object, result, now = new Date() }) {
|
|
238
|
+
const line = [
|
|
239
|
+
now.toISOString(),
|
|
240
|
+
String(action ?? 'unknown').replace(/[\t\r\n]+/g, ' '),
|
|
241
|
+
String(object ?? '-').replace(/[\t\r\n]+/g, ' '),
|
|
242
|
+
String(result ?? '-').replace(/[\t\r\n]+/g, ' '),
|
|
243
|
+
].join('\t');
|
|
244
|
+
const file = auditPath(root);
|
|
245
|
+
ensureDir(root, path.dirname(file));
|
|
246
|
+
fs.appendFileSync(file, `${line}\n`, 'utf8');
|
|
247
|
+
return { path: file, line };
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** Recursively list `.md` files under `subdir`; missing dir is an empty list. */
|
|
251
|
+
export function listMarkdownFiles(root, subdir) {
|
|
252
|
+
const base = resolveInside(root, subdir);
|
|
253
|
+
let stat = null;
|
|
254
|
+
try {
|
|
255
|
+
stat = fs.lstatSync(base);
|
|
256
|
+
} catch (error) {
|
|
257
|
+
if (error?.code === 'ENOENT') return [];
|
|
258
|
+
throw memoryError('E_LIST_FAILED', `读不到目录:${base}`, error);
|
|
259
|
+
}
|
|
260
|
+
if (stat.isSymbolicLink()) {
|
|
261
|
+
throw memoryError('E_SYMLINK_REFUSED', `拒绝跟随符号链接:${base}`);
|
|
262
|
+
}
|
|
263
|
+
if (!stat.isDirectory()) return [];
|
|
264
|
+
const found = [];
|
|
265
|
+
const walk = (dir) => {
|
|
266
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
267
|
+
if (entry.name.startsWith('.')) continue;
|
|
268
|
+
const abs = path.join(dir, entry.name);
|
|
269
|
+
if (entry.isSymbolicLink()) continue; // never follow a link out of the store
|
|
270
|
+
if (entry.isDirectory()) {
|
|
271
|
+
walk(abs);
|
|
272
|
+
} else if (entry.isFile() && entry.name.toLowerCase().endsWith('.md')) {
|
|
273
|
+
found.push(abs);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
};
|
|
277
|
+
walk(base);
|
|
278
|
+
return found.sort((a, b) => a.localeCompare(b));
|
|
279
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// src/memory/tiers.js — 03 热温冷分层(recall tier)纯规则层。
|
|
2
|
+
// 内容:TIERS / TIER_SCHEMA / DEFAULT_TIERING(默认值唯一来源)/ normalizeTiering
|
|
3
|
+
// (归一化)/ resolveTierPolicy(读取策略唯一判据)/ buildTierHint(收窄提示唯一实现)/
|
|
4
|
+
// isBusyError(BUSY 分类);零 I/O、不 import fs、无网络。
|
|
5
|
+
// 设计:designs/03-tiers.v4.md §3 / §6 + 附录 C(v4);测试:impl/03/tests/run.mjs。
|
|
6
|
+
|
|
7
|
+
export const TIERS = Object.freeze(['hot', 'warm', 'cold']);
|
|
8
|
+
export const TIER_SCHEMA = 'tiers/v1';
|
|
9
|
+
/** meta.tier_* 键名(tiers-clear / status / health 共用,§7.1)。 */
|
|
10
|
+
export const TIER_PASS_META_KEYS = Object.freeze([
|
|
11
|
+
'tier_schema', 'tier_pass_at', 'tier_labels_source', 'tier_counts', 'tier_pass_ms',
|
|
12
|
+
]);
|
|
13
|
+
export const TIER_FILTERS = Object.freeze(['off', 'shadow', 'auto', 'time-fallback', 'hot', 'warm', 'cold', 'all']);
|
|
14
|
+
const FILTERING = new Set(['auto', 'time-fallback', 'hot', 'warm', 'cold']);
|
|
15
|
+
export const isFilteringTierFilter = (tierFilter) => FILTERING.has(String(tierFilter));
|
|
16
|
+
|
|
17
|
+
/** 唯一默认值来源:配置读不到 / 键缺失 / 非法值时都回落到这里。 */
|
|
18
|
+
export const DEFAULT_TIERING = Object.freeze({
|
|
19
|
+
mode: 'shadow',
|
|
20
|
+
hotSessions: 3,
|
|
21
|
+
hotTurns: 40,
|
|
22
|
+
hotCardDays: 7,
|
|
23
|
+
hotCardMax: 20,
|
|
24
|
+
warmDays: 30,
|
|
25
|
+
hotDays: 3,
|
|
26
|
+
maxStaleHours: 72,
|
|
27
|
+
suppressedCap: 200,
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
export function normalizeTiering(raw = {}) {
|
|
31
|
+
const out = { ...DEFAULT_TIERING };
|
|
32
|
+
const src = raw && typeof raw === 'object' ? raw : {};
|
|
33
|
+
const int = (v, lo, hi, dflt) => {
|
|
34
|
+
const n = Number(v);
|
|
35
|
+
if (!Number.isFinite(n)) return dflt;
|
|
36
|
+
return Math.max(lo, Math.min(hi, Math.trunc(n)));
|
|
37
|
+
};
|
|
38
|
+
out.hotSessions = int(src.hotSessions, 1, 20, DEFAULT_TIERING.hotSessions);
|
|
39
|
+
out.hotTurns = int(src.hotTurns, 1, 500, DEFAULT_TIERING.hotTurns);
|
|
40
|
+
out.hotCardDays = int(src.hotCardDays, 1, 365, DEFAULT_TIERING.hotCardDays);
|
|
41
|
+
out.hotCardMax = int(src.hotCardMax, 1, 200, DEFAULT_TIERING.hotCardMax);
|
|
42
|
+
out.warmDays = int(src.warmDays, 1, 3650, DEFAULT_TIERING.warmDays);
|
|
43
|
+
out.hotDays = int(src.hotDays, 1, 30, DEFAULT_TIERING.hotDays);
|
|
44
|
+
out.maxStaleHours = int(src.maxStaleHours, 1, 720, DEFAULT_TIERING.maxStaleHours);
|
|
45
|
+
out.suppressedCap = int(src.suppressedCap, 1, 1000, DEFAULT_TIERING.suppressedCap);
|
|
46
|
+
const mode = String(src.mode ?? '');
|
|
47
|
+
out.mode = ['off', 'shadow', 'filter'].includes(mode) ? mode : DEFAULT_TIERING.mode;
|
|
48
|
+
const kill = String(process.env.DSH_LONGLIVE_TIER_OFF ?? '');
|
|
49
|
+
if (kill === '1' || kill === 'true') out.mode = 'off';
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// ---- 附录 C(v4 逐字转写) ----
|
|
54
|
+
export function isBusyError(error) {
|
|
55
|
+
const code = Number(error?.errcode ?? NaN);
|
|
56
|
+
if (code === 5 || code === 6) return true;
|
|
57
|
+
const text = String(error?.errstr ?? error?.message ?? '');
|
|
58
|
+
return /database (?:table )?is locked/i.test(text);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function resolveTierPolicy({
|
|
62
|
+
mode = DEFAULT_TIERING.mode,
|
|
63
|
+
requested = 'auto',
|
|
64
|
+
hasTierColumn = false,
|
|
65
|
+
passAtMs = null,
|
|
66
|
+
labelsSource = null,
|
|
67
|
+
maxStaleHours = DEFAULT_TIERING.maxStaleHours,
|
|
68
|
+
nowMs = Date.now(),
|
|
69
|
+
hasReader = false,
|
|
70
|
+
} = {}) {
|
|
71
|
+
// MINOR-1:null/undefined = "没传" = auto;其余非白名单 = E_TIER_ARG
|
|
72
|
+
const tier = requested === null || requested === undefined ? 'auto' : String(requested);
|
|
73
|
+
if (!['auto', 'hot', 'warm', 'cold', 'all'].includes(tier)) {
|
|
74
|
+
return { error: 'E_TIER_ARG', code: 'E_TIER_ARG', requested: String(requested) };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// ★ M6:这三块与 mode 无关,所有分支都带出去
|
|
78
|
+
const passAtValid = Number.isFinite(passAtMs) && passAtMs > 0;
|
|
79
|
+
const stale = !passAtValid || (nowMs - passAtMs) > maxStaleHours * 3600000;
|
|
80
|
+
const labelsUsable = Boolean(hasTierColumn) && passAtValid && !stale && labelsSource === 'pass';
|
|
81
|
+
const base = {
|
|
82
|
+
hasTierColumn, passAtValid, stale, labelsUsable,
|
|
83
|
+
labelsSource: labelsSource ?? null,
|
|
84
|
+
reason: null,
|
|
85
|
+
};
|
|
86
|
+
const reasonOf = () => (!hasTierColumn ? 'no-tier-column'
|
|
87
|
+
: !passAtValid ? 'no-pass-meta'
|
|
88
|
+
: labelsSource !== 'pass' ? 'backfill-labels'
|
|
89
|
+
: 'stale');
|
|
90
|
+
|
|
91
|
+
if (tier === 'all') {
|
|
92
|
+
return { ...base, tierFilter: 'all', filtering: false, overlay: false, sqlKind: null, annotateOnly: hasTierColumn };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
if (tier !== 'auto') {
|
|
96
|
+
if (!hasTierColumn) {
|
|
97
|
+
return { ...base, error: 'E_TIER_SCHEMA_MISSING', code: 'E_TIER_SCHEMA_MISSING', requested: tier };
|
|
98
|
+
}
|
|
99
|
+
return {
|
|
100
|
+
...base, tierFilter: tier, filtering: true, sqlKind: 'label-explicit',
|
|
101
|
+
overlay: tier === 'hot', requested: tier, suppressedBasis: 'tier',
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
if (mode === 'off') {
|
|
106
|
+
return { ...base, tierFilter: 'off', filtering: false, overlay: false, sqlKind: null, annotateOnly: false };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// ★ H3:shadow 永不过滤
|
|
110
|
+
if (mode === 'shadow') {
|
|
111
|
+
return { ...base, tierFilter: 'shadow', filtering: false, overlay: false, sqlKind: null, annotateOnly: hasTierColumn };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
if (labelsUsable) {
|
|
115
|
+
return { ...base, tierFilter: 'auto', filtering: true, overlay: true, sqlKind: 'label', suppressedBasis: 'tier' };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
return {
|
|
119
|
+
...base, reason: reasonOf(), tierFilter: 'time-fallback', filtering: true,
|
|
120
|
+
overlay: hasReader, sqlKind: 'time', suppressedBasis: 'time-window',
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function buildTierHint({
|
|
125
|
+
tierFilter = 'off',
|
|
126
|
+
coldSuppressed = 0,
|
|
127
|
+
coldSuppressedCapped = false,
|
|
128
|
+
suppressedBasis = null,
|
|
129
|
+
hits = 0,
|
|
130
|
+
warmDays = DEFAULT_TIERING.warmDays,
|
|
131
|
+
queryDegraded = false,
|
|
132
|
+
queryDegradedCode = null,
|
|
133
|
+
suppressedCap = DEFAULT_TIERING.suppressedCap,
|
|
134
|
+
baseHint = '',
|
|
135
|
+
} = {}) {
|
|
136
|
+
const filtering = isFilteringTierFilter(tierFilter);
|
|
137
|
+
const parts = [];
|
|
138
|
+
if (queryDegraded) {
|
|
139
|
+
parts.push(`索引查询期间有一路 FTS 策略失败(${queryDegradedCode ?? 'unknown'}),本次结果可能不完整;建议重试。`);
|
|
140
|
+
}
|
|
141
|
+
if (filtering && coldSuppressed === null) { // ★ MINOR-6:null 不是 0
|
|
142
|
+
parts.push('索引降级:本次无法统计被挡条数——结果可能不全,别据此判断「没记过」。');
|
|
143
|
+
}
|
|
144
|
+
const n = filtering && typeof coldSuppressed === 'number' && Number.isFinite(coldSuppressed)
|
|
145
|
+
? Math.max(0, coldSuppressed) : 0;
|
|
146
|
+
if (n > 0) {
|
|
147
|
+
if (hits === 0) parts.push('默认可见集合里没有命中,但不是「没记过」:');
|
|
148
|
+
if (suppressedBasis === 'time-window') {
|
|
149
|
+
parts.push(`另有 ${n} 条命中在默认时间窗口(warmDays=${warmDays} 天)之外,默认不返回;要查请重试 tier:'all'。`);
|
|
150
|
+
} else if (suppressedBasis === 'tier') {
|
|
151
|
+
// MINOR-4(round4):显式 hot/warm/cold 的被挡行 = "不属于该层",可能包含 hot 行,
|
|
152
|
+
// 不能一律归因成"冷层还有"(只有 auto 的 hidden 才是冷层)。§6.4 文字同步按此实现。
|
|
153
|
+
if (tierFilter === 'hot' || tierFilter === 'warm' || tierFilter === 'cold') {
|
|
154
|
+
parts.push(`该层之外还有 ${n} 条命中,默认不返回;要查请重试 tier:'all'。`);
|
|
155
|
+
} else {
|
|
156
|
+
parts.push(`冷层还有 ${n} 条命中,默认不返回;要查冷层请重试 tier:'all'。`);
|
|
157
|
+
}
|
|
158
|
+
} else {
|
|
159
|
+
// MINOR-2(round1):basis 未知也绝不静默——fail-closed 通用句(不猜 tier 还是时间窗口)。
|
|
160
|
+
parts.push(`另有 ${n} 条命中被当前可见范围挡住,默认不返回;要查请重试 tier:'all'。`);
|
|
161
|
+
}
|
|
162
|
+
if (coldSuppressedCapped) parts.push(`(只统计到 ${suppressedCap} 条上限)`);
|
|
163
|
+
}
|
|
164
|
+
const text = [baseHint, ...parts].filter(Boolean).join(' ').trim();
|
|
165
|
+
// ★ B1-③:不过滤态 fail-closed 自检
|
|
166
|
+
if (!filtering && /冷层还有|默认时间窗口|不是「没记过」/.test(text)) return String(baseHint ?? '').trim();
|
|
167
|
+
return text;
|
|
168
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// src/memory/topic-phrases.js — S8:事件记录的主题短语(topicPhrases)。
|
|
2
|
+
//
|
|
3
|
+
// 背景:`extractTurns` 的 summary/terms 之前只做首尾截断 + 整段 CJK run 过滤,
|
|
4
|
+
// 长句里的主题词(「五问」「智能体工程师」)在事件层不可见,auto 卡 title/terms
|
|
5
|
+
// 原样拷贝事件字段,于是召回/索引找不到主题。
|
|
6
|
+
//
|
|
7
|
+
// 本模块从一轮的原文(优先用户消息)抽「用户显式标记 + 内容块 + 实体后缀短语」,
|
|
8
|
+
// 作为 EventRecord.topicPhrases(可选字段;老记录无此字段,读取时按 [] 处理)。
|
|
9
|
+
// 纯函数、无 IO、无词典文件;输出顺序稳定(同输入同输出)。
|
|
10
|
+
|
|
11
|
+
import { normalizeForExtraction, quotedPhrasesOf, cjkContentChunks, entityPhrasesOf } from './fts-query.js';
|
|
12
|
+
|
|
13
|
+
export const TOPIC_PHRASES_MAX = 12;
|
|
14
|
+
const MAX_PHRASE_CHARS = 40;
|
|
15
|
+
|
|
16
|
+
function toTextList(text) {
|
|
17
|
+
if (Array.isArray(text)) return text.map((item) => String(item ?? '')).filter((item) => item.trim() !== '');
|
|
18
|
+
return String(text ?? '').trim() === '' ? [] : [String(text)];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function cleanPhrase(value) {
|
|
22
|
+
const phrase = normalizeForExtraction(value);
|
|
23
|
+
if (phrase === '') return '';
|
|
24
|
+
const chars = Array.from(phrase);
|
|
25
|
+
if (chars.length < 2 || chars.length > MAX_PHRASE_CHARS) return '';
|
|
26
|
+
return phrase;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Extract stable, ordered topic phrases from one turn's text.
|
|
31
|
+
*
|
|
32
|
+
* Priority: quoted/book-title phrases → entity suffix phrases → content chunks
|
|
33
|
+
* (long runs are segmented by function words instead of being dropped). Stable
|
|
34
|
+
* order: source order within each tier; tiers concatenated; deduped; capped.
|
|
35
|
+
*
|
|
36
|
+
* @param {string|string[]} text
|
|
37
|
+
* @param {{limit?:number}} [options]
|
|
38
|
+
* @returns {string[]}
|
|
39
|
+
*/
|
|
40
|
+
export function extractTopicPhrases(text, options = {}) {
|
|
41
|
+
const limit = Number.isInteger(options.limit) && options.limit > 0 ? options.limit : TOPIC_PHRASES_MAX;
|
|
42
|
+
const texts = toTextList(text);
|
|
43
|
+
if (texts.length === 0) return [];
|
|
44
|
+
const out = [];
|
|
45
|
+
const seen = new Set();
|
|
46
|
+
const push = (value) => {
|
|
47
|
+
const phrase = cleanPhrase(value);
|
|
48
|
+
if (phrase === '' || seen.has(phrase)) return;
|
|
49
|
+
seen.add(phrase);
|
|
50
|
+
out.push(phrase);
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
const joined = texts.join('\n');
|
|
54
|
+
|
|
55
|
+
// 1) 用户显式标记:引号 / 书名号 / 方括号 / 圆括号内短语。
|
|
56
|
+
for (const phrase of quotedPhrasesOf(joined)) push(phrase);
|
|
57
|
+
|
|
58
|
+
// 2) 实体后缀短语(智能体工程师 / 插件 / 版本 … 类名词短语)。
|
|
59
|
+
for (const phrase of entityPhrasesOf(joined, { limit: limit * 2 })) push(phrase);
|
|
60
|
+
|
|
61
|
+
// 3) 内容块(长 run 用虚词切开;2–12 字保留;更长块取 bigram 窗口意义不大,
|
|
62
|
+
// 这里只保留 2–12 字块,避免 topicPhrases 变成噪声)。
|
|
63
|
+
for (const text_ of texts) {
|
|
64
|
+
for (const run of normalizeForExtraction(text_).match(/[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]+/g) ?? []) {
|
|
65
|
+
for (const chunk of cjkContentChunks(run)) {
|
|
66
|
+
const chars = Array.from(chunk).length;
|
|
67
|
+
if (chars >= 2 && chars <= 12) push(chunk);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
return out.slice(0, limit);
|
|
73
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// src/memory/trust.js — 1.8.0 / v2.8 §15.1-A3:trustScore(规则写死,时间可注入)
|
|
2
|
+
//
|
|
3
|
+
// 公式(写死):
|
|
4
|
+
// w_tier = { user: 1.0, host: 0.9, agent: 0.6, plugin: 0.4 }
|
|
5
|
+
// trustScore = clamp(0, 1, w_tier * (1 + 0.1 * min(verifyCount, 5)) * decay)
|
|
6
|
+
// decay = 0.5 ^ (ageDays / 30) (ageDays 由注入的 now/createdAt 计算,不用真实等待)
|
|
7
|
+
//
|
|
8
|
+
// 时间注入 API(GOV-04:禁止 sleep 造假):
|
|
9
|
+
// - computeTrustScore({ sourceTier, verifyCount, ageDays })
|
|
10
|
+
// - trustScoreAt({ sourceTier, verifyCount, createdAt, now })
|
|
11
|
+
// - createGovTrustClock({ now }) → { at(createdAt), score(claim) } 测试显式传 now
|
|
12
|
+
// 低信任阈值 < 0.35 的 claim 只能进候选区、不得作为结论注入。
|
|
13
|
+
// legacy 迁移记录不做时间衰减(legacy:true → ageDays=0),避免把旧卡误判为低信任。
|
|
14
|
+
|
|
15
|
+
export const TRUST_TIERS = Object.freeze(['user', 'host', 'agent', 'plugin']);
|
|
16
|
+
export const TIER_WEIGHTS = Object.freeze({ user: 1.0, host: 0.9, agent: 0.6, plugin: 0.4 });
|
|
17
|
+
export const VERIFY_COUNT_CAP = 5;
|
|
18
|
+
export const LOW_TRUST_THRESHOLD = 0.35;
|
|
19
|
+
export const TRUST_SCHEMA = 'trust/v1';
|
|
20
|
+
|
|
21
|
+
function clamp01(value) {
|
|
22
|
+
if (!Number.isFinite(value)) return 0;
|
|
23
|
+
if (value < 0) return 0;
|
|
24
|
+
if (value > 1) return 1;
|
|
25
|
+
return value;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function toDateMs(value) {
|
|
29
|
+
if (value instanceof Date) return value.getTime();
|
|
30
|
+
if (typeof value === 'number' && Number.isFinite(value)) return value;
|
|
31
|
+
if (typeof value === 'string' && value !== '') {
|
|
32
|
+
const parsed = Date.parse(value);
|
|
33
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
34
|
+
}
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Pure formula (no clock): used directly by tests and by trustScoreAt. */
|
|
39
|
+
export function computeTrustScore({ sourceTier = 'agent', verifyCount = 0, ageDays = 0 } = {}) {
|
|
40
|
+
const tier = TRUST_TIERS.includes(sourceTier) ? sourceTier : 'agent';
|
|
41
|
+
const weight = TIER_WEIGHTS[tier];
|
|
42
|
+
const verified = Math.max(0, Math.min(VERIFY_COUNT_CAP, Number.isInteger(verifyCount) ? verifyCount : 0));
|
|
43
|
+
const days = Number.isFinite(ageDays) && ageDays > 0 ? ageDays : 0;
|
|
44
|
+
const decay = Math.pow(0.5, days / 30);
|
|
45
|
+
const score = weight * (1 + 0.1 * verified) * decay;
|
|
46
|
+
return {
|
|
47
|
+
schema: TRUST_SCHEMA,
|
|
48
|
+
sourceTier: tier,
|
|
49
|
+
verifyCount: verified,
|
|
50
|
+
ageDays: days,
|
|
51
|
+
decay,
|
|
52
|
+
trustScore: clamp01(score),
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Time-injected score: age is computed from createdAt → now (both injectable). */
|
|
57
|
+
export function trustScoreAt({ sourceTier = 'agent', verifyCount = 0, createdAt = null, now = new Date(), legacy = false } = {}) {
|
|
58
|
+
const nowMs = toDateMs(now) ?? Date.now();
|
|
59
|
+
const createdMs = toDateMs(createdAt);
|
|
60
|
+
// A backwards clock must not inflate trust: negative age clamps to 0 (CLOCK_ROLLBACK-safe).
|
|
61
|
+
const rawAgeDays = createdMs === null ? 0 : (nowMs - createdMs) / (24 * 60 * 60 * 1000);
|
|
62
|
+
const ageDays = legacy === true ? 0 : (Number.isFinite(rawAgeDays) && rawAgeDays > 0 ? rawAgeDays : 0);
|
|
63
|
+
return computeTrustScore({ sourceTier, verifyCount, ageDays });
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Time-injection seam for GOV-04 probes/tests (no sleep, no wall-clock dependency). */
|
|
67
|
+
export function createGovTrustClock({ now } = {}) {
|
|
68
|
+
const clockNow = () => (typeof now === 'function' ? now() : now ?? new Date());
|
|
69
|
+
return {
|
|
70
|
+
at: (createdAt) => trustScoreAt({ sourceTier: 'host', verifyCount: 0, createdAt, now: clockNow() }),
|
|
71
|
+
score: ({ sourceTier, verifyCount = 0, createdAt = null, legacy = false } = {}) => trustScoreAt({ sourceTier, verifyCount, createdAt, now: clockNow(), legacy }),
|
|
72
|
+
now: clockNow,
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function isLowTrust(trustScore) {
|
|
77
|
+
return !(typeof trustScore === 'number' && trustScore >= LOW_TRUST_THRESHOLD);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** 低信任不进结论注入;候选区仍可见(标 unverified)。 */
|
|
81
|
+
export function injectionEligibility(claim = {}, { lifecycle = null, historyQuery = false } = {}) {
|
|
82
|
+
const score = typeof claim.trustScore === 'number' ? claim.trustScore : 0;
|
|
83
|
+
const base = {
|
|
84
|
+
eligible: !isLowTrust(score),
|
|
85
|
+
unverified: isLowTrust(score),
|
|
86
|
+
trustScore: score,
|
|
87
|
+
};
|
|
88
|
+
// 1.8.11 D1/D6 接线:lifecycle 只表达「卡在现行 canon 的位置」,
|
|
89
|
+
// 不产生第二套权威分(authority 仍由 trustScore/strength 决定)。
|
|
90
|
+
// historical 默认不进结论注入;只有本轮显式历史查询才放行并标 historical。
|
|
91
|
+
if (lifecycle !== 'canonical' && lifecycle !== 'historical') return base;
|
|
92
|
+
if (lifecycle === 'canonical') return { ...base, lifecycle: 'canonical' };
|
|
93
|
+
if (historyQuery === true) {
|
|
94
|
+
return { ...base, lifecycle: 'historical', historical: true, reason: 'lifecycle-historical-explicit' };
|
|
95
|
+
}
|
|
96
|
+
return { ...base, eligible: false, lifecycle: 'historical', historical: true, reason: 'lifecycle-historical' };
|
|
97
|
+
}
|