@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,1060 @@
|
|
|
1
|
+
// src/memory/conflicts.js — 1.8.0 / v2.8 §15.1-A2/A4:冲突检测唯一实现(避免两套真相)
|
|
2
|
+
//
|
|
3
|
+
// 目标:Claim(治理层)与 records(v2.6.4 遗留)共用同一套互斥判定,
|
|
4
|
+
// 以 cards.js 的极性词表为唯一词源;输出 conflicts[]{idA,idB,subject,why,source}。
|
|
5
|
+
// - subject 归一:entity(+attribute)小写、去空白;同 subject 才可能互斥;
|
|
6
|
+
// - 互斥:正反极性(cards.isNegativeConclusion 取反)或同 attribute 不同 value;
|
|
7
|
+
// - supersedes/supersededBy 链内不判冲突;非 active/verified 状态不参与;
|
|
8
|
+
// - 有 claims 时以 claims 为准(旧 records 是迁移来源),避免同一事实重复计数。
|
|
9
|
+
|
|
10
|
+
import crypto from 'node:crypto';
|
|
11
|
+
import fs from 'node:fs';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
|
|
14
|
+
import { readClaims } from './governance.js';
|
|
15
|
+
import { readCardLifecycle, readLifecycle } from './lifecycle.js';
|
|
16
|
+
import { detectRecordConflicts, listRecords } from './records.js';
|
|
17
|
+
import { appendGateLog } from '../recall/gate-log.mjs';
|
|
18
|
+
import { loadEdges, normalizeEvidence } from '../recall/edges.js';
|
|
19
|
+
|
|
20
|
+
export function conflictKeyOf(claimA, claimB) {
|
|
21
|
+
return [String(claimA), String(claimB)].sort().join('|');
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function conflictIdOf(claimA, claimB) {
|
|
25
|
+
const key = conflictKeyOf(claimA, claimB);
|
|
26
|
+
return `cfl_${crypto.createHash('sha1').update(key, 'utf8').digest('hex').slice(0, 12)}`;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function conflictStatePathOf(memoryRoot) {
|
|
30
|
+
return path.join(path.resolve(String(memoryRoot)), '.longlive', 'conflicts', 'state.json');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Persistent arbitration state (CAS version source for conflict.arbitrate). */
|
|
34
|
+
export function readConflictState({ memoryRoot }) {
|
|
35
|
+
try {
|
|
36
|
+
const value = JSON.parse(fs.readFileSync(conflictStatePathOf(memoryRoot), 'utf8'));
|
|
37
|
+
return {
|
|
38
|
+
version: Number.isInteger(value?.version) ? value.version : 0,
|
|
39
|
+
items: value?.items && typeof value.items === 'object' ? value.items : {},
|
|
40
|
+
};
|
|
41
|
+
} catch {
|
|
42
|
+
return { version: 0, items: {} };
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function resolutionState(item) {
|
|
47
|
+
if (!item || typeof item.resolution !== 'string') return 'open';
|
|
48
|
+
if (item.resolution === 'disputed') return 'disputed';
|
|
49
|
+
if (item.resolution === 'both') return 'both';
|
|
50
|
+
return 'resolved';
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export const CONFLICT_SCHEMA = 'conflicts/v1';
|
|
54
|
+
|
|
55
|
+
function normalizeSubjectPart(value) {
|
|
56
|
+
return String(value ?? '').toLowerCase().replace(/[\s\u3000]+/g, '');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Detect conflicts via the SINGLE implementation in records.js (EA-03: one source of truth).
|
|
61
|
+
* Entries may be claims (subject object) or legacy records (subject string).
|
|
62
|
+
*/
|
|
63
|
+
export function detectConflicts(entries) {
|
|
64
|
+
const list = Array.isArray(entries) ? entries : [];
|
|
65
|
+
const { conflicts, byId } = detectRecordConflicts(list);
|
|
66
|
+
return {
|
|
67
|
+
conflicts: conflicts.map((conflict) => ({ ...conflict, source: (list.find((entry) => entry.id === conflict.idA) ?? {}).source ?? null })),
|
|
68
|
+
byId,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* 1.8.11 D6/E6 接线:conflicts_with 边的唯一读取点。
|
|
74
|
+
* 边表本体归 src/recall/edges.js(recall-edges/v1),这里只把「边 × 卡 lifecycle」接起来,
|
|
75
|
+
* 不另建第二套冲突判定/权威分;edges 可传 loadEdges() 结果或裸数组(测试/调用方注入)。
|
|
76
|
+
*/
|
|
77
|
+
export const LIFECYCLE_CONFLICT_SCHEMA = 'conflicts-lifecycle/v1';
|
|
78
|
+
|
|
79
|
+
export function lifecycleConflicts({ memoryRoot, edges = null } = {}) {
|
|
80
|
+
let list = [];
|
|
81
|
+
let source = 'recall-edges/v1';
|
|
82
|
+
if (Array.isArray(edges)) {
|
|
83
|
+
list = edges;
|
|
84
|
+
} else if (edges && Array.isArray(edges.edges)) {
|
|
85
|
+
list = edges.edges;
|
|
86
|
+
if (typeof edges.schema === 'string') source = edges.schema;
|
|
87
|
+
} else if (memoryRoot) {
|
|
88
|
+
const store = loadEdges({ memoryRoot });
|
|
89
|
+
list = Array.isArray(store?.edges) ? store.edges : [];
|
|
90
|
+
if (typeof store?.schema === 'string') source = store.schema;
|
|
91
|
+
}
|
|
92
|
+
const conflicts = [];
|
|
93
|
+
for (const edge of list) {
|
|
94
|
+
if (!edge || edge.type !== 'conflicts_with') continue;
|
|
95
|
+
if (typeof edge.from !== 'string' || typeof edge.to !== 'string') continue;
|
|
96
|
+
conflicts.push({
|
|
97
|
+
...edge,
|
|
98
|
+
conflictId: conflictIdOf(edge.from, edge.to),
|
|
99
|
+
lifecycle: {
|
|
100
|
+
from: readCardLifecycle(edge.from, { memoryRoot }),
|
|
101
|
+
to: readCardLifecycle(edge.to, { memoryRoot }),
|
|
102
|
+
},
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
return { schema: LIFECYCLE_CONFLICT_SCHEMA, source, conflicts, total: conflicts.length };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Unified view: claims preferred; legacy records only when no claims exist.
|
|
110
|
+
* Every entry gets conflict/conflict_with flags computed here (one source of truth).
|
|
111
|
+
* includeLifecycle=true 时额外带 `lifecycle` 视图(默认输出保持字节兼容)。
|
|
112
|
+
*/
|
|
113
|
+
export function unifiedConflicts({ memoryRoot, includeLifecycle = false } = {}) {
|
|
114
|
+
const claims = readClaims({ memoryRoot, actor: { kind: 'host' } }).items.map((claim) => ({ ...claim, source: 'claim' }));
|
|
115
|
+
let pool = claims;
|
|
116
|
+
if (pool.length === 0) {
|
|
117
|
+
pool = listRecords({ memoryRoot }).items.map((record) => ({
|
|
118
|
+
...record,
|
|
119
|
+
source: 'record',
|
|
120
|
+
subject: record.subject ?? null,
|
|
121
|
+
}));
|
|
122
|
+
}
|
|
123
|
+
const { conflicts: rawConflicts, byId } = detectConflicts(pool);
|
|
124
|
+
const conflictState = readConflictState({ memoryRoot });
|
|
125
|
+
const conflicts = rawConflicts.map((conflict) => {
|
|
126
|
+
const key = conflictKeyOf(conflict.idA, conflict.idB);
|
|
127
|
+
const item = conflictState.items[key] ?? null;
|
|
128
|
+
return {
|
|
129
|
+
...conflict,
|
|
130
|
+
conflictId: conflictIdOf(conflict.idA, conflict.idB),
|
|
131
|
+
state: resolutionState(item),
|
|
132
|
+
version: item && Number.isInteger(item.version) ? item.version : 0,
|
|
133
|
+
};
|
|
134
|
+
});
|
|
135
|
+
const marked = pool.map((entry) => {
|
|
136
|
+
const ids = byId.get(entry.id) ?? [];
|
|
137
|
+
return { ...entry, conflict: ids.length > 0, conflict_with: ids };
|
|
138
|
+
});
|
|
139
|
+
const out = {
|
|
140
|
+
schema: CONFLICT_SCHEMA,
|
|
141
|
+
source: claims.length > 0 ? 'claim' : 'record',
|
|
142
|
+
entries: marked,
|
|
143
|
+
conflicts,
|
|
144
|
+
total: conflicts.length,
|
|
145
|
+
};
|
|
146
|
+
if (includeLifecycle === true) out.lifecycle = lifecycleConflicts({ memoryRoot });
|
|
147
|
+
return out;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// ---------------------------------------------------------------------------
|
|
151
|
+
// 2.0.0 / D14(批 E · M30):冲突候选扫描 + appendConflictEdge + memory_conflicts action
|
|
152
|
+
//
|
|
153
|
+
// 契约(V0.5.2-MERGE-PLAN v3.6.4 §4③ / §14 D14):
|
|
154
|
+
// - 候选口径(对/边两口径分列,全部来自同一遍扫描):
|
|
155
|
+
// same_topic 边 conf >= sameTopicConf(0.5)
|
|
156
|
+
// ∧ 两端都在 topics/(scopePrefix)
|
|
157
|
+
// ∧ 两端都不是 historical(lifecycle 缺失 = 普通卡,参与)
|
|
158
|
+
// ∧ links.jsonl 共享主题词 >= minSharedTerms(2)
|
|
159
|
+
// ∧ 该卡对尚无 conflicts_with 边
|
|
160
|
+
// ∧ 结论行/frontmatter 不是完全同文(同文是重复而非冲突)
|
|
161
|
+
// → 只产候选,不改卡、不合并、不写 history。上限 maxPairs(32) 对。
|
|
162
|
+
// - 候选落盘:`.longlive/hardgate/conflict-candidates.jsonl`(append-only;
|
|
163
|
+
// pending <= maxPending(200) 且 90 天保留;卡对去重;archived 行只移出队列不删历史)。
|
|
164
|
+
// - accept:appendConflictEdge 校验双卡存在 + type 白名单 + 幂等去重;向
|
|
165
|
+
// `.longlive/recall/edges.jsonl` append 恰 1 条边;向 `.longlive/hardgate/auto-authz.jsonl`
|
|
166
|
+
// append 恰 1 行 kind=conflict-accept 审计;返回 {ok,edge,auditPath}。
|
|
167
|
+
// 错误码 E_HG_EDGE_INVALID / E_HG_EDGE_DUP(失败同时写 hg.d14.fail 事件)。
|
|
168
|
+
// - 消费者:面板候选队列 + memory_conflicts(list/accept/reject)。
|
|
169
|
+
// ---------------------------------------------------------------------------
|
|
170
|
+
|
|
171
|
+
export const CONFLICT_CANDIDATE_SCHEMA = 'conflict-candidates/v1';
|
|
172
|
+
/** 1.8.x prep 草案写过的 schema:读取时兼容,避免旧行被当坏行。 */
|
|
173
|
+
const LEGACY_CONFLICT_CANDIDATE_SCHEMA = 'hardgate-conflict-candidate/v1';
|
|
174
|
+
export const CONFLICT_CANDIDATES_REL = '.longlive/hardgate/conflict-candidates.jsonl';
|
|
175
|
+
export const CONFLICT_LAST_RUN_REL = '.longlive/hardgate/last-run/conflict-candidates.json';
|
|
176
|
+
export const CONFLICT_CANDIDATE_REASON = 'rule-v1';
|
|
177
|
+
export const CONFLICT_ACCEPT_KIND = 'conflict-accept';
|
|
178
|
+
export const AUTO_AUTHZ_SCHEMA = 'auto-authz/v1';
|
|
179
|
+
export const AUTO_AUTHZ_REL = '.longlive/hardgate/auto-authz.jsonl';
|
|
180
|
+
export const AUTO_AUTHZ_MAX_ROWS = 50000;
|
|
181
|
+
export const AUTO_AUTHZ_RETENTION_DAYS = 180;
|
|
182
|
+
export const EDGES_REL = '.longlive/recall/edges.jsonl';
|
|
183
|
+
export const LINKS_REL = '.longlive/recall/links.jsonl';
|
|
184
|
+
export const D14_GATE_EVENT = 'hg.d14.fail';
|
|
185
|
+
|
|
186
|
+
export const CONFLICT_CANDIDATE_DEFAULTS = Object.freeze({
|
|
187
|
+
enabled: true,
|
|
188
|
+
sameTopicConf: 0.5,
|
|
189
|
+
minSharedTerms: 2,
|
|
190
|
+
maxPairs: 32,
|
|
191
|
+
maxPending: 200,
|
|
192
|
+
retentionDays: 90,
|
|
193
|
+
scopePrefix: 'topics/',
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
/** 对称边类型:去重与查重都按无序卡对。 */
|
|
197
|
+
const SYMMETRIC_EDGE_TYPES = new Set(['conflicts_with', 'same_topic', 'answers_with', 'mentions']);
|
|
198
|
+
/** appendConflictEdge 只允许写冲突边:type 白名单(§4③)。 */
|
|
199
|
+
const CONFLICT_EDGE_TYPES = Object.freeze(['conflicts_with']);
|
|
200
|
+
|
|
201
|
+
function conflictCfgOf(config = {}) {
|
|
202
|
+
const overrides = config && typeof config === 'object' ? config?.hardgate?.conflicts : null;
|
|
203
|
+
return { ...CONFLICT_CANDIDATE_DEFAULTS, ...(overrides && typeof overrides === 'object' ? overrides : {}) };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function resolveMemoryRoot(value, required = true) {
|
|
207
|
+
const root = typeof value === 'string' && value.trim() !== '' ? path.resolve(value) : '';
|
|
208
|
+
if (root === '' && required) {
|
|
209
|
+
throw Object.assign(new Error('E_HG_NO_MEMORY_ROOT: memoryRoot required'), { code: 'E_HG_NO_MEMORY_ROOT' });
|
|
210
|
+
}
|
|
211
|
+
return root;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** 卡路径归一:反斜杠→斜杠、去 ./、去绝对 root 前缀。 */
|
|
215
|
+
export function conflictCardRel(value, memoryRoot = '') {
|
|
216
|
+
let rel = String(value ?? '').trim().replace(/\\/g, '/');
|
|
217
|
+
if (rel === '') return '';
|
|
218
|
+
const root = String(memoryRoot ?? '').trim().replace(/\\/g, '/').replace(/\/+$/, '');
|
|
219
|
+
if (root !== '' && rel.toLowerCase().startsWith(`${root.toLowerCase()}/`)) rel = rel.slice(root.length + 1);
|
|
220
|
+
return rel.replace(/^\.\//, '').replace(/\/{2,}/g, '/');
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** 无序卡对键(路径字典序,同一对永远同 key)。 */
|
|
224
|
+
export function conflictPairKey(aCard, bCard) {
|
|
225
|
+
const left = conflictCardRel(aCard);
|
|
226
|
+
const right = conflictCardRel(bCard);
|
|
227
|
+
return left <= right ? `${left}\u0000${right}` : `${right}\u0000${left}`;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
export function conflictCandidateId(aCard, bCard) {
|
|
231
|
+
return `cc_${crypto.createHash('sha256').update(conflictPairKey(aCard, bCard), 'utf8').digest('hex').slice(0, 16)}`;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function toIso(value) {
|
|
235
|
+
if (value instanceof Date) return value.toISOString();
|
|
236
|
+
const date = value === undefined || value === null || value === '' ? new Date() : new Date(value);
|
|
237
|
+
return Number.isFinite(date.getTime()) ? date.toISOString() : new Date().toISOString();
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function sha256OfText(text) {
|
|
241
|
+
return crypto.createHash('sha256').update(String(text), 'utf8').digest('hex');
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function sha256OfFileIfPresent(file) {
|
|
245
|
+
try {
|
|
246
|
+
return sha256OfText(fs.readFileSync(file, 'utf8'));
|
|
247
|
+
} catch {
|
|
248
|
+
return null;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function readJsonlRows(file) {
|
|
253
|
+
let raw;
|
|
254
|
+
try {
|
|
255
|
+
raw = fs.readFileSync(file, 'utf8');
|
|
256
|
+
} catch (error) {
|
|
257
|
+
return { rows: [], bad: 0, missing: String(error?.code ?? '') === 'ENOENT', error: String(error?.code ?? error) };
|
|
258
|
+
}
|
|
259
|
+
const rows = [];
|
|
260
|
+
let bad = 0;
|
|
261
|
+
for (const line of raw.split(/\r?\n/)) {
|
|
262
|
+
if (line.trim() === '') continue;
|
|
263
|
+
try {
|
|
264
|
+
const row = JSON.parse(line);
|
|
265
|
+
if (row && typeof row === 'object') rows.push(row);
|
|
266
|
+
else bad += 1;
|
|
267
|
+
} catch {
|
|
268
|
+
bad += 1;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
return { rows, bad, missing: false, error: null };
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function appendJsonlLines(file, rows) {
|
|
275
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
276
|
+
const fd = fs.openSync(file, 'a');
|
|
277
|
+
try {
|
|
278
|
+
fs.writeSync(fd, rows.map((row) => `${JSON.stringify(row)}\n`).join(''));
|
|
279
|
+
fs.fsyncSync(fd);
|
|
280
|
+
} finally {
|
|
281
|
+
fs.closeSync(fd);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function conflictGateFail(memoryRoot, gate, reason, evidence = null) {
|
|
286
|
+
try {
|
|
287
|
+
appendGateLog(memoryRoot, {
|
|
288
|
+
gate,
|
|
289
|
+
decision: 'fail',
|
|
290
|
+
reason,
|
|
291
|
+
evidence: [evidence && typeof evidence === 'object' ? evidence : { detail: String(evidence ?? '') }],
|
|
292
|
+
});
|
|
293
|
+
} catch {
|
|
294
|
+
/* gate-log 是诊断面:写失败不得掩盖原始错误,也不得静默冒充成功(原始错误照抛)。 */
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function edgeRowsOf(memoryRoot, edgesStore) {
|
|
299
|
+
if (Array.isArray(edgesStore)) return { rows: edgesStore, bad: 0, present: true, file: null };
|
|
300
|
+
if (edgesStore && Array.isArray(edgesStore.edges)) return { rows: edgesStore.edges, bad: 0, present: true, file: null };
|
|
301
|
+
const file = path.join(memoryRoot, ...EDGES_REL.split('/'));
|
|
302
|
+
const store = readJsonlRows(file);
|
|
303
|
+
return { rows: store.rows, bad: store.bad, present: !store.missing, file };
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function linkRowsOf(memoryRoot, linksStore) {
|
|
307
|
+
if (Array.isArray(linksStore)) return { rows: linksStore, bad: 0, present: true };
|
|
308
|
+
if (linksStore && Array.isArray(linksStore.edges)) return { rows: linksStore.edges, bad: 0, present: true };
|
|
309
|
+
if (linksStore && Array.isArray(linksStore.links)) return { rows: linksStore.links, bad: 0, present: true };
|
|
310
|
+
const file = path.join(memoryRoot, ...LINKS_REL.split('/'));
|
|
311
|
+
const store = readJsonlRows(file);
|
|
312
|
+
return { rows: store.rows, bad: store.bad, present: !store.missing };
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function linkCardOf(row) {
|
|
316
|
+
return conflictCardRel(row?.cardPath ?? row?.path ?? row?.card ?? '');
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** links 里两卡共享的主题词(交集按词升序,确定性)。 */
|
|
320
|
+
export function sharedTermsOf(linkRows, aCard, bCard) {
|
|
321
|
+
const a = conflictCardRel(aCard);
|
|
322
|
+
const b = conflictCardRel(bCard);
|
|
323
|
+
const termsA = new Set();
|
|
324
|
+
const termsB = new Set();
|
|
325
|
+
for (const row of Array.isArray(linkRows) ? linkRows : []) {
|
|
326
|
+
const card = linkCardOf(row);
|
|
327
|
+
const term = String(row?.term ?? '').trim();
|
|
328
|
+
if (card === '' || term === '') continue;
|
|
329
|
+
if (card === a) termsA.add(term);
|
|
330
|
+
else if (card === b) termsB.add(term);
|
|
331
|
+
}
|
|
332
|
+
const shared = [];
|
|
333
|
+
for (const term of termsA) if (termsB.has(term)) shared.push(term);
|
|
334
|
+
shared.sort();
|
|
335
|
+
return shared;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
function buildCardMap(cards, memoryRoot) {
|
|
339
|
+
const map = new Map();
|
|
340
|
+
for (const card of Array.isArray(cards) ? cards : []) {
|
|
341
|
+
const rel = conflictCardRel(card?.rel ?? card?.cardPath ?? card?.path ?? card?.card, memoryRoot);
|
|
342
|
+
if (rel !== '') map.set(rel, card);
|
|
343
|
+
}
|
|
344
|
+
return map;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function cardLifecycleOf(rel, cardMap, memoryRoot) {
|
|
348
|
+
const card = cardMap.get(rel);
|
|
349
|
+
const direct = card ? readLifecycle(card) : null;
|
|
350
|
+
if (direct) return direct;
|
|
351
|
+
return memoryRoot === '' ? null : readCardLifecycle(rel, { memoryRoot });
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
function evidenceOfEdge(row) {
|
|
355
|
+
const evidence = row?.evidence;
|
|
356
|
+
if (!evidence || typeof evidence !== 'object') return null;
|
|
357
|
+
const path = conflictCardRel(evidence.path ?? '');
|
|
358
|
+
const lines = Array.isArray(evidence.lines) ? evidence.lines.map(String).join('-') : String(evidence.lines ?? '');
|
|
359
|
+
const quote = String(evidence.quote ?? '').slice(0, 120);
|
|
360
|
+
if (path === '' && lines === '' && quote === '') return null;
|
|
361
|
+
return { path, lines, quote };
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
function frontmatterBlockOf(text) {
|
|
365
|
+
const src = String(text ?? '');
|
|
366
|
+
const body = src.charCodeAt(0) === 0xfeff ? src.slice(1) : src;
|
|
367
|
+
const block = /^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(\r?\n|$)/.exec(body);
|
|
368
|
+
return block ? block[1].trim() : null;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function firstConclusionLineOf(text) {
|
|
372
|
+
const src = String(text ?? '');
|
|
373
|
+
const body = src.charCodeAt(0) === 0xfeff ? src.slice(1) : src;
|
|
374
|
+
const block = /^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(\r?\n|$)/.exec(body);
|
|
375
|
+
const rest = block ? body.slice(block[0].length) : body;
|
|
376
|
+
for (const raw of rest.split(/\r?\n/)) {
|
|
377
|
+
const line = raw.trim();
|
|
378
|
+
if (line === '' || line.startsWith('#')) continue;
|
|
379
|
+
return line.replace(/^[-*>]\s*/, '').trim();
|
|
380
|
+
}
|
|
381
|
+
return '';
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* 结论/frontmatter 是否完全同文。读不到正文时按「不同」处理(fail-open,绝不因此漏候选)。
|
|
386
|
+
*/
|
|
387
|
+
function contentSimilarity(aCard, bCard, cardMap, memoryRoot, cache) {
|
|
388
|
+
const textOf = (rel) => {
|
|
389
|
+
if (cache.has(rel)) return cache.get(rel);
|
|
390
|
+
let text = typeof cardMap.get(rel)?.text === 'string' ? cardMap.get(rel).text : null;
|
|
391
|
+
if (text === null && memoryRoot !== '') {
|
|
392
|
+
try {
|
|
393
|
+
text = fs.readFileSync(path.resolve(memoryRoot, rel), 'utf8');
|
|
394
|
+
} catch {
|
|
395
|
+
text = null;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
cache.set(rel, text);
|
|
399
|
+
return text;
|
|
400
|
+
};
|
|
401
|
+
const textA = textOf(aCard);
|
|
402
|
+
const textB = textOf(bCard);
|
|
403
|
+
if (textA === null || textB === null) return { sameFrontmatter: false, sameConclusion: false, comparable: false };
|
|
404
|
+
const fmA = frontmatterBlockOf(textA);
|
|
405
|
+
const fmB = frontmatterBlockOf(textB);
|
|
406
|
+
const conclusionA = firstConclusionLineOf(textA);
|
|
407
|
+
const conclusionB = firstConclusionLineOf(textB);
|
|
408
|
+
return {
|
|
409
|
+
sameFrontmatter: fmA !== null && fmA === fmB,
|
|
410
|
+
sameConclusion: conclusionA !== '' && conclusionA === conclusionB,
|
|
411
|
+
comparable: true,
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
function emptyConflictCounts() {
|
|
416
|
+
return { sameTopicEdges: 0, sameTopicPairs: 0, eligibleEdges: 0, eligiblePairs: 0, candidateEdges: 0, candidatePairs: 0 };
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
function conflictCountViews(counts) {
|
|
420
|
+
return {
|
|
421
|
+
pairView: { sameTopic: counts.sameTopicPairs, eligible: counts.eligiblePairs, candidates: counts.candidatePairs },
|
|
422
|
+
edgeView: { sameTopic: counts.sameTopicEdges, eligible: counts.eligibleEdges, candidates: counts.candidateEdges },
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/**
|
|
427
|
+
* 检测冲突候选。纯读(不写盘、不改卡、不合并)。
|
|
428
|
+
* 参数可注入 edgesStore/linksStore/cards(夹具)或从 memoryRoot 现读。
|
|
429
|
+
* 返回 {ok,schema,counts,pairView,edgeView,candidates,skippedReasons,limits,...}。
|
|
430
|
+
*/
|
|
431
|
+
export function detectConflictCandidates({
|
|
432
|
+
memoryRoot,
|
|
433
|
+
config = {},
|
|
434
|
+
edgesStore = null,
|
|
435
|
+
linksStore = null,
|
|
436
|
+
cards = null,
|
|
437
|
+
now = new Date(),
|
|
438
|
+
} = {}) {
|
|
439
|
+
let root = '';
|
|
440
|
+
try {
|
|
441
|
+
root = resolveMemoryRoot(memoryRoot);
|
|
442
|
+
} catch (error) {
|
|
443
|
+
return { ok: false, code: 'E_HG_NO_MEMORY_ROOT', message: String(error?.message ?? error), candidates: [], counts: emptyConflictCounts(), skippedReasons: {} };
|
|
444
|
+
}
|
|
445
|
+
const cfg = conflictCfgOf(config);
|
|
446
|
+
if (cfg.enabled === false) {
|
|
447
|
+
return {
|
|
448
|
+
ok: true,
|
|
449
|
+
schema: CONFLICT_CANDIDATE_SCHEMA,
|
|
450
|
+
disabled: true,
|
|
451
|
+
at: toIso(now),
|
|
452
|
+
candidates: [],
|
|
453
|
+
counts: emptyConflictCounts(),
|
|
454
|
+
pairView: { sameTopic: 0, eligible: 0, candidates: 0 },
|
|
455
|
+
edgeView: { sameTopic: 0, eligible: 0, candidates: 0 },
|
|
456
|
+
skippedReasons: { disabled: 1 },
|
|
457
|
+
limits: { sameTopicConf: cfg.sameTopicConf, minSharedTerms: cfg.minSharedTerms, maxPairs: cfg.maxPairs, maxPending: cfg.maxPending },
|
|
458
|
+
};
|
|
459
|
+
}
|
|
460
|
+
const edges = edgeRowsOf(root, edgesStore);
|
|
461
|
+
const links = linkRowsOf(root, linksStore);
|
|
462
|
+
const cardMap = buildCardMap(cards, root);
|
|
463
|
+
const skippedReasons = {};
|
|
464
|
+
const skip = (reason) => {
|
|
465
|
+
skippedReasons[reason] = (skippedReasons[reason] ?? 0) + 1;
|
|
466
|
+
};
|
|
467
|
+
|
|
468
|
+
const conflictPairs = new Set();
|
|
469
|
+
for (const row of edges.rows) {
|
|
470
|
+
if (row?.type !== 'conflicts_with') continue;
|
|
471
|
+
const a = conflictCardRel(row.from, root);
|
|
472
|
+
const b = conflictCardRel(row.to, root);
|
|
473
|
+
if (a !== '' && b !== '' && a !== b) conflictPairs.add(conflictPairKey(a, b));
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
const pairMap = new Map();
|
|
477
|
+
let considered = 0;
|
|
478
|
+
let sameTopicEdges = 0;
|
|
479
|
+
for (const row of edges.rows) {
|
|
480
|
+
if (row?.type !== 'same_topic') continue;
|
|
481
|
+
sameTopicEdges += 1;
|
|
482
|
+
considered += 1;
|
|
483
|
+
const a = conflictCardRel(row.from, root);
|
|
484
|
+
const b = conflictCardRel(row.to, root);
|
|
485
|
+
if (a === '' || b === '' || a === b) {
|
|
486
|
+
skip('selfEdge');
|
|
487
|
+
continue;
|
|
488
|
+
}
|
|
489
|
+
const confidence = Number(row.confidence);
|
|
490
|
+
if (!Number.isFinite(confidence) || confidence < Number(cfg.sameTopicConf)) {
|
|
491
|
+
skip('lowConfidence');
|
|
492
|
+
continue;
|
|
493
|
+
}
|
|
494
|
+
const key = conflictPairKey(a, b);
|
|
495
|
+
let pair = pairMap.get(key);
|
|
496
|
+
if (!pair) {
|
|
497
|
+
const ordered = a <= b ? [a, b] : [b, a];
|
|
498
|
+
pair = { key, aCard: ordered[0], bCard: ordered[1], edges: [] };
|
|
499
|
+
pairMap.set(key, pair);
|
|
500
|
+
}
|
|
501
|
+
pair.edges.push(row);
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
const scoped = (rel) => rel.startsWith(String(cfg.scopePrefix));
|
|
505
|
+
const eligible = [];
|
|
506
|
+
let eligibleEdges = 0;
|
|
507
|
+
for (const pair of pairMap.values()) {
|
|
508
|
+
if (cardLifecycleOf(pair.aCard, cardMap, root) === 'historical' || cardLifecycleOf(pair.bCard, cardMap, root) === 'historical') {
|
|
509
|
+
skip('historicalEndpoint');
|
|
510
|
+
continue;
|
|
511
|
+
}
|
|
512
|
+
if (!scoped(pair.aCard) || !scoped(pair.bCard)) {
|
|
513
|
+
skip('outOfScope');
|
|
514
|
+
continue;
|
|
515
|
+
}
|
|
516
|
+
eligibleEdges += pair.edges.length;
|
|
517
|
+
eligible.push(pair);
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
const sharedCache = new Map();
|
|
521
|
+
const textCache = new Map();
|
|
522
|
+
const verified = [];
|
|
523
|
+
let candidateEdges = 0;
|
|
524
|
+
for (const pair of eligible) {
|
|
525
|
+
const cacheKey = pair.key;
|
|
526
|
+
if (!sharedCache.has(cacheKey)) sharedCache.set(cacheKey, sharedTermsOf(links.rows, pair.aCard, pair.bCard));
|
|
527
|
+
const sharedTerms = sharedCache.get(cacheKey);
|
|
528
|
+
if (sharedTerms.length < Number(cfg.minSharedTerms)) {
|
|
529
|
+
skip('tooFewSharedTerms');
|
|
530
|
+
continue;
|
|
531
|
+
}
|
|
532
|
+
if (conflictPairs.has(pair.key)) {
|
|
533
|
+
skip('existingConflict');
|
|
534
|
+
continue;
|
|
535
|
+
}
|
|
536
|
+
const similarity = contentSimilarity(pair.aCard, pair.bCard, cardMap, root, textCache);
|
|
537
|
+
if (similarity.sameFrontmatter && similarity.sameConclusion) {
|
|
538
|
+
skip('similarContent');
|
|
539
|
+
continue;
|
|
540
|
+
}
|
|
541
|
+
candidateEdges += pair.edges.length;
|
|
542
|
+
const confidences = pair.edges.map((edge) => Number(edge.confidence)).filter((value) => Number.isFinite(value));
|
|
543
|
+
verified.push({
|
|
544
|
+
id: conflictCandidateId(pair.aCard, pair.bCard),
|
|
545
|
+
pairKey: pair.key,
|
|
546
|
+
aCard: pair.aCard,
|
|
547
|
+
bCard: pair.bCard,
|
|
548
|
+
sharedTerms,
|
|
549
|
+
confidence: confidences.length > 0 ? Math.max(...confidences) : null,
|
|
550
|
+
sameTopicEdges: pair.edges.length,
|
|
551
|
+
evidence: {
|
|
552
|
+
a: evidenceOfEdge(pair.edges[0]),
|
|
553
|
+
b: evidenceOfEdge(pair.edges[pair.edges.length - 1]),
|
|
554
|
+
},
|
|
555
|
+
similarity,
|
|
556
|
+
});
|
|
557
|
+
}
|
|
558
|
+
verified.sort((x, y) => (y.sharedTerms.length - x.sharedTerms.length) || (x.id < y.id ? -1 : x.id > y.id ? 1 : 0));
|
|
559
|
+
const omitted = Math.max(0, verified.length - Math.max(0, Number(cfg.maxPairs) || 0));
|
|
560
|
+
const candidates = omitted > 0 ? verified.slice(0, Number(cfg.maxPairs)) : verified;
|
|
561
|
+
const counts = {
|
|
562
|
+
sameTopicEdges,
|
|
563
|
+
sameTopicPairs: pairMap.size,
|
|
564
|
+
eligibleEdges,
|
|
565
|
+
eligiblePairs: eligible.length,
|
|
566
|
+
candidateEdges,
|
|
567
|
+
candidatePairs: verified.length,
|
|
568
|
+
};
|
|
569
|
+
const views = conflictCountViews(counts);
|
|
570
|
+
return {
|
|
571
|
+
ok: true,
|
|
572
|
+
schema: CONFLICT_CANDIDATE_SCHEMA,
|
|
573
|
+
at: toIso(now),
|
|
574
|
+
source: 'recall-edges/v1+recall-links/v1',
|
|
575
|
+
counts,
|
|
576
|
+
pairView: views.pairView,
|
|
577
|
+
edgeView: views.edgeView,
|
|
578
|
+
candidates,
|
|
579
|
+
considered,
|
|
580
|
+
omitted,
|
|
581
|
+
skippedReasons,
|
|
582
|
+
badEdges: edges.bad,
|
|
583
|
+
badLinks: links.bad,
|
|
584
|
+
edgesPresent: edges.present,
|
|
585
|
+
linksPresent: links.present,
|
|
586
|
+
limits: {
|
|
587
|
+
sameTopicConf: cfg.sameTopicConf,
|
|
588
|
+
minSharedTerms: cfg.minSharedTerms,
|
|
589
|
+
maxPairs: cfg.maxPairs,
|
|
590
|
+
maxPending: cfg.maxPending,
|
|
591
|
+
retentionDays: cfg.retentionDays,
|
|
592
|
+
scopePrefix: cfg.scopePrefix,
|
|
593
|
+
},
|
|
594
|
+
};
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/** 检测器别名:面板/脚本按扫描语义调用时用这个名字。 */
|
|
598
|
+
export function scanConflictCandidates(input = {}) {
|
|
599
|
+
return detectConflictCandidates(input);
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
/** 1.8.x prep 草案的旧名(read-only 别名),保留兼容。 */
|
|
603
|
+
export function conflictCandidates(input = {}) {
|
|
604
|
+
return detectConflictCandidates(input);
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
// ---- 候选账本(append-only,pending 有界 + 90 天保留) -------------------------
|
|
608
|
+
|
|
609
|
+
export function conflictCandidatesPathOf(memoryRoot) {
|
|
610
|
+
return path.join(resolveMemoryRoot(memoryRoot), ...CONFLICT_CANDIDATES_REL.split('/'));
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
export function conflictLastRunPathOf(memoryRoot) {
|
|
614
|
+
return path.join(resolveMemoryRoot(memoryRoot), ...CONFLICT_LAST_RUN_REL.split('/'));
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
function isCandidateSchema(schema) {
|
|
618
|
+
return schema === CONFLICT_CANDIDATE_SCHEMA || schema === LEGACY_CONFLICT_CANDIDATE_SCHEMA;
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
/**
|
|
622
|
+
* 读候选账本。append-only:同一卡对以最后一行状态为准(pending/accepted/rejected/archived)。
|
|
623
|
+
* pending 只算「latest 状态 = pending 且未过 retentionDays」的行;坏行计数不抛。
|
|
624
|
+
*/
|
|
625
|
+
export function readConflictCandidates({ memoryRoot, config = {}, now = new Date() } = {}) {
|
|
626
|
+
const root = resolveMemoryRoot(memoryRoot);
|
|
627
|
+
const cfg = conflictCfgOf(config);
|
|
628
|
+
const file = path.join(root, ...CONFLICT_CANDIDATES_REL.split('/'));
|
|
629
|
+
const store = readJsonlRows(file);
|
|
630
|
+
const rows = [];
|
|
631
|
+
let bad = store.bad;
|
|
632
|
+
for (const row of store.rows) {
|
|
633
|
+
if (isCandidateSchema(row?.schema) && typeof row.id === 'string' && typeof row.aCard === 'string' && typeof row.bCard === 'string') rows.push(row);
|
|
634
|
+
else bad += 1;
|
|
635
|
+
}
|
|
636
|
+
const byPair = new Map();
|
|
637
|
+
for (const row of rows) {
|
|
638
|
+
const key = conflictPairKey(row.aCard, row.bCard);
|
|
639
|
+
if (key !== '\u0000') byPair.set(key, row);
|
|
640
|
+
}
|
|
641
|
+
const nowMs = new Date(toIso(now)).getTime();
|
|
642
|
+
const retentionMs = Math.max(0, Number(cfg.retentionDays) || 0) * 24 * 60 * 60 * 1000;
|
|
643
|
+
const pending = [];
|
|
644
|
+
for (const row of byPair.values()) {
|
|
645
|
+
if (row.state !== 'pending') continue;
|
|
646
|
+
const atMs = new Date(String(row.at ?? '')).getTime();
|
|
647
|
+
const fresh = !Number.isFinite(atMs) || retentionMs === 0 || nowMs - atMs <= retentionMs;
|
|
648
|
+
if (fresh) pending.push(row);
|
|
649
|
+
}
|
|
650
|
+
return { ok: true, file, rows, bad, missing: store.missing, byPair, pending, pendingCount: pending.length };
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
/**
|
|
654
|
+
* 追加候选/裁决行(只 append)。
|
|
655
|
+
* - state='pending':任何已出现过的卡对(含 archived/accepted/rejected)不再重复提议;
|
|
656
|
+
* - state='accepted'|'rejected':同状态重复裁决幂等(不写第二行);
|
|
657
|
+
* - pending 超过 maxPending 时,把最老的 pending 追加 archived 行(有界)。
|
|
658
|
+
*/
|
|
659
|
+
export function appendConflictCandidates({
|
|
660
|
+
memoryRoot,
|
|
661
|
+
candidates = [],
|
|
662
|
+
config = {},
|
|
663
|
+
now = new Date(),
|
|
664
|
+
state = 'pending',
|
|
665
|
+
reason = null,
|
|
666
|
+
actor = null,
|
|
667
|
+
} = {}) {
|
|
668
|
+
const root = resolveMemoryRoot(memoryRoot);
|
|
669
|
+
const cfg = conflictCfgOf(config);
|
|
670
|
+
const at = toIso(now);
|
|
671
|
+
const ledger = readConflictCandidates({ memoryRoot: root, config, now });
|
|
672
|
+
const latest = ledger.byPair;
|
|
673
|
+
const fresh = [];
|
|
674
|
+
for (const candidate of Array.isArray(candidates) ? candidates : []) {
|
|
675
|
+
const aCard = conflictCardRel(candidate?.aCard, root);
|
|
676
|
+
const bCard = conflictCardRel(candidate?.bCard, root);
|
|
677
|
+
if (aCard === '' || bCard === '' || aCard === bCard) continue;
|
|
678
|
+
const pairKey = conflictPairKey(aCard, bCard);
|
|
679
|
+
const id = typeof candidate?.id === 'string' && candidate.id.trim() !== '' ? candidate.id.trim() : conflictCandidateId(aCard, bCard);
|
|
680
|
+
const previous = latest.get(pairKey);
|
|
681
|
+
if (state === 'pending') {
|
|
682
|
+
if (previous) continue;
|
|
683
|
+
} else if (previous && previous.state === state) {
|
|
684
|
+
continue;
|
|
685
|
+
}
|
|
686
|
+
const row = {
|
|
687
|
+
schema: CONFLICT_CANDIDATE_SCHEMA,
|
|
688
|
+
id,
|
|
689
|
+
at,
|
|
690
|
+
aCard,
|
|
691
|
+
bCard,
|
|
692
|
+
sharedTerms: Array.isArray(candidate?.sharedTerms) ? candidate.sharedTerms.map(String) : [],
|
|
693
|
+
confidence: Number.isFinite(Number(candidate?.confidence)) ? Number(candidate.confidence) : null,
|
|
694
|
+
evidence: candidate?.evidence && typeof candidate.evidence === 'object' ? candidate.evidence : { a: null, b: null },
|
|
695
|
+
reason: state === 'pending' ? CONFLICT_CANDIDATE_REASON : String(reason ?? state),
|
|
696
|
+
state,
|
|
697
|
+
};
|
|
698
|
+
if (actor !== null && actor !== undefined && String(actor).trim() !== '') row.actor = String(actor);
|
|
699
|
+
fresh.push(row);
|
|
700
|
+
}
|
|
701
|
+
const pendingRows = [];
|
|
702
|
+
for (const row of latest.values()) if (row.state === 'pending') pendingRows.push(row);
|
|
703
|
+
for (const row of fresh) if (row.state === 'pending') pendingRows.push(row);
|
|
704
|
+
pendingRows.sort((x, y) => String(x.at ?? '').localeCompare(String(y.at ?? '')) || String(x.id).localeCompare(String(y.id)));
|
|
705
|
+
const overflow = Math.max(0, pendingRows.length - Math.max(0, Number(cfg.maxPending) || 0));
|
|
706
|
+
const archivedRows = [];
|
|
707
|
+
for (let index = 0; index < overflow; index += 1) {
|
|
708
|
+
const row = pendingRows[index];
|
|
709
|
+
if (row) archivedRows.push({ ...row, state: 'archived', archivedAt: at, reason: 'pending-cap' });
|
|
710
|
+
}
|
|
711
|
+
const rows = [...fresh, ...archivedRows];
|
|
712
|
+
const pendingAfter = pendingRows.length - overflow;
|
|
713
|
+
if (rows.length === 0) {
|
|
714
|
+
return { ok: true, file: ledger.file, written: 0, archived: 0, pending: pendingAfter, corrupt: ledger.bad };
|
|
715
|
+
}
|
|
716
|
+
try {
|
|
717
|
+
appendJsonlLines(ledger.file, rows);
|
|
718
|
+
return { ok: true, file: ledger.file, written: fresh.length, archived: archivedRows.length, pending: pendingAfter, corrupt: ledger.bad };
|
|
719
|
+
} catch (error) {
|
|
720
|
+
conflictGateFail(root, D14_GATE_EVENT, 'E_HG_CONFLICT_WRITE', { code: String(error?.code ?? error) });
|
|
721
|
+
return { ok: false, code: 'E_HG_CONFLICT_WRITE', message: String(error?.message ?? error), file: ledger.file, written: 0, archived: 0, pending: pendingAfter };
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
export function readConflictLastRun(memoryRoot) {
|
|
726
|
+
try {
|
|
727
|
+
const parsed = JSON.parse(fs.readFileSync(conflictLastRunPathOf(memoryRoot), 'utf8'));
|
|
728
|
+
return parsed && typeof parsed === 'object' ? parsed : null;
|
|
729
|
+
} catch {
|
|
730
|
+
return null;
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
function writeConflictLastRun({ memoryRoot, now, summary }) {
|
|
735
|
+
const file = conflictLastRunPathOf(memoryRoot);
|
|
736
|
+
const at = toIso(now);
|
|
737
|
+
const body = { schema: CONFLICT_CANDIDATE_SCHEMA, at, day: at.slice(0, 10), ...summary };
|
|
738
|
+
try {
|
|
739
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
740
|
+
const tmp = `${file}.tmp-${process.pid}`;
|
|
741
|
+
fs.writeFileSync(tmp, `${JSON.stringify(body)}\n`, 'utf8');
|
|
742
|
+
fs.renameSync(tmp, file);
|
|
743
|
+
return { ok: true, body };
|
|
744
|
+
} catch (error) {
|
|
745
|
+
conflictGateFail(memoryRoot, D14_GATE_EVENT, 'E_HG_CONFLICT_LASTRUN_WRITE', { code: String(error?.code ?? error) });
|
|
746
|
+
return { ok: false, code: 'E_HG_CONFLICT_LASTRUN_WRITE' };
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
export function shouldRunConflictCandidates({ memoryRoot, now = new Date(), config = {} } = {}) {
|
|
751
|
+
const cfg = conflictCfgOf(config);
|
|
752
|
+
if (cfg.enabled === false) return false;
|
|
753
|
+
const last = readConflictLastRun(memoryRoot);
|
|
754
|
+
if (!last) return true;
|
|
755
|
+
return last.day !== toIso(now).slice(0, 10);
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
/** 每日 pre-step job:一天一次(last-run 幂等),只产候选、不合并、不改卡。 */
|
|
759
|
+
export function runConflictCandidateJob({
|
|
760
|
+
memoryRoot,
|
|
761
|
+
config = {},
|
|
762
|
+
now = new Date(),
|
|
763
|
+
cards = null,
|
|
764
|
+
edgesStore = null,
|
|
765
|
+
linksStore = null,
|
|
766
|
+
} = {}) {
|
|
767
|
+
const root = resolveMemoryRoot(memoryRoot);
|
|
768
|
+
const at = toIso(now);
|
|
769
|
+
const last = readConflictLastRun(root);
|
|
770
|
+
if (last && last.day === at.slice(0, 10)) return { ok: true, skipped: true, reason: 'already-ran-today', lastRun: last };
|
|
771
|
+
const detected = detectConflictCandidates({ memoryRoot: root, config, cards, edgesStore, linksStore, now: at });
|
|
772
|
+
if (detected.ok !== true) return detected;
|
|
773
|
+
const appended = appendConflictCandidates({ memoryRoot: root, candidates: detected.candidates, config, now: at, state: 'pending' });
|
|
774
|
+
const summary = {
|
|
775
|
+
created: appended.written ?? 0,
|
|
776
|
+
archived: appended.archived ?? 0,
|
|
777
|
+
considered: detected.considered ?? 0,
|
|
778
|
+
pending: appended.pending ?? 0,
|
|
779
|
+
skippedReasons: detected.skippedReasons ?? {},
|
|
780
|
+
counts: detected.counts,
|
|
781
|
+
pairView: detected.pairView,
|
|
782
|
+
edgeView: detected.edgeView,
|
|
783
|
+
};
|
|
784
|
+
const lastRun = writeConflictLastRun({ memoryRoot: root, now: at, summary });
|
|
785
|
+
return { ok: appended.ok !== false, ...summary, lastRun: lastRun.body ?? null };
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
// ---- accept:appendConflictEdge(校验 + 幂等 + 1 边 + 1 审计行) ----------------
|
|
789
|
+
|
|
790
|
+
function resolveActors(value) {
|
|
791
|
+
if (value === null || value === undefined) return null;
|
|
792
|
+
if (typeof value === 'string') return value.trim() === '' ? null : value.trim();
|
|
793
|
+
if (typeof value === 'object') return value;
|
|
794
|
+
return String(value);
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
function actorLabelOf(value) {
|
|
798
|
+
const actor = resolveActors(value);
|
|
799
|
+
if (actor === null) return 'memory_conflicts';
|
|
800
|
+
if (typeof actor === 'string') return actor;
|
|
801
|
+
const kind = typeof actor.kind === 'string' ? actor.kind : 'host';
|
|
802
|
+
const id = typeof actor.id === 'string' && actor.id.trim() !== '' ? actor.id.trim() : null;
|
|
803
|
+
return id ? `${kind}:${id}` : kind;
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
function pruneAutoAuthz(file, now) {
|
|
807
|
+
const store = readJsonlRows(file);
|
|
808
|
+
if (store.missing || store.bad > 0) return { rows: store.rows.length, dropped: 0 };
|
|
809
|
+
const cutoff = new Date(toIso(now)).getTime() - AUTO_AUTHZ_RETENTION_DAYS * 24 * 60 * 60 * 1000;
|
|
810
|
+
const keep = store.rows.filter((row) => {
|
|
811
|
+
const atMs = new Date(String(row.ts ?? row.at ?? '')).getTime();
|
|
812
|
+
return !Number.isFinite(atMs) || atMs >= cutoff;
|
|
813
|
+
});
|
|
814
|
+
const dropped = store.rows.length - keep.length;
|
|
815
|
+
if (dropped > 0) {
|
|
816
|
+
const tmp = `${file}.tmp-${process.pid}`;
|
|
817
|
+
fs.writeFileSync(tmp, keep.map((row) => `${JSON.stringify(row)}\n`).join(''), 'utf8');
|
|
818
|
+
fs.renameSync(tmp, file);
|
|
819
|
+
}
|
|
820
|
+
return { rows: keep.length, dropped };
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
function rotateAutoAuthzIfNeeded(file, now) {
|
|
824
|
+
const store = readJsonlRows(file);
|
|
825
|
+
if (store.missing) return;
|
|
826
|
+
const pruned = pruneAutoAuthz(file, now);
|
|
827
|
+
if (pruned.rows < AUTO_AUTHZ_MAX_ROWS) return;
|
|
828
|
+
const rotated = `${file}.1`;
|
|
829
|
+
try {
|
|
830
|
+
fs.rmSync(rotated, { force: true });
|
|
831
|
+
} catch {
|
|
832
|
+
/* 旧归档删不掉就覆盖写 */
|
|
833
|
+
}
|
|
834
|
+
fs.renameSync(file, rotated);
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
/**
|
|
838
|
+
* accept 一条冲突边:校验双卡存在 + type 白名单 + 幂等去重;
|
|
839
|
+
* append 恰 1 条边到 `.longlive/recall/edges.jsonl`;
|
|
840
|
+
* append 恰 1 行 kind=conflict-accept 审计到 `.longlive/hardgate/auto-authz.jsonl`。
|
|
841
|
+
* 返回 {ok,edge,auditPath,edgePath,auditRow,beforeSha,afterSha};
|
|
842
|
+
* 非法 → E_HG_EDGE_INVALID,重复 → E_HG_EDGE_DUP(都写 hg.d14.fail 事件)。
|
|
843
|
+
*/
|
|
844
|
+
export function appendConflictEdge(memoryRoot, input = {}, options = {}) {
|
|
845
|
+
let root;
|
|
846
|
+
const fail = (code, detail) => {
|
|
847
|
+
const message = `${code}${detail ? `: ${detail}` : ''}`;
|
|
848
|
+
if (typeof root === 'string' && root !== '') conflictGateFail(root, D14_GATE_EVENT, code, { detail: String(detail ?? '') });
|
|
849
|
+
const error = new Error(message);
|
|
850
|
+
error.code = code;
|
|
851
|
+
error.detail = detail;
|
|
852
|
+
throw error;
|
|
853
|
+
};
|
|
854
|
+
try {
|
|
855
|
+
root = resolveMemoryRoot(memoryRoot);
|
|
856
|
+
} catch {
|
|
857
|
+
fail('E_HG_EDGE_INVALID', 'memoryRoot required');
|
|
858
|
+
}
|
|
859
|
+
const from = conflictCardRel(input?.from ?? input?.aCard, root);
|
|
860
|
+
const to = conflictCardRel(input?.to ?? input?.bCard, root);
|
|
861
|
+
if (from === '' || to === '') fail('E_HG_EDGE_INVALID', 'from/to required');
|
|
862
|
+
if (from === to) fail('E_HG_EDGE_INVALID', 'self edge is not a conflict');
|
|
863
|
+
const type = typeof input?.type === 'string' && input.type.trim() !== '' ? input.type.trim() : 'conflicts_with';
|
|
864
|
+
if (!CONFLICT_EDGE_TYPES.includes(type)) fail('E_HG_EDGE_INVALID', `type not allowed: ${type} (allowed: ${CONFLICT_EDGE_TYPES.join(', ')})`);
|
|
865
|
+
const confidence = input?.confidence === undefined || input?.confidence === null ? 1 : Number(input.confidence);
|
|
866
|
+
if (!Number.isFinite(confidence) || confidence < 0 || confidence > 1) fail('E_HG_EDGE_INVALID', `confidence out of range: ${input?.confidence}`);
|
|
867
|
+
for (const rel of [from, to]) {
|
|
868
|
+
const abs = path.resolve(root, rel);
|
|
869
|
+
const inside = path.relative(root, abs);
|
|
870
|
+
if (inside.startsWith('..') || path.isAbsolute(inside)) fail('E_HG_EDGE_INVALID', `outside memoryRoot: ${rel}`);
|
|
871
|
+
let stat = null;
|
|
872
|
+
try {
|
|
873
|
+
stat = fs.statSync(abs);
|
|
874
|
+
} catch {
|
|
875
|
+
stat = null;
|
|
876
|
+
}
|
|
877
|
+
if (!stat || !stat.isFile()) fail('E_HG_EDGE_INVALID', `card missing: ${rel}`);
|
|
878
|
+
}
|
|
879
|
+
const source = typeof input?.source === 'string' && input.source.trim() !== '' ? input.source.trim() : 'conflict-candidates';
|
|
880
|
+
const evidence = input?.evidence === undefined || input?.evidence === null ? null : normalizeEvidence(input.evidence);
|
|
881
|
+
const edgesFile = path.join(root, ...EDGES_REL.split('/'));
|
|
882
|
+
const existing = readJsonlRows(edgesFile);
|
|
883
|
+
const symmetric = SYMMETRIC_EDGE_TYPES.has(type);
|
|
884
|
+
const wantedKey = symmetric ? conflictPairKey(from, to) : `${from}\u0000${to}`;
|
|
885
|
+
const duplicate = existing.rows.find((row) => {
|
|
886
|
+
if (row?.type !== type) return false;
|
|
887
|
+
const a = conflictCardRel(row.from, root);
|
|
888
|
+
const b = conflictCardRel(row.to, root);
|
|
889
|
+
if (a === '' || b === '') return false;
|
|
890
|
+
return (symmetric ? conflictPairKey(a, b) : `${a}\u0000${b}`) === wantedKey;
|
|
891
|
+
});
|
|
892
|
+
if (duplicate) {
|
|
893
|
+
fail('E_HG_EDGE_DUP', `edge already exists: ${from} -> ${to} (${type})`);
|
|
894
|
+
}
|
|
895
|
+
const now = options?.now ?? input?.now ?? new Date();
|
|
896
|
+
const at = toIso(now);
|
|
897
|
+
const beforeSha = sha256OfFileIfPresent(edgesFile);
|
|
898
|
+
const edge = {
|
|
899
|
+
from,
|
|
900
|
+
to,
|
|
901
|
+
type,
|
|
902
|
+
evidence,
|
|
903
|
+
confidence,
|
|
904
|
+
source,
|
|
905
|
+
created_at: at,
|
|
906
|
+
};
|
|
907
|
+
try {
|
|
908
|
+
appendJsonlLines(edgesFile, [edge]);
|
|
909
|
+
} catch (error) {
|
|
910
|
+
fail('E_HG_EDGE_WRITE', String(error?.message ?? error));
|
|
911
|
+
}
|
|
912
|
+
const afterSha = sha256OfFileIfPresent(edgesFile);
|
|
913
|
+
let auditPath = null;
|
|
914
|
+
let auditRow = null;
|
|
915
|
+
if (options?.audit !== false) {
|
|
916
|
+
auditPath = path.join(root, ...AUTO_AUTHZ_REL.split('/'));
|
|
917
|
+
const actorLabel = actorLabelOf(options?.actor ?? input?.actor);
|
|
918
|
+
auditRow = {
|
|
919
|
+
schema: AUTO_AUTHZ_SCHEMA,
|
|
920
|
+
ts: at,
|
|
921
|
+
kind: CONFLICT_ACCEPT_KIND,
|
|
922
|
+
actor: actorLabel,
|
|
923
|
+
target: `${from} -> ${to}`,
|
|
924
|
+
from,
|
|
925
|
+
to,
|
|
926
|
+
type,
|
|
927
|
+
confidence,
|
|
928
|
+
source,
|
|
929
|
+
paramsSha: sha256OfText(JSON.stringify({ from, to, type, confidence, source, evidence })),
|
|
930
|
+
verdict: 'accepted',
|
|
931
|
+
ruleHits: [],
|
|
932
|
+
reason: 'memory_conflicts.accept',
|
|
933
|
+
beforeSha,
|
|
934
|
+
afterSha,
|
|
935
|
+
result: 'appended',
|
|
936
|
+
edgeId: conflictCandidateId(from, to),
|
|
937
|
+
};
|
|
938
|
+
try {
|
|
939
|
+
rotateAutoAuthzIfNeeded(auditPath, at);
|
|
940
|
+
appendJsonlLines(auditPath, [auditRow]);
|
|
941
|
+
} catch (error) {
|
|
942
|
+
fail('E_HG_EDGE_AUDIT', `audit row not written (fail-closed): ${String(error?.message ?? error)}`);
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
return { ok: true, edge, edgePath: edgesFile, auditPath, auditRow, beforeSha, afterSha };
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
/** d14 夹具/旧调用名:acceptConflict 与 appendConflictEdge 同实现。 */
|
|
949
|
+
export function acceptConflict(memoryRoot, input = {}, options = {}) {
|
|
950
|
+
return appendConflictEdge(memoryRoot, input, options);
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
// ---- memory_conflicts action:list / accept / reject -------------------------
|
|
954
|
+
|
|
955
|
+
function resolveConflictTarget(args, memoryRoot) {
|
|
956
|
+
const ledger = readConflictCandidates({ memoryRoot });
|
|
957
|
+
const id = typeof args?.id === 'string' && args.id.trim() !== '' ? args.id.trim() : '';
|
|
958
|
+
if (id !== '') {
|
|
959
|
+
const row = ledger.rows.find((candidate) => candidate.id === id);
|
|
960
|
+
if (row) return { id, aCard: row.aCard, bCard: row.bCard, sharedTerms: Array.isArray(row.sharedTerms) ? row.sharedTerms : [], row };
|
|
961
|
+
}
|
|
962
|
+
const aCard = conflictCardRel(args?.from ?? args?.aCard, memoryRoot);
|
|
963
|
+
const bCard = conflictCardRel(args?.to ?? args?.bCard, memoryRoot);
|
|
964
|
+
if (aCard === '' || bCard === '') {
|
|
965
|
+
const error = new Error('E_HG_EDGE_INVALID: accept/reject needs id or from/to');
|
|
966
|
+
error.code = 'E_HG_EDGE_INVALID';
|
|
967
|
+
throw error;
|
|
968
|
+
}
|
|
969
|
+
return { id: id !== '' ? id : conflictCandidateId(aCard, bCard), aCard, bCard, sharedTerms: [], row: null };
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
/**
|
|
973
|
+
* memory_conflicts 的 action 实现(工具壳只做 root 校验与转发)。
|
|
974
|
+
* - list:统一冲突视图 + 当前候选(对/边两口径)+ pending 账本计数;只读。
|
|
975
|
+
* - accept:appendConflictEdge(1 边 + 1 auto-authz 行),并把候选置 accepted。
|
|
976
|
+
* - reject:不写边、不写审计,只把候选置 rejected。
|
|
977
|
+
*/
|
|
978
|
+
export function memoryConflicts(args = {}) {
|
|
979
|
+
const root = resolveMemoryRoot(args?.memoryRoot);
|
|
980
|
+
const action = typeof args?.action === 'string' && args.action.trim() !== '' ? args.action.trim() : 'list';
|
|
981
|
+
const config = args?.config && typeof args.config === 'object' ? args.config : {};
|
|
982
|
+
if (action === 'list') {
|
|
983
|
+
const view = unifiedConflicts({ memoryRoot: root, includeLifecycle: args?.includeLifecycle === true });
|
|
984
|
+
const detected = detectConflictCandidates({ memoryRoot: root, config });
|
|
985
|
+
const ledger = readConflictCandidates({ memoryRoot: root, config });
|
|
986
|
+
return {
|
|
987
|
+
ok: true,
|
|
988
|
+
action: 'list',
|
|
989
|
+
...view,
|
|
990
|
+
candidates: detected.candidates ?? [],
|
|
991
|
+
counts: detected.counts ?? emptyConflictCounts(),
|
|
992
|
+
pairView: detected.pairView ?? null,
|
|
993
|
+
edgeView: detected.edgeView ?? null,
|
|
994
|
+
skippedReasons: detected.skippedReasons ?? {},
|
|
995
|
+
limits: detected.limits ?? null,
|
|
996
|
+
pending: { rows: ledger.pendingCount, cap: conflictCfgOf(config).maxPending, retentionDays: conflictCfgOf(config).retentionDays },
|
|
997
|
+
ledger: { file: ledger.file, missing: ledger.missing, bad: ledger.bad, rows: ledger.rows.length },
|
|
998
|
+
};
|
|
999
|
+
}
|
|
1000
|
+
if (action === 'accept') {
|
|
1001
|
+
const target = resolveConflictTarget(args, root);
|
|
1002
|
+
const accepted = appendConflictEdge(
|
|
1003
|
+
root,
|
|
1004
|
+
{
|
|
1005
|
+
from: target.aCard,
|
|
1006
|
+
to: target.bCard,
|
|
1007
|
+
type: 'conflicts_with',
|
|
1008
|
+
evidence: args?.evidence,
|
|
1009
|
+
confidence: args?.confidence,
|
|
1010
|
+
source: args?.source ?? 'conflict-candidates',
|
|
1011
|
+
},
|
|
1012
|
+
{ actor: args?.actor, audit: args?.audit !== false, now: args?.now },
|
|
1013
|
+
);
|
|
1014
|
+
const ledger = appendConflictCandidates({
|
|
1015
|
+
memoryRoot: root,
|
|
1016
|
+
candidates: [{ id: target.id, aCard: target.aCard, bCard: target.bCard, sharedTerms: target.sharedTerms, confidence: accepted.edge.confidence }],
|
|
1017
|
+
config,
|
|
1018
|
+
now: args?.now ?? new Date(),
|
|
1019
|
+
state: 'accepted',
|
|
1020
|
+
reason: 'memory_conflicts.accept',
|
|
1021
|
+
actor: actorLabelOf(args?.actor),
|
|
1022
|
+
});
|
|
1023
|
+
return {
|
|
1024
|
+
ok: true,
|
|
1025
|
+
action: 'accept',
|
|
1026
|
+
accepted: true,
|
|
1027
|
+
id: target.id,
|
|
1028
|
+
aCard: target.aCard,
|
|
1029
|
+
bCard: target.bCard,
|
|
1030
|
+
edge: accepted.edge,
|
|
1031
|
+
auditPath: accepted.auditPath,
|
|
1032
|
+
edgePath: accepted.edgePath,
|
|
1033
|
+
ledger: { file: ledger.file, written: ledger.written, pending: ledger.pending, state: 'accepted' },
|
|
1034
|
+
};
|
|
1035
|
+
}
|
|
1036
|
+
if (action === 'reject') {
|
|
1037
|
+
const target = resolveConflictTarget(args, root);
|
|
1038
|
+
const ledger = appendConflictCandidates({
|
|
1039
|
+
memoryRoot: root,
|
|
1040
|
+
candidates: [{ id: target.id, aCard: target.aCard, bCard: target.bCard, sharedTerms: target.sharedTerms }],
|
|
1041
|
+
config,
|
|
1042
|
+
now: args?.now ?? new Date(),
|
|
1043
|
+
state: 'rejected',
|
|
1044
|
+
reason: typeof args?.reason === 'string' && args.reason.trim() !== '' ? args.reason.trim() : 'rejected-by-user',
|
|
1045
|
+
actor: actorLabelOf(args?.actor),
|
|
1046
|
+
});
|
|
1047
|
+
return {
|
|
1048
|
+
ok: true,
|
|
1049
|
+
action: 'reject',
|
|
1050
|
+
rejected: true,
|
|
1051
|
+
id: target.id,
|
|
1052
|
+
aCard: target.aCard,
|
|
1053
|
+
bCard: target.bCard,
|
|
1054
|
+
ledger: { file: ledger.file, written: ledger.written, pending: ledger.pending, state: 'rejected' },
|
|
1055
|
+
};
|
|
1056
|
+
}
|
|
1057
|
+
const error = new Error(`E_HG_CONFLICT_ACTION: unknown action ${action}`);
|
|
1058
|
+
error.code = 'E_HG_CONFLICT_ACTION';
|
|
1059
|
+
throw error;
|
|
1060
|
+
}
|