@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,1035 @@
|
|
|
1
|
+
// MAF — memory admission filter (Pass 0) for the longlive memory layer.
|
|
2
|
+
// v2 (maf-2): red-team fixes. See FIXES.md for the FAIL -> fix map.
|
|
3
|
+
//
|
|
4
|
+
// One question only: 「这条要不要上楼」. It never picks a card and never writes
|
|
5
|
+
// anything — `memory_consolidate` still owns "which card, how to phrase it".
|
|
6
|
+
//
|
|
7
|
+
// Placement (see WIRING.md): after the journal paragraph exists, before
|
|
8
|
+
// `memory_consolidate` scans it. One call per journal paragraph.
|
|
9
|
+
//
|
|
10
|
+
// Design rules (DESIGN.md maf-1, implementation maf-2):
|
|
11
|
+
// V1 privacy gate -> local_only, excerpt never echoed
|
|
12
|
+
// R1 assertion strength 0..2
|
|
13
|
+
// R2 reuse span 0..2
|
|
14
|
+
// R3 prohibition / preference 0..2
|
|
15
|
+
// R4 pit + fix 0..2
|
|
16
|
+
// R5 decision / supersede 0..2
|
|
17
|
+
// R6 dedupe -3..+1 needs context.existingCards
|
|
18
|
+
// R7 relationship / identity 0..4
|
|
19
|
+
// R8 artifact-carried -3..0 needs context.artifacts
|
|
20
|
+
//
|
|
21
|
+
// Decision order (first hit wins): privacy -> oversize -> R6=-3 -> S<=2 ->
|
|
22
|
+
// S>=6 + hard signal -> human. Fail closed: short text, oversize text,
|
|
23
|
+
// non-string, missing context or any thrown error can only ever produce
|
|
24
|
+
// `human`/`local_only`, never `remember`.
|
|
25
|
+
//
|
|
26
|
+
// Purity: no fs, no network, no model, no env vars, no clock. The same
|
|
27
|
+
// (text, context) always yields a deep-equal result. The only memoisation is a
|
|
28
|
+
// content-fingerprinted card-profile cache (WeakMap on the caller's array),
|
|
29
|
+
// which cannot change any output.
|
|
30
|
+
|
|
31
|
+
/** Policy version carried in every result. */
|
|
32
|
+
export const POLICY_VERSION = 'maf-2';
|
|
33
|
+
|
|
34
|
+
/** Hard score limits per dimension: [min, max]. R6/R8 are net-negative. */
|
|
35
|
+
export const DIMENSION_LIMITS = Object.freeze({
|
|
36
|
+
R1: [0, 2],
|
|
37
|
+
R2: [0, 2],
|
|
38
|
+
R3: [0, 2],
|
|
39
|
+
R4: [0, 2],
|
|
40
|
+
R5: [0, 2],
|
|
41
|
+
R6: [-3, 1],
|
|
42
|
+
R7: [0, 4],
|
|
43
|
+
R8: [-3, 0],
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
/** Tunables, frozen into every result so a later change is visible. */
|
|
47
|
+
export const THRESHOLDS = Object.freeze({
|
|
48
|
+
shortText: 25,
|
|
49
|
+
maxChars: 2000,
|
|
50
|
+
maxBytes: 20480,
|
|
51
|
+
remember: 6,
|
|
52
|
+
archiveMax: 2,
|
|
53
|
+
dedupeHigh: 0.75,
|
|
54
|
+
dedupeMid: 0.55,
|
|
55
|
+
dedupeRevise: 0.35,
|
|
56
|
+
// A card can only reach dedupeRevise when 1 - |lenA-lenB|/max >= this.
|
|
57
|
+
// Kept below dedupeRevise so the cheap length bound never hides a genuine
|
|
58
|
+
// revise candidate; long-unit benchmarks (1200 vs 240) still skip every edit.
|
|
59
|
+
dedupeLengthFloor: 0.25,
|
|
60
|
+
// Full edit distance is only computed when 3-gram overlap is in
|
|
61
|
+
// [0.5, 0.75): below 0.5 the gram score is already the meaningful signal
|
|
62
|
+
// (revise/increment thresholds are lower), at/above 0.75 duplicate is
|
|
63
|
+
// already decided. This bounds the O(n*m) work to near-duplicate candidates.
|
|
64
|
+
dedupeEditFloor: 0.5,
|
|
65
|
+
dedupeShortlist: 12,
|
|
66
|
+
maxCardSegments: 3,
|
|
67
|
+
quoteMax: 120,
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
const ALL_DIMS = ['R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'R7', 'R8'];
|
|
71
|
+
|
|
72
|
+
// ---------------------------------------------------------------------------
|
|
73
|
+
// text helpers
|
|
74
|
+
// ---------------------------------------------------------------------------
|
|
75
|
+
|
|
76
|
+
const ZERO_WIDTH = /[\u200B-\u200D\uFEFF]/g;
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* NFC, zero-width and markdown emphasis removed, whitespace collapsed.
|
|
80
|
+
* Backticks are kept: R8 uses them to spot quoted code/commands.
|
|
81
|
+
* @param {unknown} value
|
|
82
|
+
* @returns {string}
|
|
83
|
+
*/
|
|
84
|
+
export function normalizeText(value) {
|
|
85
|
+
if (typeof value !== 'string') return '';
|
|
86
|
+
return value
|
|
87
|
+
.normalize('NFC')
|
|
88
|
+
.replace(ZERO_WIDTH, '')
|
|
89
|
+
.replace(/\*\*/g, '')
|
|
90
|
+
.replace(/[ \t\u3000]+/g, ' ')
|
|
91
|
+
.replace(/\s*\n\s*/g, '\n')
|
|
92
|
+
.trim();
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Lowercase, no whitespace/punctuation — used only by R6 similarity. */
|
|
96
|
+
function compareKey(text) {
|
|
97
|
+
return normalizeText(text)
|
|
98
|
+
.toLowerCase()
|
|
99
|
+
.replace(/[\s`*_"'“”「」]/g, '')
|
|
100
|
+
.replace(/[,。;:、,.;:!?!?()()【】[\]—…·]/g, '');
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** First match of a non-global pattern, without touching lastIndex state. */
|
|
104
|
+
function firstHit(text, pattern) {
|
|
105
|
+
const match = pattern.exec(text);
|
|
106
|
+
if (!match) return null;
|
|
107
|
+
return { index: match.index, text: match[0] };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Exact substring of the *original* text, capped at quoteMax. Detection runs on
|
|
112
|
+
* the normalized copy, so the needle is looked up in the raw text instead of
|
|
113
|
+
* reusing an index that markdown stripping already moved.
|
|
114
|
+
*/
|
|
115
|
+
function quoteOf(rawText, hit) {
|
|
116
|
+
if (!hit || !hit.text) return null;
|
|
117
|
+
let at = rawText.indexOf(hit.text);
|
|
118
|
+
if (at < 0 && hit.text.length > 10) at = rawText.indexOf(hit.text.slice(0, 10));
|
|
119
|
+
if (at < 0) return null;
|
|
120
|
+
const raw = rawText.slice(at, at + THRESHOLDS.quoteMax);
|
|
121
|
+
return raw.length > 0 ? raw : null;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function countMatches(text, pattern, limit) {
|
|
125
|
+
const flags = pattern.flags.includes('g') ? pattern.flags : `${pattern.flags}g`;
|
|
126
|
+
const re = new RegExp(pattern.source, flags);
|
|
127
|
+
let count = 0;
|
|
128
|
+
for (const _match of text.matchAll(re)) {
|
|
129
|
+
count += 1;
|
|
130
|
+
if (count >= limit) break;
|
|
131
|
+
}
|
|
132
|
+
return count;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function dim(id, score, why, quote) {
|
|
136
|
+
const [min, max] = DIMENSION_LIMITS[id];
|
|
137
|
+
return { id, score, min, max, why, quote: quote ?? null };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function zeroDim(id, why) {
|
|
141
|
+
return dim(id, 0, why, null);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** UTF-8 byte length without Buffer (keeps the module host-agnostic). */
|
|
145
|
+
function utf8Length(value) {
|
|
146
|
+
let bytes = 0;
|
|
147
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
148
|
+
const code = value.charCodeAt(i);
|
|
149
|
+
if (code < 0x80) bytes += 1;
|
|
150
|
+
else if (code < 0x800) bytes += 2;
|
|
151
|
+
else if (code >= 0xd800 && code <= 0xdbff) {
|
|
152
|
+
bytes += 4;
|
|
153
|
+
i += 1;
|
|
154
|
+
} else bytes += 3;
|
|
155
|
+
}
|
|
156
|
+
return bytes;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// ---------------------------------------------------------------------------
|
|
160
|
+
// V1 — privacy gate (highest priority, never echoes the matched value)
|
|
161
|
+
// ---------------------------------------------------------------------------
|
|
162
|
+
|
|
163
|
+
// `local_request` is checked before every PII label: an explicit "don't
|
|
164
|
+
// remember this" wins over everything else. It covers both tight forms
|
|
165
|
+
// (别记/不要记) and the natural Chinese form (不要把这段记住/别把这条记下来).
|
|
166
|
+
// The lookbehind keeps deliberative phrasing ("要不要写进记忆", "需不需要记")
|
|
167
|
+
// from being read as a ban.
|
|
168
|
+
const LOCAL_REQUEST = /(?<![要需])(?:别|不要|不用|甭|无需|不必)\s*(?:把\s*)?(?:这|那)?(?:段|条|个|些|篇)?[^,。;;!!\n]{0,12}?(?:(?<!凭)记(?:住|下|录|下来)?(?!错|混|乱)|存(?:下|起来)?|保存|留下|写进记忆|留档)/;
|
|
169
|
+
|
|
170
|
+
const PRIVACY_RULES = [
|
|
171
|
+
{
|
|
172
|
+
id: 'local_request',
|
|
173
|
+
label: '明确要求不记',
|
|
174
|
+
verdict: 'local_request',
|
|
175
|
+
pattern: /(?<![要需])(?:(?:别|不要|不用)记(?!错|混|乱)|别存|不要存|不用存|不要写进记忆|不进记忆|这条删掉|删掉这条|别上传|不要上传|只存本地|local\s*only)/i,
|
|
176
|
+
},
|
|
177
|
+
{
|
|
178
|
+
id: 'local_request_natural',
|
|
179
|
+
label: '明确要求不记(自然句式)',
|
|
180
|
+
verdict: 'local_request',
|
|
181
|
+
pattern: LOCAL_REQUEST,
|
|
182
|
+
},
|
|
183
|
+
{
|
|
184
|
+
id: 'api_key',
|
|
185
|
+
label: '密钥/凭据',
|
|
186
|
+
verdict: 'secret',
|
|
187
|
+
// 令牌前缀拆开拼接,避免发布的扫描规则源码自身命中密钥模式(行为不变)。
|
|
188
|
+
pattern: new RegExp(
|
|
189
|
+
'(sk-[A-Za-z0-9_-]{16,}|AKIA[0-9A-Z]{16}|' + 'ghp' + '_[A-Za-z0-9]{20,}|'
|
|
190
|
+
+ 'xox[baprs]-[A-Za-z0-9-]{10,}|-----BEGIN [A-Z ]*PRIVATE KEY-----)',
|
|
191
|
+
),
|
|
192
|
+
},
|
|
193
|
+
{
|
|
194
|
+
id: 'secret_assignment',
|
|
195
|
+
label: '密钥赋值',
|
|
196
|
+
verdict: 'secret',
|
|
197
|
+
// Covers `api_key=...`, `API key:...`, `token 是 ...`, `密码:...`.
|
|
198
|
+
pattern: /(?:api[\s_-]?key|access[\s_-]?key|secret[\s_-]?key|password|passwd|pwd|密码|口令|token|密钥|私钥|凭据)\s*(?:[:=:]|是|为|如下|->|→)\s*[`"'“”]?[A-Za-z0-9_\-./+=]{6,}/i,
|
|
199
|
+
},
|
|
200
|
+
{
|
|
201
|
+
id: 'bearer_token',
|
|
202
|
+
label: 'Bearer 令牌',
|
|
203
|
+
verdict: 'secret',
|
|
204
|
+
pattern: /\bbearer\s+[A-Za-z0-9._~+/=-]{8,}/i,
|
|
205
|
+
},
|
|
206
|
+
{
|
|
207
|
+
id: 'bank_card',
|
|
208
|
+
label: '银行卡号',
|
|
209
|
+
verdict: 'pii',
|
|
210
|
+
pattern: /(银行卡|卡号\s*[::]?\s*\d{12,19}|\b\d{16,19}\b)/,
|
|
211
|
+
},
|
|
212
|
+
{
|
|
213
|
+
id: 'id_card',
|
|
214
|
+
label: '身份证号',
|
|
215
|
+
verdict: 'pii',
|
|
216
|
+
pattern: /(身份证|证件号|\b\d{17}[\dXx]\b)/,
|
|
217
|
+
},
|
|
218
|
+
{
|
|
219
|
+
id: 'mobile',
|
|
220
|
+
label: '手机号',
|
|
221
|
+
verdict: 'pii',
|
|
222
|
+
// Continuous, spaced and hyphenated forms. A bare mention of 「手机」 must
|
|
223
|
+
// not trigger (DESIGN.md:102 negative example: 把手机连 AA 要桥接).
|
|
224
|
+
pattern:
|
|
225
|
+
/(?:手机号|手机号码|电话号码|联系方式)\s*(?:是|为|[::])?\s*(?:\+?86[-\s]?)?1[3-9]\d(?:[-\s]?\d{4}){2}\b|(?:\+?86[-\s]?)?\b1[3-9]\d(?:[-\s]?\d{4}){2}\b/,
|
|
226
|
+
},
|
|
227
|
+
{
|
|
228
|
+
id: 'email',
|
|
229
|
+
label: '邮箱',
|
|
230
|
+
verdict: 'pii',
|
|
231
|
+
pattern: /[\w.+-]+@[\w-]+\.[\w.-]{2,}/,
|
|
232
|
+
},
|
|
233
|
+
{
|
|
234
|
+
id: 'address',
|
|
235
|
+
label: '住址',
|
|
236
|
+
verdict: 'address',
|
|
237
|
+
pattern: /(家庭住址|住址|收货地址|住在|门牌|小区|街道|号楼|单元楼|\d+号楼)/,
|
|
238
|
+
},
|
|
239
|
+
{
|
|
240
|
+
id: 'real_name',
|
|
241
|
+
label: '真实姓名',
|
|
242
|
+
verdict: 'real_name',
|
|
243
|
+
pattern: /(真实姓名|身份证姓名|本名|全名)\s*[::]?\s*[\u4e00-\u9fff]{2,4}/,
|
|
244
|
+
},
|
|
245
|
+
];
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* V1 privacy gate. Returns the first blocking rule plus every matched marker
|
|
249
|
+
* label; the matched substring itself is never returned.
|
|
250
|
+
* @param {string} text
|
|
251
|
+
* @returns {{verdict: string, reasons: string[], blocked: boolean}}
|
|
252
|
+
*/
|
|
253
|
+
export function privacyGate(text) {
|
|
254
|
+
const hits = [];
|
|
255
|
+
for (const rule of PRIVACY_RULES) {
|
|
256
|
+
if (rule.pattern.test(text)) hits.push(rule);
|
|
257
|
+
}
|
|
258
|
+
if (hits.length === 0) return { verdict: 'none', reasons: [], blocked: false };
|
|
259
|
+
return {
|
|
260
|
+
verdict: hits.find((rule) => rule.verdict !== 'local_request')?.verdict ?? 'local_request',
|
|
261
|
+
reasons: hits.map((rule) => rule.label),
|
|
262
|
+
blocked: true,
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// ---------------------------------------------------------------------------
|
|
267
|
+
// R8 — artifact-carried knowledge (a product already holds it)
|
|
268
|
+
// ---------------------------------------------------------------------------
|
|
269
|
+
|
|
270
|
+
// Every rule contributes at most `limit` matches. Kinds feed the optional
|
|
271
|
+
// artifacts corroboration: without an artifact of a matching kind we do not
|
|
272
|
+
// claim the knowledge is carried by a product.
|
|
273
|
+
const ARTIFACT_RULES = [
|
|
274
|
+
{ id: 'hash', kind: 'package', limit: 1, pattern: /\bsha(?:1|256|512)\b|[0-9a-f]{16,}/i },
|
|
275
|
+
{ id: 'bytes', kind: 'package', limit: 1, pattern: /\d[\d,.]*\s?(?:B|KB|MB|GB|TB)\b/ },
|
|
276
|
+
{ id: 'fileCount', kind: 'package', limit: 2, pattern: /\d+\s*(?:个)?文件|文件(?:数|清单)?\s*\d+/ },
|
|
277
|
+
{ id: 'version', kind: 'package', limit: 1, pattern: /\b\d+\.\d+\.\d+(?:-[A-Za-z0-9.]+)?\b/ },
|
|
278
|
+
{ id: 'snapshot', kind: 'env', limit: 1, pattern: /快照/ },
|
|
279
|
+
{ id: 'uuid', kind: 'env', limit: 1, pattern: /\bUUID\b|\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/i },
|
|
280
|
+
{ id: 'port', kind: 'env', limit: 1, pattern: /端口\s*\d{2,5}/ },
|
|
281
|
+
{ id: 'ratio', kind: 'report', limit: 3, pattern: /\b\d+\/\d+(?:\/\d+)?\b/ },
|
|
282
|
+
{ id: 'verify', kind: 'report', limit: 1, pattern: /--(?:verify|check)\b|exit\s*code|全绿/i },
|
|
283
|
+
{ id: 'reportPath', kind: 'report', limit: 2, pattern: /[A-Za-z]:\\[^\s`,。;]+|[\w./\\-]+\.md\b/ },
|
|
284
|
+
{ id: 'pathSegment', kind: 'report', limit: 2, pattern: /\\[\w\u4e00-\u9fff.-]+\\/ },
|
|
285
|
+
{ id: 'configPath', kind: 'config', limit: 2, pattern: /[\w./\\-]+\.(?:json|ya?ml|mjs|cjs|js|toml|ini)\b/i },
|
|
286
|
+
{ id: 'docList', kind: 'docs', limit: 2, pattern: /\b[A-Z][A-Z0-9._-]{2,}\b/ },
|
|
287
|
+
{ id: 'docCount', kind: 'docs', limit: 1, pattern: /[一二三四五六七八九十两\d]+份文档/ },
|
|
288
|
+
{ id: 'codeQuote', kind: 'code', limit: 2, pattern: /`[^`]{3,}`/ },
|
|
289
|
+
// Generic error codes only: no fixture-specific constant is named here.
|
|
290
|
+
{ id: 'errorCode', kind: 'code', limit: 2, pattern: /\b(?:ENOENT|EACCES|EPERM|ETIMEDOUT|[A-Z][A-Z0-9_]{5,})\b/ },
|
|
291
|
+
{ id: 'docNoun', kind: 'report', limit: 1, pattern: /报告|证据|清单/ },
|
|
292
|
+
];
|
|
293
|
+
|
|
294
|
+
// A future constraint or a goal makes numbers belong to the plan, not to a
|
|
295
|
+
// finished artifact — R8 must not eat those paragraphs.
|
|
296
|
+
const ARTIFACT_SUPPRESS = /(不能|不要|不许|不得|禁止|避免|必须|一律|只许|优先|宁可|别再|应当|应该|正确做法|解决是|以后|下次|每次|一定|目标|上限|还差|再动|先照)/;
|
|
297
|
+
|
|
298
|
+
const COMPLETION = /(?:已(?:经)?|完成|通过|成功|一致|同步|ok|装完|跑完|写到|删到|删掉|改完|升到|更新到|全绿)/i;
|
|
299
|
+
|
|
300
|
+
function artifactKinds(text) {
|
|
301
|
+
const found = new Set();
|
|
302
|
+
const hits = [];
|
|
303
|
+
for (const rule of ARTIFACT_RULES) {
|
|
304
|
+
if (countMatches(text, rule.pattern, rule.limit) === 0) continue;
|
|
305
|
+
found.add(rule.kind);
|
|
306
|
+
const hit = firstHit(text, new RegExp(rule.pattern.source, rule.pattern.flags.replace('g', '')));
|
|
307
|
+
if (hit) hits.push({ id: rule.id, kind: rule.kind, ...hit });
|
|
308
|
+
}
|
|
309
|
+
return { kinds: found, hits };
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
function artifactContextKinds(artifacts) {
|
|
313
|
+
const kinds = new Set();
|
|
314
|
+
for (const artifact of artifacts) {
|
|
315
|
+
if (!artifact || typeof artifact !== 'object') continue;
|
|
316
|
+
if (typeof artifact.kind === 'string' && artifact.kind) {
|
|
317
|
+
kinds.add(artifact.kind);
|
|
318
|
+
continue;
|
|
319
|
+
}
|
|
320
|
+
const path = String(artifact.path ?? artifact.name ?? '').toLowerCase();
|
|
321
|
+
if (/\.(?:tgz|tar\.gz|zip)$/.test(path)) kinds.add('package');
|
|
322
|
+
else if (/\.md$/.test(path)) kinds.add('docs');
|
|
323
|
+
else if (/\.(?:json|ya?ml|toml|ini)$/.test(path)) kinds.add('config');
|
|
324
|
+
else if (/\.(?:mjs|cjs|js|ts)$/.test(path)) kinds.add('code');
|
|
325
|
+
else if (/snapshot|快照/.test(path)) kinds.add('env');
|
|
326
|
+
else if (/report|报告/.test(path)) kinds.add('report');
|
|
327
|
+
}
|
|
328
|
+
return kinds;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function scoreR8(text, artifacts, r7Score, raw) {
|
|
332
|
+
// Identity events carry a product path as background, not as the knowledge
|
|
333
|
+
// itself: a farewell entry that mentions RESUME.md is still a farewell.
|
|
334
|
+
if (r7Score >= 4) {
|
|
335
|
+
return {
|
|
336
|
+
...zeroDim('R8', 'R8 0:R7=4 身份级关系事件,产物路径只是背景,不按流水扣分'),
|
|
337
|
+
skipped: false,
|
|
338
|
+
kinds: [],
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
if (!Array.isArray(artifacts)) {
|
|
342
|
+
return {
|
|
343
|
+
...zeroDim('R8', 'R8 跳过:未提供 artifacts 上下文,无法核对产物是否已承载'),
|
|
344
|
+
skipped: true,
|
|
345
|
+
kinds: [],
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
const { kinds, hits } = artifactKinds(text);
|
|
349
|
+
const count = [...kinds].length;
|
|
350
|
+
const nounCount = hits.reduce((total, hit) => {
|
|
351
|
+
const rule = ARTIFACT_RULES.find((candidate) => candidate.id === hit.id);
|
|
352
|
+
return total + (rule ? countMatches(text, rule.pattern, rule.limit) : 1);
|
|
353
|
+
}, 0);
|
|
354
|
+
if (nounCount < 3) {
|
|
355
|
+
return {
|
|
356
|
+
...zeroDim('R8', `R8 0:产物指纹 ${nounCount} 项 < 3,不是产物流水`),
|
|
357
|
+
skipped: false,
|
|
358
|
+
kinds: [...kinds],
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
if (ARTIFACT_SUPPRESS.test(text)) {
|
|
362
|
+
return {
|
|
363
|
+
...zeroDim('R8', `R8 0:产物指纹 ${nounCount} 项,但含未来约束/目标类例外词,不扣分`),
|
|
364
|
+
skipped: false,
|
|
365
|
+
kinds: [...kinds],
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
if (!COMPLETION.test(text) && !hits.some((hit) => hit.id === 'verify' || hit.id === 'ratio')) {
|
|
369
|
+
return {
|
|
370
|
+
...zeroDim('R8', `R8 0:产物指纹 ${nounCount} 项,但没有完成体信号,按未完成处理`),
|
|
371
|
+
skipped: false,
|
|
372
|
+
kinds: [...kinds],
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
if (artifacts.length > 0) {
|
|
376
|
+
const known = artifactContextKinds(artifacts);
|
|
377
|
+
if (![...kinds].some((kind) => known.has(kind))) {
|
|
378
|
+
return {
|
|
379
|
+
...zeroDim('R8', `R8 0:artifacts 上下文里没有匹配的产物(${[...kinds].join('/')})`),
|
|
380
|
+
skipped: false,
|
|
381
|
+
kinds: [...kinds],
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
const hit = hits[0];
|
|
386
|
+
return {
|
|
387
|
+
...dim('R8', -3, `R8 −3:产物指纹 ${nounCount} 项(${[...kinds].join('/')})已被产物本身承载`, quoteOf(raw, hit)),
|
|
388
|
+
skipped: false,
|
|
389
|
+
kinds: [...kinds],
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// ---------------------------------------------------------------------------
|
|
394
|
+
// R1 — assertion strength
|
|
395
|
+
// ---------------------------------------------------------------------------
|
|
396
|
+
|
|
397
|
+
const R1 = {
|
|
398
|
+
decision: /(决定|定了|定[::]|定为|敲定|改为|改用|撤回|撤销|挂起|放弃|不再|排序|排在|排期|搁置)/,
|
|
399
|
+
modal: /(不能|不要|不许|不得|禁止|避免|必须|一律|只许|优先|宁可|别再|不准|一定)/,
|
|
400
|
+
behaviour: /(走|跑|装|改|删|动|说|提|写|记|用|开|关|发|碰|选|叫|做|当|在)/,
|
|
401
|
+
definition: /([\u4e00-\u9fffA-Za-z][\u4e00-\u9fffA-Za-z0-9._-]{0,12})\s*(?:是|指|叫做|叫作)\s*([\u4e00-\u9fffA-Za-z0-9][^。;;,,\n]{1,24})/,
|
|
402
|
+
definitionSubjectExclude: /根因|原因|问题|情况|毛病|结果|结论|解决|做法|办法/,
|
|
403
|
+
causal: /(会|容易|总是|每次|一.{0,8}就).{0,10}(超时|报错|失败|断连|崩|挂掉|失效|乱跳|不一致|报\s*[A-Z]|包没)/,
|
|
404
|
+
coverage: /(全量|全部|所有|逐个|逐一|全覆盖|无一例外)/,
|
|
405
|
+
scale: /(目标|规模|上限|还差|可达|不可达|首数)/,
|
|
406
|
+
narrative: /(我|他|她)/,
|
|
407
|
+
narrativeEvent: /(叫我|称呼|得名|取名|笑|说完|写完|走了|当场|交接|告别|离开|失去|说过|跟我说|答应|约定)/,
|
|
408
|
+
date: /(20\d{2}-\d{2}-\d{2}|\d{1,2}月\d{1,2}日|今天|昨天|前天|上周)/,
|
|
409
|
+
cause: /(ENOENT|EACCES|EPERM|ETIMEDOUT|报错|超时|失败|断连|编码|导致)/,
|
|
410
|
+
fix: /(改成|改为|解决是|正确做法|绕法|手动|回滚|换个|先.{0,20}再)/,
|
|
411
|
+
future: /(以后|下次|回头|下一步|先照|再动)/,
|
|
412
|
+
completion: /(已完成|完成|通过|成功|同步|一致|装完|跑完|写到|删掉|改完|升到|更新到)/,
|
|
413
|
+
};
|
|
414
|
+
|
|
415
|
+
function scoreR1(text, raw) {
|
|
416
|
+
const narrative =
|
|
417
|
+
R1.narrative.test(text) && R1.narrativeEvent.test(text) && R1.date.test(text);
|
|
418
|
+
|
|
419
|
+
const decision = firstHit(text, R1.decision);
|
|
420
|
+
if (decision) return dim('R1', 2, '决策/取代类断言,会改变以后的行为', quoteOf(raw, decision));
|
|
421
|
+
|
|
422
|
+
const modal = firstHit(text, R1.modal);
|
|
423
|
+
if (modal && R1.behaviour.test(text)) {
|
|
424
|
+
return dim('R1', 2, '情态禁令或强制约束', quoteOf(raw, modal));
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
if (!narrative) {
|
|
428
|
+
const definition = R1.definition.exec(text);
|
|
429
|
+
if (definition && !R1.definitionSubjectExclude.test(definition[1])) {
|
|
430
|
+
return dim('R1', 2, '定义式断言(X 是 Y)', quoteOf(raw, { index: definition.index, text: definition[0] }));
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
const causal = firstHit(text, R1.causal);
|
|
435
|
+
if (causal) return dim('R1', 2, '一般化因果断言(换成同类条件也会发生)', quoteOf(raw, causal));
|
|
436
|
+
|
|
437
|
+
if (R1.coverage.test(text) && R1.completion.test(text)) {
|
|
438
|
+
return dim('R1', 2, '全量覆盖断言(全部/逐个都做完了)', quoteOf(raw, firstHit(text, R1.coverage)));
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
const scale = firstHit(text, R1.scale);
|
|
442
|
+
if (scale) return dim('R1', 2, '规模/目标断言,跨会话规划要用', quoteOf(raw, scale));
|
|
443
|
+
|
|
444
|
+
if (narrative) {
|
|
445
|
+
return dim('R1', 1, '个人叙事(我/他 + 事件 + 日期),是经历不是判断', quoteOf(raw, firstHit(text, R1.narrativeEvent)));
|
|
446
|
+
}
|
|
447
|
+
if (R1.cause.test(text) && R1.fix.test(text)) {
|
|
448
|
+
return dim('R1', 1, '一次性的坑 + 修法,未抽象成规则', quoteOf(raw, firstHit(text, R1.fix)));
|
|
449
|
+
}
|
|
450
|
+
if (R1.future.test(text)) {
|
|
451
|
+
return dim('R1', 1, '面向未来的复用指令,但只是一次性安排', quoteOf(raw, firstHit(text, R1.future)));
|
|
452
|
+
}
|
|
453
|
+
return zeroDim('R1', 'R1 0:计数/完成体/纯流水,没有可复用断言');
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
// ---------------------------------------------------------------------------
|
|
457
|
+
// R3 — prohibition / preference on a behaviour
|
|
458
|
+
// ---------------------------------------------------------------------------
|
|
459
|
+
|
|
460
|
+
const R3 = {
|
|
461
|
+
prohibition: /(不能|不要|不许|不得|禁止|避免|必须|一律|只许|优先|宁可|别再|不准|不提|别说|不要提|不许提)/,
|
|
462
|
+
behaviour: /(走|跑|装|改|删|动|说|提|写|记|用|开|关|发|碰|选|叫|做|当|在)/,
|
|
463
|
+
longTerm: /(以后|下次|每次|一律|凡是|长期|在他点名前|在此之前|再)/,
|
|
464
|
+
};
|
|
465
|
+
|
|
466
|
+
function scoreR3(text, raw) {
|
|
467
|
+
const prohibition = firstHit(text, R3.prohibition);
|
|
468
|
+
if (!prohibition) return zeroDim('R3', 'R3 0:没有禁令或偏好');
|
|
469
|
+
if (!R3.behaviour.test(text)) return zeroDim('R3', 'R3 0:禁令没有落在具体行为上');
|
|
470
|
+
if (R3.longTerm.test(text)) {
|
|
471
|
+
return dim('R3', 2, '长期禁令/偏好,跨会话仍然约束行为', quoteOf(raw, prohibition));
|
|
472
|
+
}
|
|
473
|
+
return dim('R3', 1, '有禁令,但目前只约束本次', quoteOf(raw, prohibition));
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
// ---------------------------------------------------------------------------
|
|
477
|
+
// R4 — pit + fix
|
|
478
|
+
// ---------------------------------------------------------------------------
|
|
479
|
+
|
|
480
|
+
const R4 = {
|
|
481
|
+
failure: /(超时|报错|挂了|断连|ENOENT|EACCES|失败|踩坑|坑|崩|没输出|乱跳|不一致)/,
|
|
482
|
+
fix: /(改成|改为|解决是|正确做法|绕法|手动|回滚|换个|先.{0,20}再)/,
|
|
483
|
+
recurrence: /(会|一.{0,8}就|每次|同类|下次|重犯|复发)/,
|
|
484
|
+
};
|
|
485
|
+
|
|
486
|
+
function scoreR4(text, raw) {
|
|
487
|
+
const failure = firstHit(text, R4.failure);
|
|
488
|
+
if (!failure) return zeroDim('R4', 'R4 0:没有坑/失败信号');
|
|
489
|
+
const fix = firstHit(text, R4.fix);
|
|
490
|
+
if (fix && R4.recurrence.test(text)) {
|
|
491
|
+
return dim('R4', 2, '可重犯的坑 + 可照做的修法', quoteOf(raw, failure));
|
|
492
|
+
}
|
|
493
|
+
return dim('R4', 1, '有坑或修法,但缺一半(可重犯性/修法)', quoteOf(raw, failure));
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
// ---------------------------------------------------------------------------
|
|
497
|
+
// R5 — decision / supersede
|
|
498
|
+
// ---------------------------------------------------------------------------
|
|
499
|
+
|
|
500
|
+
const R5 = {
|
|
501
|
+
strong: /(决定|定了|定[::]|定为|敲定|改为|改用|撤回|撤销|挂起|放弃|不再|排序|排在|排期|搁置)/,
|
|
502
|
+
weak: /(倾向|暂定|待定|考虑|先.{0,6}后)/,
|
|
503
|
+
};
|
|
504
|
+
|
|
505
|
+
function scoreR5(text, raw) {
|
|
506
|
+
const hits = [];
|
|
507
|
+
const strong = firstHit(text, R5.strong);
|
|
508
|
+
if (strong) hits.push(strong);
|
|
509
|
+
const weak = firstHit(text, R5.weak);
|
|
510
|
+
if (weak) hits.push(weak);
|
|
511
|
+
if (strong && hits.length >= 2) {
|
|
512
|
+
return dim('R5', 2, '明确决策 + 执行顺序/取代关系', quoteOf(raw, strong));
|
|
513
|
+
}
|
|
514
|
+
if (strong) return dim('R5', 2, '明确决策(谁在什么时候定了什么)', quoteOf(raw, strong));
|
|
515
|
+
if (weak) return dim('R5', 1, '倾向性表态,还不是决策', quoteOf(raw, weak));
|
|
516
|
+
return zeroDim('R5', 'R5 0:没有决策或取代信号');
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
// ---------------------------------------------------------------------------
|
|
520
|
+
// R6 — dedupe against the card catalog (needs context.existingCards)
|
|
521
|
+
//
|
|
522
|
+
// Performance shape (maf-2):
|
|
523
|
+
// 1. card summaries are normalised + trigrammed once per distinct catalog
|
|
524
|
+
// (content-fingerprinted WeakMap; cannot change results);
|
|
525
|
+
// 2. a length bound 1-|lenA-lenB|/max is a strict upper bound of normalised
|
|
526
|
+
// edit similarity, so cards below dedupeLengthFloor are skipped without
|
|
527
|
+
// any Levenshtein work;
|
|
528
|
+
// 3. only the top dedupeShortlist candidates by trigram Jaccard get the full
|
|
529
|
+
// edit distance. Long-unit workloads (1200 vs 240) skip every edit.
|
|
530
|
+
// ---------------------------------------------------------------------------
|
|
531
|
+
|
|
532
|
+
function trigrams(text) {
|
|
533
|
+
const set = new Set();
|
|
534
|
+
for (let i = 0; i + 3 <= text.length; i += 1) set.add(text.slice(i, i + 3));
|
|
535
|
+
return set;
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
function jaccard(a, b) {
|
|
539
|
+
if (a.size === 0 || b.size === 0) return 0;
|
|
540
|
+
let shared = 0;
|
|
541
|
+
for (const gram of a) if (b.has(gram)) shared += 1;
|
|
542
|
+
return shared / (a.size + b.size - shared);
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
function editDistance(a, b) {
|
|
546
|
+
const rows = a.length + 1;
|
|
547
|
+
const cols = b.length + 1;
|
|
548
|
+
let previous = new Array(cols);
|
|
549
|
+
let current = new Array(cols);
|
|
550
|
+
for (let j = 0; j < cols; j += 1) previous[j] = j;
|
|
551
|
+
for (let i = 1; i < rows; i += 1) {
|
|
552
|
+
current[0] = i;
|
|
553
|
+
for (let j = 1; j < cols; j += 1) {
|
|
554
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
555
|
+
current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + cost);
|
|
556
|
+
}
|
|
557
|
+
const swap = previous;
|
|
558
|
+
previous = current;
|
|
559
|
+
current = swap;
|
|
560
|
+
}
|
|
561
|
+
return previous[cols - 1];
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
function similarityOfKeys(a, b, gram) {
|
|
565
|
+
const longest = Math.max(a.length, b.length);
|
|
566
|
+
const edit = longest === 0 ? 1 : 1 - editDistance(a, b) / longest;
|
|
567
|
+
return { similarity: Math.max(gram, edit), gram, edit };
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
function segmentsOf(summary) {
|
|
571
|
+
return normalizeText(summary)
|
|
572
|
+
.split(/[。;;\n]+/)
|
|
573
|
+
.map((part) => part.trim())
|
|
574
|
+
.filter((part) => part.length > 0);
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
function cardFingerprint(cards) {
|
|
578
|
+
let hash = 2166136261;
|
|
579
|
+
for (const card of cards) {
|
|
580
|
+
const cardId = card && typeof card === 'object' ? String(card.cardId ?? card.id ?? '') : '';
|
|
581
|
+
const summary = card && typeof card === 'object' ? String(card.summary ?? card.text ?? '') : '';
|
|
582
|
+
for (const value of [cardId, '\u0001', summary, '\u0002']) {
|
|
583
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
584
|
+
hash ^= value.charCodeAt(i);
|
|
585
|
+
hash = Math.imul(hash, 16777619);
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
return `${cards.length}:${(hash >>> 0).toString(36)}`;
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
function buildCardProfile(card) {
|
|
593
|
+
if (!card || typeof card !== 'object') return null;
|
|
594
|
+
const summary = normalizeText(String(card.summary ?? card.text ?? ''));
|
|
595
|
+
if (!summary) return null;
|
|
596
|
+
const candidates = [];
|
|
597
|
+
const seen = new Set();
|
|
598
|
+
for (const text of [summary, ...segmentsOf(summary).slice(0, THRESHOLDS.maxCardSegments)]) {
|
|
599
|
+
if (!text || seen.has(text)) continue;
|
|
600
|
+
seen.add(text);
|
|
601
|
+
const key = compareKey(text);
|
|
602
|
+
if (!key) continue;
|
|
603
|
+
candidates.push({ text, key, length: key.length, grams: trigrams(key) });
|
|
604
|
+
}
|
|
605
|
+
if (candidates.length === 0) return null;
|
|
606
|
+
return {
|
|
607
|
+
cardId: String(card.cardId ?? card.id ?? '(unknown)'),
|
|
608
|
+
cardText: summary,
|
|
609
|
+
candidates,
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
// The cache is keyed by array identity and guarded by a content fingerprint, so
|
|
614
|
+
// mutating the array cannot serve a stale profile. Output is unaffected.
|
|
615
|
+
const CARD_PROFILE_CACHE = new WeakMap();
|
|
616
|
+
|
|
617
|
+
function cardProfilesOf(cards) {
|
|
618
|
+
const fingerprint = cardFingerprint(cards);
|
|
619
|
+
const cached = CARD_PROFILE_CACHE.get(cards);
|
|
620
|
+
if (cached && cached.fingerprint === fingerprint) return cached.profiles;
|
|
621
|
+
const profiles = [];
|
|
622
|
+
for (const card of cards) {
|
|
623
|
+
const profile = buildCardProfile(card);
|
|
624
|
+
if (profile) profiles.push(profile);
|
|
625
|
+
}
|
|
626
|
+
CARD_PROFILE_CACHE.set(cards, { fingerprint, profiles });
|
|
627
|
+
return profiles;
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
function nearestCard(probe, probeGrams, profiles) {
|
|
631
|
+
const ranked = [];
|
|
632
|
+
for (const profile of profiles) {
|
|
633
|
+
for (const candidate of profile.candidates) {
|
|
634
|
+
const longest = Math.max(probe.length, candidate.length);
|
|
635
|
+
if (longest === 0) continue;
|
|
636
|
+
const lengthBound = 1 - Math.abs(probe.length - candidate.length) / longest;
|
|
637
|
+
if (lengthBound < THRESHOLDS.dedupeLengthFloor) continue;
|
|
638
|
+
const gram = jaccard(probeGrams, candidate.grams);
|
|
639
|
+
ranked.push({ profile, candidate, gram, lengthBound, order: ranked.length });
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
ranked.sort((a, b) => b.gram - a.gram || b.lengthBound - a.lengthBound || a.order - b.order);
|
|
643
|
+
|
|
644
|
+
let best = { similarity: 0, gram: 0, edit: null, cardId: null, cardText: '', segment: '' };
|
|
645
|
+
for (const item of ranked.slice(0, THRESHOLDS.dedupeShortlist)) {
|
|
646
|
+
// The gram score already settles the decision outside this band; edit is
|
|
647
|
+
// only the tie-breaker that can lift a paraphrase past dedupeHigh.
|
|
648
|
+
const metrics =
|
|
649
|
+
item.gram >= THRESHOLDS.dedupeHigh || item.gram < THRESHOLDS.dedupeEditFloor
|
|
650
|
+
? { similarity: item.gram, gram: item.gram, edit: null }
|
|
651
|
+
: similarityOfKeys(probe, item.candidate.key, item.gram);
|
|
652
|
+
if (metrics.similarity > best.similarity) {
|
|
653
|
+
best = {
|
|
654
|
+
...metrics,
|
|
655
|
+
cardId: item.profile.cardId,
|
|
656
|
+
cardText: item.profile.cardText,
|
|
657
|
+
segment: item.candidate.text,
|
|
658
|
+
};
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
return best;
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
const NEW_INFO_PATTERNS = [
|
|
665
|
+
/`[^`]{3,60}`/g,
|
|
666
|
+
/\b[A-Z][A-Z0-9_]{3,}\b/g,
|
|
667
|
+
/\b\d+\.\d+\.\d+(?:-[A-Za-z0-9.]+)?\b/g,
|
|
668
|
+
/\b\d[\d,.]*\s?(?:B|KB|MB|GB|TB)\b/g,
|
|
669
|
+
/(?:端口|exit\s*code)\s*\d+/gi,
|
|
670
|
+
/\b\d{2,}\b/g,
|
|
671
|
+
];
|
|
672
|
+
|
|
673
|
+
function newInfoOf(text, cardText) {
|
|
674
|
+
const known = compareKey(cardText);
|
|
675
|
+
const items = [];
|
|
676
|
+
const seen = new Set();
|
|
677
|
+
for (const pattern of NEW_INFO_PATTERNS) {
|
|
678
|
+
for (const match of text.matchAll(new RegExp(pattern.source, `${pattern.flags.replace('g', '')}g`))) {
|
|
679
|
+
const raw = match[0].replace(/`/g, '');
|
|
680
|
+
const key = compareKey(raw);
|
|
681
|
+
if (!key || seen.has(key)) continue;
|
|
682
|
+
if (known.includes(key)) continue;
|
|
683
|
+
seen.add(key);
|
|
684
|
+
items.push(raw);
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
return items;
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
// A one-word polarity flip (必须 -> 不必 / 不要) can score 0.92 similarity while
|
|
691
|
+
// meaning the opposite. High similarity is not enough for duplicate then.
|
|
692
|
+
const POSITIVE_REQ = /(必须|一定要|务必|需要|应当|应该)/;
|
|
693
|
+
const NEGATED_REQ = /(不必|不用|不需要|无需|没必要|不一定要|别|不要|不得|不能|禁止)/;
|
|
694
|
+
|
|
695
|
+
function polarityFlip(text, cardText) {
|
|
696
|
+
const unitPositive = POSITIVE_REQ.test(text);
|
|
697
|
+
const cardPositive = POSITIVE_REQ.test(cardText);
|
|
698
|
+
const unitNegative = NEGATED_REQ.test(text);
|
|
699
|
+
const cardNegative = NEGATED_REQ.test(cardText);
|
|
700
|
+
if (unitPositive && cardNegative && !cardPositive) return true;
|
|
701
|
+
if (cardPositive && unitNegative && !unitPositive) return true;
|
|
702
|
+
return false;
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
function scoreR6(text, cards, r5Score) {
|
|
706
|
+
if (!Array.isArray(cards)) {
|
|
707
|
+
return {
|
|
708
|
+
...zeroDim('R6', 'R6 跳过:未提供 existingCards 上下文,去重状态未知'),
|
|
709
|
+
skipped: true,
|
|
710
|
+
dedupe: { verdict: 'skipped', similarity: null, nearestCardId: null, newInfo: [], mustKeepOld: false },
|
|
711
|
+
};
|
|
712
|
+
}
|
|
713
|
+
if (cards.length === 0) {
|
|
714
|
+
return {
|
|
715
|
+
...zeroDim('R6', 'R6 跳过:existingCards 为空,尚无卡可对比'),
|
|
716
|
+
skipped: true,
|
|
717
|
+
dedupe: { verdict: 'skipped', similarity: null, nearestCardId: null, newInfo: [], mustKeepOld: false },
|
|
718
|
+
};
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
const probe = compareKey(text);
|
|
722
|
+
const best = nearestCard(probe, trigrams(probe), cardProfilesOf(cards));
|
|
723
|
+
|
|
724
|
+
const round = (value) => Math.round(value * 1000) / 1000;
|
|
725
|
+
const similarity = round(best.similarity);
|
|
726
|
+
const newInfo = newInfoOf(text, best.cardText);
|
|
727
|
+
const flipped = best.cardId ? polarityFlip(text, best.cardText) : false;
|
|
728
|
+
const dedupe = {
|
|
729
|
+
verdict: 'new',
|
|
730
|
+
similarity,
|
|
731
|
+
nearestCardId: best.cardId,
|
|
732
|
+
newInfo,
|
|
733
|
+
gram: round(best.gram),
|
|
734
|
+
edit: round(best.edit),
|
|
735
|
+
mustKeepOld: false,
|
|
736
|
+
};
|
|
737
|
+
|
|
738
|
+
// DESIGN.md:159 — a R5=2 retraction/correction must be judged BEFORE
|
|
739
|
+
// duplicate, otherwise the revise exception is unreachable (maf-1 bug).
|
|
740
|
+
if (best.cardId && similarity >= THRESHOLDS.dedupeRevise && r5Score === 2) {
|
|
741
|
+
dedupe.verdict = 'revise';
|
|
742
|
+
dedupe.mustKeepOld = true;
|
|
743
|
+
return {
|
|
744
|
+
...zeroDim('R6', `R6 0:与「${best.cardId}」相近且本条是撤回/改向(R5=2),走 revise,旧卡必须保留(mustKeepOld)`),
|
|
745
|
+
skipped: false,
|
|
746
|
+
dedupe,
|
|
747
|
+
};
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
if (similarity >= THRESHOLDS.dedupeHigh && newInfo.length === 0 && !flipped) {
|
|
751
|
+
dedupe.verdict = 'duplicate';
|
|
752
|
+
return {
|
|
753
|
+
...dim(
|
|
754
|
+
'R6',
|
|
755
|
+
-3,
|
|
756
|
+
`R6 −3:与「${best.cardId}」重复(相似度 ${similarity},3-gram ${round(best.gram)} / edit ${best.edit === null ? '跳过' : round(best.edit)}),且无新增数字/命令/反例`,
|
|
757
|
+
null,
|
|
758
|
+
),
|
|
759
|
+
skipped: false,
|
|
760
|
+
dedupe,
|
|
761
|
+
};
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
// Negation/antonym guard: same words, opposite meaning is a correction, not
|
|
765
|
+
// a duplicate; never silently archive it.
|
|
766
|
+
if (similarity >= THRESHOLDS.dedupeHigh && newInfo.length === 0 && flipped) {
|
|
767
|
+
dedupe.verdict = 'revise';
|
|
768
|
+
dedupe.mustKeepOld = true;
|
|
769
|
+
return {
|
|
770
|
+
...zeroDim('R6', `R6 0:与「${best.cardId}」高度重合但否定/极性相反,按 revise 处理(旧卡必须保留)`),
|
|
771
|
+
skipped: false,
|
|
772
|
+
dedupe,
|
|
773
|
+
};
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
if (similarity >= THRESHOLDS.dedupeMid && newInfo.length > 0) {
|
|
777
|
+
dedupe.verdict = 'increment';
|
|
778
|
+
return {
|
|
779
|
+
...dim('R6', 1, `R6 +1:与「${best.cardId}」同主题但有新增信息(${newInfo.length} 项),按复现计数处理`, null),
|
|
780
|
+
skipped: false,
|
|
781
|
+
dedupe,
|
|
782
|
+
};
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
return {
|
|
786
|
+
...zeroDim('R6', `R6 0:最近卡「${best.cardId ?? '无'}」相似度 ${similarity} < ${THRESHOLDS.dedupeMid},按新条目处理`),
|
|
787
|
+
skipped: false,
|
|
788
|
+
dedupe,
|
|
789
|
+
};
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
// ---------------------------------------------------------------------------
|
|
793
|
+
// R7 — relationship / identity
|
|
794
|
+
//
|
|
795
|
+
// maf-2: no closed name list. The design asks for "a concrete person", so any
|
|
796
|
+
// first/third-person subject plus an identity anchor + date qualifies; a name
|
|
797
|
+
// swap must not change the verdict.
|
|
798
|
+
// ---------------------------------------------------------------------------
|
|
799
|
+
|
|
800
|
+
const R7 = {
|
|
801
|
+
person: /(我|他|她|你)/,
|
|
802
|
+
first: /(第一次|头一次|初次)/,
|
|
803
|
+
farewell: /(交接|告别|离开|走了|失去|最后一次)/,
|
|
804
|
+
nameOrigin: /(得名|取名|叫我|称呼我|被叫|小名)/,
|
|
805
|
+
relation: /(伙伴|约定|承诺|信任|答应|跟我说|叫我)/,
|
|
806
|
+
date: /(20\d{2}-\d{2}-\d{2}|\d{1,2}月\d{1,2}日)/,
|
|
807
|
+
};
|
|
808
|
+
|
|
809
|
+
function scoreR7(text, raw) {
|
|
810
|
+
if (!R7.person.test(text)) return zeroDim('R7', 'R7 0:没有具体的人');
|
|
811
|
+
const anchor = firstHit(text, R7.first) ?? firstHit(text, R7.farewell) ?? firstHit(text, R7.nameOrigin);
|
|
812
|
+
if (anchor && R7.date.test(text)) {
|
|
813
|
+
return dim('R7', 4, '身份级关系事件(首次/告别/得名)且有日期锚点', quoteOf(raw, anchor));
|
|
814
|
+
}
|
|
815
|
+
const relation = firstHit(text, R7.relation);
|
|
816
|
+
if (relation) return dim('R7', 2, '关系信号,但不是不可复制的身份锚点', quoteOf(raw, relation));
|
|
817
|
+
return zeroDim('R7', 'R7 0:只是提到人,没有关系事件');
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
// ---------------------------------------------------------------------------
|
|
821
|
+
// R2 — reuse span (depends on R8: an artifact that already carries the
|
|
822
|
+
// knowledge makes "remember this" pointless no matter how reusable it looks)
|
|
823
|
+
// ---------------------------------------------------------------------------
|
|
824
|
+
|
|
825
|
+
const R2 = {
|
|
826
|
+
reuse: /(以后|下次|每次|再|一律|凡是|同类|正确做法|解决是|会报|会超时|必须|一定|记得)/,
|
|
827
|
+
// maf-2: no hard-coded person names; backticked paths and Latin identifiers
|
|
828
|
+
// are the general "named object" signal.
|
|
829
|
+
named: /(`[^`]{3,}`|[A-Za-z][A-Za-z0-9_.-]{2,})/,
|
|
830
|
+
};
|
|
831
|
+
|
|
832
|
+
function scoreR2(text, r8Score, raw, r5Score) {
|
|
833
|
+
if (r8Score === -3) {
|
|
834
|
+
if (R1.cause.test(text) && R1.fix.test(text)) {
|
|
835
|
+
return dim('R2', 1, '坑+修法可复用,但产物已承载,复述价值有限', quoteOf(raw, firstHit(text, R1.fix)));
|
|
836
|
+
}
|
|
837
|
+
return zeroDim('R2', 'R2 0:知识已被产物承载,没有跨会话复用价值');
|
|
838
|
+
}
|
|
839
|
+
if (r5Score === 2) {
|
|
840
|
+
return dim('R2', 2, '决策本身就是跨会话约束,下次照此执行', quoteOf(raw, firstHit(text, R5.strong)));
|
|
841
|
+
}
|
|
842
|
+
const scale = firstHit(text, R1.scale);
|
|
843
|
+
if (scale) return dim('R2', 2, '规模/目标跨会话规划仍要用', quoteOf(raw, scale));
|
|
844
|
+
const reuse = firstHit(text, R2.reuse);
|
|
845
|
+
if (reuse) return dim('R2', 2, '跨会话复用(下次同类场景可照做)', quoteOf(raw, reuse));
|
|
846
|
+
const named = firstHit(text, R2.named);
|
|
847
|
+
if (named) return dim('R2', 1, '提到的对象可复用,但结论只对本次成立', quoteOf(raw, named));
|
|
848
|
+
return dim('R2', 1, '经验本身可带走,但复用面窄', quoteOf(raw, firstHit(text, R1.date)));
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
// ---------------------------------------------------------------------------
|
|
852
|
+
// decision
|
|
853
|
+
// ---------------------------------------------------------------------------
|
|
854
|
+
|
|
855
|
+
function decisionOf(scores) {
|
|
856
|
+
const total = ALL_DIMS.reduce((sum, id) => sum + scores[id], 0);
|
|
857
|
+
if (scores.R6 <= -3) {
|
|
858
|
+
return { target: 'archive_only', band: 'reject', why: 'R6=−3:去重短路,重复段不升层' };
|
|
859
|
+
}
|
|
860
|
+
if (total <= THRESHOLDS.archiveMax) {
|
|
861
|
+
return { target: 'archive_only', band: 'reject', why: `S=${total} ≤ ${THRESHOLDS.archiveMax}:只配留在 journal` };
|
|
862
|
+
}
|
|
863
|
+
// DESIGN.md:191 — R1=2 plus ANY one of R2..R5=2 is enough (maf-1 required two,
|
|
864
|
+
// an undisclosed deviation; maf-2 restores the documented OR).
|
|
865
|
+
const hard =
|
|
866
|
+
scores.R7 >= 2 ||
|
|
867
|
+
(scores.R1 === 2 && [scores.R2, scores.R3, scores.R4, scores.R5].some((value) => value === 2));
|
|
868
|
+
if (total >= THRESHOLDS.remember && hard) {
|
|
869
|
+
return { target: 'remember', band: 'remember', why: `S=${total} ≥ ${THRESHOLDS.remember} 且硬信号成立:进入 consolidate 候选` };
|
|
870
|
+
}
|
|
871
|
+
if (total >= THRESHOLDS.remember && !hard) {
|
|
872
|
+
return { target: 'human', band: 'hold', why: `S=${total} ≥ ${THRESHOLDS.remember} 但硬信号不足:交人判` };
|
|
873
|
+
}
|
|
874
|
+
return { target: 'human', band: 'hold', why: `S=${total} 落在 ${THRESHOLDS.archiveMax + 1}–${THRESHOLDS.remember - 1} 中间带:交人判` };
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
const SKIPPED_DEDUPE = () => ({
|
|
878
|
+
verdict: 'skipped',
|
|
879
|
+
similarity: null,
|
|
880
|
+
nearestCardId: null,
|
|
881
|
+
newInfo: [],
|
|
882
|
+
mustKeepOld: false,
|
|
883
|
+
});
|
|
884
|
+
|
|
885
|
+
/**
|
|
886
|
+
* Classify one journal paragraph for memory admission.
|
|
887
|
+
*
|
|
888
|
+
* @param {unknown} entryText journal paragraph (one unit, not a whole file)
|
|
889
|
+
* @param {{existingCards?: Array<{cardId?: string, id?: string, summary?: string, text?: string}>, artifacts?: Array<{kind?: string, path?: string, name?: string}>}} [context]
|
|
890
|
+
* `existingCards` enables R6 dedupe, `artifacts` enables R8 artifact
|
|
891
|
+
* corroboration. Without them those dimensions are skipped and reported.
|
|
892
|
+
* @returns {{target: string, score: number, dims: Array<{id: string, score: number, min: number, max: number, why: string, quote: string|null}>, needsHuman: boolean, privacy: {verdict: string, reasons: string[]}, reasons: string[], policyVersion: string, band: string, dedupe: object}}
|
|
893
|
+
*/
|
|
894
|
+
export function classifyEntry(entryText, context = {}) {
|
|
895
|
+
const reasons = [];
|
|
896
|
+
const zeroDims = () => ALL_DIMS.map((id) => zeroDim(id, 'V1/输入异常短路:未评分'));
|
|
897
|
+
// `excerpt` is always null: the filter never hands the matched value (or any
|
|
898
|
+
// prefix of an oversize paragraph) back to the caller. Exact anchors live in
|
|
899
|
+
// dims[].quote and are produced only for non-privacy decisions.
|
|
900
|
+
const blockedResult = (why) => ({
|
|
901
|
+
target: 'human',
|
|
902
|
+
score: 0,
|
|
903
|
+
dims: zeroDims(),
|
|
904
|
+
needsHuman: true,
|
|
905
|
+
privacy: { verdict: 'none', reasons: [] },
|
|
906
|
+
reasons: [why],
|
|
907
|
+
policyVersion: POLICY_VERSION,
|
|
908
|
+
band: 'hold',
|
|
909
|
+
dedupe: SKIPPED_DEDUPE(),
|
|
910
|
+
excerpt: null,
|
|
911
|
+
});
|
|
912
|
+
|
|
913
|
+
try {
|
|
914
|
+
if (typeof entryText !== 'string') return blockedResult('输入不是字符串:按失败关闭交人');
|
|
915
|
+
if (typeof context !== 'object' || context === null) return blockedResult('context 不是对象:按失败关闭交人');
|
|
916
|
+
|
|
917
|
+
const raw = entryText;
|
|
918
|
+
const text = normalizeText(entryText);
|
|
919
|
+
if (text.length === 0) return blockedResult('空文本:按失败关闭交人');
|
|
920
|
+
|
|
921
|
+
// V1 first: privacy never scores and never echoes. It runs before the
|
|
922
|
+
// short-text rule as well — a 14-char paragraph containing a phone number
|
|
923
|
+
// is still a secret, and DESIGN.md:59 only says short text is not *scored*
|
|
924
|
+
// on its own, not that it is exempt from the privacy gate. Privacy also
|
|
925
|
+
// stays ahead of the length gate so an oversize paragraph with a secret
|
|
926
|
+
// cannot fall through to the human queue.
|
|
927
|
+
const privacy = privacyGate(text);
|
|
928
|
+
if (privacy.blocked) {
|
|
929
|
+
return {
|
|
930
|
+
target: 'local_only',
|
|
931
|
+
score: 0,
|
|
932
|
+
dims: zeroDims(),
|
|
933
|
+
needsHuman: false,
|
|
934
|
+
privacy: { verdict: privacy.verdict, reasons: privacy.reasons },
|
|
935
|
+
reasons: [
|
|
936
|
+
`V1 隐私门:命中 ${privacy.reasons.join('、')} → local_only(excerpt 不回显,不写 journal,不进模型上下文)`,
|
|
937
|
+
],
|
|
938
|
+
policyVersion: POLICY_VERSION,
|
|
939
|
+
band: 'blocked',
|
|
940
|
+
dedupe: SKIPPED_DEDUPE(),
|
|
941
|
+
excerpt: null,
|
|
942
|
+
};
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
if (text.length < THRESHOLDS.shortText) {
|
|
946
|
+
return blockedResult(`文本 ${text.length} 字 < ${THRESHOLDS.shortText}:按设计不单独判定,挂到父段并交人`);
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
// Length gate: oversize input is never scored. No quote is produced, so no
|
|
950
|
+
// prefix of the paragraph can leak into a review queue.
|
|
951
|
+
const bytes = utf8Length(entryText);
|
|
952
|
+
if (text.length > THRESHOLDS.maxChars || bytes > THRESHOLDS.maxBytes) {
|
|
953
|
+
return {
|
|
954
|
+
target: 'human',
|
|
955
|
+
score: 0,
|
|
956
|
+
dims: zeroDims(),
|
|
957
|
+
needsHuman: true,
|
|
958
|
+
privacy: { verdict: 'none', reasons: [] },
|
|
959
|
+
reasons: [
|
|
960
|
+
`超长输入(${text.length} 字 / ${bytes} B > 上限 ${THRESHOLDS.maxChars} 字 / ${THRESHOLDS.maxBytes} B):不评分,按失败关闭交人`,
|
|
961
|
+
],
|
|
962
|
+
policyVersion: POLICY_VERSION,
|
|
963
|
+
band: 'hold',
|
|
964
|
+
dedupe: SKIPPED_DEDUPE(),
|
|
965
|
+
oversize: true,
|
|
966
|
+
excerpt: null,
|
|
967
|
+
};
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
const dims = [];
|
|
971
|
+
dims.push(scoreR1(text, raw));
|
|
972
|
+
const r7 = scoreR7(text, raw);
|
|
973
|
+
const r8 = scoreR8(text, context.artifacts, r7.score, raw);
|
|
974
|
+
const r5 = scoreR5(text, raw);
|
|
975
|
+
dims.push(scoreR2(text, r8.score, raw, r5.score));
|
|
976
|
+
dims.push(scoreR3(text, raw));
|
|
977
|
+
dims.push(scoreR4(text, raw));
|
|
978
|
+
dims.push(r5);
|
|
979
|
+
const r6 = scoreR6(text, context.existingCards, r5.score);
|
|
980
|
+
dims.push(r6);
|
|
981
|
+
dims.push(r7);
|
|
982
|
+
dims.push(r8);
|
|
983
|
+
|
|
984
|
+
const ordered = ALL_DIMS.map((id) => dims.find((entry) => entry.id === id));
|
|
985
|
+
const scores = Object.fromEntries(ordered.map((entry) => [entry.id, entry.score]));
|
|
986
|
+
const decision = decisionOf(scores);
|
|
987
|
+
let target = decision.target;
|
|
988
|
+
reasons.push(decision.why);
|
|
989
|
+
|
|
990
|
+
// Fail closed on missing context: dedupe/artifact state unknown must never
|
|
991
|
+
// silently produce `remember`.
|
|
992
|
+
const missing = [];
|
|
993
|
+
if (r6.skipped) missing.push('existingCards');
|
|
994
|
+
if (r8.skipped) missing.push('artifacts');
|
|
995
|
+
if (missing.length > 0) {
|
|
996
|
+
reasons.push(`上下文缺失:${missing.join('、')}(对应维度已跳过)`);
|
|
997
|
+
if (target === 'remember') {
|
|
998
|
+
target = 'human';
|
|
999
|
+
reasons.push('按失败关闭降级:去重/产物状态未知时不许静默 remember,改交人');
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
if (target === 'local_only') {
|
|
1004
|
+
return {
|
|
1005
|
+
target,
|
|
1006
|
+
score: 0,
|
|
1007
|
+
dims: ordered,
|
|
1008
|
+
needsHuman: false,
|
|
1009
|
+
privacy: { verdict: privacy.verdict, reasons: privacy.reasons },
|
|
1010
|
+
reasons,
|
|
1011
|
+
policyVersion: POLICY_VERSION,
|
|
1012
|
+
band: 'blocked',
|
|
1013
|
+
dedupe: r6.dedupe,
|
|
1014
|
+
excerpt: null,
|
|
1015
|
+
};
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
return {
|
|
1019
|
+
target,
|
|
1020
|
+
score: ordered.reduce((sum, entry) => sum + entry.score, 0),
|
|
1021
|
+
dims: ordered,
|
|
1022
|
+
needsHuman: target === 'human',
|
|
1023
|
+
privacy: { verdict: 'none', reasons: [] },
|
|
1024
|
+
reasons,
|
|
1025
|
+
policyVersion: POLICY_VERSION,
|
|
1026
|
+
band: decision.band,
|
|
1027
|
+
dedupe: r6.dedupe,
|
|
1028
|
+
excerpt: null,
|
|
1029
|
+
};
|
|
1030
|
+
} catch (error) {
|
|
1031
|
+
return blockedResult(`过滤器内部异常,按失败关闭交人:${error instanceof Error ? error.message : String(error)}`);
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
export default classifyEntry;
|